按下后退按钮时如何恢复ListView并获取列表内容?

时间:2016-10-17 09:16:22

标签: android listview android-fragments android-adapter

ActivityB - >服务类 - >在ActivityC中填充ListView(如下所示,并且没有片段)---> ActivityD

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
    setLocale(pref.getString("myLocale", null));

    setTitle(R.string.title_activity_choose_number);
    setContentView(R.layout.activity_choose_number1);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    if(savedInstanceState != null ) {
        mobileNumbersList = savedInstanceState.getStringArrayList("mobileNumbers");
    }
    mobileNumbersList = getIntent().getStringArrayListExtra("mobileNumbers");

    mobileNumberAdapter = new ArrayAdapter<String>(this,
            R.layout.secnumsinglechoice,
            mobileNumbersList);

    numberListView = (ListView) findViewById(R.id.listViewNumberList);
    numberListView.setAdapter(numberAdapter);
    numberListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String numberChosen = numberAdapter.getItem(position);
            Intent passNumberIntent = new Intent(getBaseContext(), US.class).
                    putExtra(Intent.EXTRA_TEXT, numberChosen);
            startActivity(passNumberIntent);
        }
    });
}

现在当在ActivityD中按下后退按钮到ActivityC时,我收到空指针错误。我知道原因,因为这次,我没有从ActivityD和ListView传递意图,适配器,数据都是null。

所以当我搜索如何保存状态时,我遇到了saveInstanceState,onRestoreInstance和onSaveInstance。但我仍然无法解决这个问题。 ActivityC没有片段。

1 个答案:

答案 0 :(得分:0)

你应该做两件事:

  • 检查getIntent()是否为空。如果它不为null,请尝试从中获取数据
  • 将数据放入方法savedInstanceState
  • 上的public void onSaveInstanceState(Bundle savedInstanceState)变量中