在活动中保存数字以便稍后再次使用

时间:2013-04-30 09:58:57

标签: android

在我的应用程序的最后一个活动中,编辑文本中显示了一些数字以及添加更多这些总计的选项,添加更多按钮会将您带回到应用程序的开头,用户再次执行同样的操作输入一些数字,最后回到最后一次活动。

我想要做的是,如果他们按下添加更多按钮,则保存编辑文本中的数字,这样我就可以将它们添加到新的数字集中。

我的想法是在暂停时保存数字,但不知道如何然后将它们添加到Resume中的新数字,我是在正确的轨道上,这是最好的方法。

5 个答案:

答案 0 :(得分:2)

在“来源”活动中执行以下操作:

SharedPreferences settings = context.getSharedPreferences(
"yourfilename.bla", Context.MODE_PRIVATE);

SharedPreferences.Editor editor = settings.edit();

editor.putString("key", value);
editor.commit();

在目标活动中执行以下操作:

SharedPreferences preferences = getSharedPreferences(
"yourfilename.bla", Context.MODE_PRIVATE);

String value= preferences.getString("key", "");

如果找不到“key”,则getString中的第二个参数是您想要返回的默认值。

同时查看这些链接

Android Using SharedPreferences to save and retrieve values - Counter

http://android-er.blogspot.in/2011/01/use-getsharedpreferences-to-retrieve.html

答案 1 :(得分:2)

您可以使用Intent来执行此操作。例如,如果要传输int。

  //first activity
  Intent intent =  new Intent(this, FirstActivity.class);
  intent.putExtra("myInt", number);

  //Second Activity
  Intent intent =  this.getIntent();
  int number = intent.getExtra("myInt", -1);

答案 2 :(得分:1)

尝试实现活动的onSaveInsance和onRestoreInstance。这将在onPause之前和onResume之前调用。

示例为here

此外,要添加将返回此活动的其他活动的数据,您可以使用startActivityForResult并在完成之前将数据作为意图从新活动发送..

答案 3 :(得分:1)

答案 4 :(得分:-1)

您可以使用startActivityForResult并通过Intent发送数据。