Eventuali duplicati:
How do I save an Android application's state?Android: Salvare uno stato di esempio, quando applicazione è chiusa
Sono nuovo di Java e Android e la costruzione di alcuni piccoli progetti per imparare. Ho creato un'app per il monitoraggio dei soldi che consente all'utente di inserire valori e continua semplicemente a sottrarlo. Tutto funziona bene ma volevo che i valori fossero salvati o memorizzati nella cache quando l'app è stata chiusa e riaperta. Leggendo, ho scoperto che forse un OnPause avrebbe fatto il trucco, ma ancora non lo capiva al 100%.
Qualcuno può consigliare come fare questo e come applicare al mio codice?
Grazie mille per il vostro aiuto !!
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 +"\n" + tracker.getText().toString());
}
}
});
}
}
Perché usare SharedPreferences al posto di un pacchetto nella onSaveInstanceState? –