NullPointerException on findViewById from Fragment



我一直在处理这个问题,即使在尝试从已经提出的问题中实现其他想法之后,我也无法让它工作。

我正在处理碎片。我正在尝试从我选择的片段中找到一个视图,并在onStart()中调用的方法中使用它。这是它的外观:

@Override
protected void onStart() {
    super.onStart();
    Log.e(TAG, "On start");
    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
    }
    else {
        if (mCommandService == null) 
            setupCommand();
    }
}
private void setupCommand() {
    Log.d(TAG, "setupChat()");
    mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
    mConversationView = (ListView) findViewById(R.id.in);
    mConversationView.setAdapter(mConversationArrayAdapter);
    mOutEditText = (EditText) findViewById(R.id.edit_text_out);
    mOutEditText.setOnEditorActionListener(mWriteListener);
    mSendButton = (Button) findViewById(R.id.action_send);
    mSendButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Send a message using content of the edit text widget
            TextView view = (TextView) findViewById(R.id.edit_text_out);
            String message = view.getText().toString();
            sendMessage(message);
        }
    });
    mCommandService = new CommandService(this, mHandler);
    mOutStringBuffer = new StringBuffer("");
}
@SuppressLint("ValidFragment")
public class SendSectionFragment extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.send, container, false);
            rootView.findViewById(R.id.action_send)
            .setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                }
            });
            return rootView;
        }
    }

SendSectionFragment片段正在使用自己的.xml。我想做的是引用SendSectionFragment.xml ListView。导致麻烦的原因:

01-06 18:05:21.259: E/AndroidRuntime(17868): Caused by: java.lang.NullPointerException
01-06 18:05:21.259: E/AndroidRuntime(17868):    at com.receive.bluereceive.Main.setupCommand(Main.java:244)
01-06 18:05:21.259: E/AndroidRuntime(17868):    at com.receive.bluereceive.Main.onStart(Main.java:217)

其中 217 表示setupCommand();,244 表示mConversationView.setAdapter(mConversationArrayAdapter);

我该如何处理?SendSectionFragment不是我的应用程序的主要部分。

从 setupCommand() 中删除此行 -

mConversationView = (ListView) findViewById(R.id.in);

它在onCreateView()中,像这样-

mConversationView = (ListView) rootView.findViewById(R.id.in);

最新更新