簡體   English   中英

片段上findViewById的NullPointerException

[英]NullPointerException on findViewById from Fragment

我對這個問題的處理方式太多了,即使嘗試從已經提出的問題中實施其他想法后,我也無法使它起作用。

我正在研究片段。 我試圖從我選擇的片段中找到一個視圖,並在onStart()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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM