使用getExtra() - NullPointerException

时间:2014-09-09 18:52:02

标签: java android android-activity android-fragments nullpointerexception

我有一个onItemClick - 方法的片段,我在其中调用另一个Activity并传​​递id参数:

public class MoviesListFragment extends Fragment {
  // some code
  listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView mid = (TextView) view.findViewById(R.id.textID);
                Intent intent = new Intent(getActivity().getBaseContext(), InfoActivity.class);
                intent.putExtra("id", mid.getText());
                startActivity(intent);
            }
        });
}

所以,在另一个活动(InfoActivity.java)中我试图获得id - 值:

public class InfoActivity extends Activity {

    Intent intent = getIntent();
    private final String id = intent.getStringExtra("id");
    // some code

并在此行中获得例外:intent.getStringExtra("id");

我犯了错误?

2 个答案:

答案 0 :(得分:1)

此代码:

Intent intent = getIntent();
private final String id = intent.getStringExtra("id");

应该从onCreate()或类似方法内部调用,否则在创建Activity对象之前调用它,然后将意图传递给它。

答案 1 :(得分:1)

 private final String id;
 public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.table);
        Intent intent = getIntent();
         id = intent.getStringExtra("id");

    }