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

时间:2015-07-28 15:12:51

标签: java android android-studio sharedpreferences back-button

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

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();
    }
}

3 个答案:

答案 0 :(得分:0)

[已编辑]您可以尝试:

@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);
}

答案 1 :(得分:0)

如果需要在用户离开该活动时保存数据,则可以使用TextWatcher解决问题。使用以下内容覆盖TextWatcher的onTextChanged()方法:

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

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

答案 2 :(得分:0)

您应该使用onSaveInstanceState / onRestoreInstanceState方法保存/恢复活动的持久状态。您已经覆盖了这些内容,因此只需从中调用SavePreferences / LoadPreferences即可。

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