繁体   English   中英

Android使用数据维护活动状态

[英]Android maintain activity state with data

我有2种不同的活动。 MainActivityContactListContactDetails 现在,从MainActivity中,用户将点击Add new,应用程序将打开ContactList屏幕,用户可以从中选择任何联系人以查看详细信息,从而打开ContactDetails活动。 现在,如果用户选择任何否。 从ContactDetails,应用程序将返回MainActivity并添加选择的编号。 在arraylist中。 我能够添加数据,但是我的问题是,每当添加新记录时,旧记录就会被删除。 我发现每次我从ContactDetails打开MainActivity 都会创建新Activity的原因 所以我正在寻找一种使用OnResumeOnResult方法解决问题的方法。

在ContactDetails中

Intent intent = new Intent(getBaseContext(),MainActivity.class); intent.putExtra(“ CONTACT_NO”,CONTACT_NO); startActivity(意向)

在MainActivity OnResume方法中

字符串数据= getIntent()。getExtras()。getString(“ keyName”);

arr.add(数据);

如果您希望在Activity的生命周期内保留数据, SharefPreferences将为您提供很好的服务。 一个例子:

写(onPause / onDestroy):

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();

阅读(onResume / onCreate):

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);

在这里阅读更多。

更新

另外,您可以使用onSavedInstanceState 例:

保存状态:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

恢复状态:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // Always call the superclass first

    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    } else {
        // Probably initialize members with default values for a new instance
    }
    ...
}

有关在此处管理活动状态的更多信息。

从MainActivity.java中获取列表的任何地方,将其作为公共静态ArrayList或String数组使用,不要在MainActivity.java中对其进行初始化。

另外,如果尚未为MainActivity调用finish()(同时转到ContactListActivity.java),则将新数据添加到onResume()中的arraylist中。 但是请记住要进行检查-是否要添加新数据,因为第一次将没有要添加的数据(根据您发布的问题)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM