Android: Save an instance state when app is closed
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
How do I save an Android application's state?
我是Java和Android的新手,需要学习一些小项目。我制作了一个货币追踪应用程序,允许用户输入值,然后继续减去它。一切正常,但我希望在应用程序关闭并重新打开时保存或缓存这些值。阅读时,我发现也许暂停一下就可以了,但仍然不能100%理解。
有人能推荐如何做以及如何应用到我的代码吗?
非常感谢你的帮助!!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | package ps.age.sl; import java.text.NumberFormat; import java.util.Locale; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; public class MoneyTrackerActivity extends Activity { /** Called when the activity is first created. */ ImageButton subtract; EditText startingmoney,submoney, endmoney, tracker; Locale currentLocale = Locale.getDefault(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // startingmoney = (EditText) findViewById (R.id.firstmoney); // submoney = (EditText) findViewById (R.id.submoney); // subtract = (ImageButton) findViewById (R.id.subbutton); // endmoney = (EditText) findViewById (R.id.endtv); // tracker = (EditText) findViewById (R.id.trackertv); startingmoney.setText(""); submoney.setText(""); endmoney.setText(""); subtract.setOnClickListener(new View.OnClickListener() { double currentValue=0; double startValue=0; public void onClick(View v) throws NumberFormatException { if (v == subtract) { NumberFormat currencyFormatter; currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale); String totalString; String x = startingmoney.getText().toString(); String y = submoney.getText().toString (); double total; double xm = 0.00; double ym =0.00; try { xm = Double.parseDouble(x); } catch(NumberFormatException n) { xm = 0.00; } try { ym = Double.parseDouble(y); } catch(NumberFormatException n) { ym = 0.00; } if(startValue!=xm){ startValue=xm; currentValue=xm; } currentValue = currentValue -ym; totalString = currencyFormatter.format(currentValue); endmoney.setText(totalString); tracker.setText("you have entered" + totalString +" " + tracker.getText().toString()); } } }); } } |
请使用
1 2 3 4 5 6 7 8 9 10 11 12 13 | @Override protected void onPause() { super.onPause(); // Store values between instances here SharedPreferences preferences = getSharedPreferences("sharedPrefs", 0); SharedPreferences.Editor editor = preferences.edit(); editor.putString("CLASSLABEL", this.getLocalClassName()); // value to store editor.putString("STRINGLABEL",String1 ); editor.putString("STRINGLABEL1",String2); // Commit to storage editor.commit(); } |