使用 SharedPreferences 覆盖后退按钮以保存数据

Override Back button to save data using SharedPreferences

当使用我的应用程序时,用户输入数据并且数据应该被保存。但是目前后退按钮会删除 EditText 中的数据。这是我 activity 的 java 文件,这个 activity 是通过从 Main Activity 按下按钮激活的。我已经尝试覆盖后退按钮但没有成功。有什么建议吗?

public class NewLocation extends ActionBarActivity {

    public String coName;
    public String coAddress;
    public String coContact;
    public String sqFt;
    public String taxed;
    public String concerns;
    public EditText editCoName;
    public EditText editCoAddress;
    public EditText editCoContact;
    public EditText editSqFt;
    public EditText editTaxed;
    public EditText editConcerns;

    public static final String DEFAULT = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_location);
        findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(NewLocation.this, RoomList.class));
            }
        });

        editCoName = (EditText) findViewById(R.id.CoName);
        editCoAddress = (EditText) findViewById(R.id.CoAddress);
        editCoContact = (EditText) findViewById(R.id.CoContact);
        editSqFt = (EditText) findViewById(R.id.SqFt);
        editTaxed = (EditText) findViewById(R.id.Taxed);
        editConcerns = (EditText) findViewById(R.id.Concerns);

        coName = editCoName.getText().toString();
        coAddress = editCoAddress.getText().toString();
        coContact = editCoContact.getText().toString();
        sqFt = editSqFt.getText().toString();
        taxed = editTaxed.getText().toString();
        concerns = editConcerns.getText().toString();


        LoadPreferences();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);

        outState.putString("coName", coName);
        outState.putString("coAddress", coAddress);
        outState.putString("coContact", coContact);
        outState.putString("sqFt", sqFt);
        outState.putString("taxed", taxed);
        outState.putString("concerns", concerns);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        coName = savedInstanceState.get("coName").toString();
        coAddress = savedInstanceState.get("coAddress").toString();
        coContact = savedInstanceState.get("coContact").toString();
        sqFt = savedInstanceState.get("sqFt").toString();
        taxed = savedInstanceState.get("taxed").toString();
        concerns = savedInstanceState.get("concerns").toString();

    }

    private void SavePreferences()
    {
        SharedPreferences sharedPreferences = getSharedPreferences("New Location Data", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        editor.putString("coName", coName);
        editor.putString("coAddress", coAddress);
        editor.putString("coContact", coContact);
        editor.putString("sqFt", sqFt);
        editor.putString("taxed", taxed);
        editor.putString("concerns", concerns);

        editor.apply();
    }

    private void LoadPreferences()
    {
        SharedPreferences sharedPreferences = getSharedPreferences("New Location Data", Context.MODE_PRIVATE);

        coName = sharedPreferences.getString("coName", DEFAULT);
        coAddress = sharedPreferences.getString("coAddress", DEFAULT);
        coContact = sharedPreferences.getString("coContact", DEFAULT);
        sqFt = sharedPreferences.getString("sqFt", DEFAULT);
        taxed = sharedPreferences.getString("taxed", DEFAULT);
        concerns = sharedPreferences.getString("concerns", DEFAULT);

        editCoName.setText(coName);
        editCoAddress.setText(coAddress);
        editCoContact.setText(coContact);
        editSqFt.setText(sqFt);
        editTaxed.setText(taxed);
        editConcerns.setText(concerns);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_new_location, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        switch(item.getItemId())
        {
            case R.id.home:
                SavePreferences();
                startActivity(new Intent(getApplicationContext(), MainPage.class));
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        SavePreferences();
        super.onBackPressed();
    }
}

[已编辑]你可以试试:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        SavePreferences();
        finish(); //<-- You need finish your activity after saved
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

如果每当用户离开时都需要保存数据 activity,您可以使用 TextWatcher 解决该问题。用这样的东西覆盖 TextWatcher 的 onTextChanged() 方法:

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    if (s.length > 0) coName = s;
}

然后重写 onPause() 以在必要时保存变量的状态。

您应该 save/restore onSaveInstanceState/onRestoreInstanceState 方法中 activity 的持久状态。您已经覆盖了它们,所以只需从它们中调用 SavePreferences/LoadPreferences

覆盖后退按钮不是一个好主意,也不建议在 onDestroy 中保存状态。 onSaveInstanceStateonPause 就是为此目的。