簡體   English   中英

關閉應用程序后,應該保存並檢索復選框,我嘗試使用sharedpreferences進行嘗試,但它不起作用,我也不知道為什么

[英]Checkbox should saved and retrieved after closing the app, i tried it with sharedpreferences but it doesnt work and i dont know why

我是android開發的初學者,我嘗試實現了一個使用sharedpreferences保存復選框的類。 到目前為止,我可以看到所有內容並選中模擬器中的復選框。 但是,單擊“保存”按鈕會使我的應用程序崩潰。 也許TextView有問題?

繼承人的代碼...

public class Settings extends Activity implements OnClickListener {

    CheckBox checkBox;
    TextView textView;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settingslayout);

        checkBox = (CheckBox) findViewById(R.id.checkBox1);
        textView = (TextView) findViewById(R.id.textView1);
        button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(this);
        loadSavedPreferences();
    }

    private void loadSavedPreferences() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        boolean checkBoxValue = sharedPreferences.getBoolean("CheckBox_Value", false);
        if (checkBoxValue) {
            checkBox.setChecked(true);
        } else {
            checkBox.setChecked(false);
        }


    }

    private void savePreferences(String key, boolean value) {
        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        Editor editor = sharedPreferences.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }



    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        savePreferences("CheckBox_Value", checkBox.isChecked());
        if (checkBox.isChecked())
            textView.setText("Visited.");
        else
            textView.setText("Not Visited");


finish();

    }

}

試試這個代碼:

@Override
    public void onClick(View v) {
        if (v.getId() == R.id.button1) {
           // TODO Auto-generated method stub
           savePreferences("CheckBox_Value", checkBox.isChecked());
           if (checkBox.isChecked())
              textView.setText("Visited.");
           else
              textView.setText("Not Visited");
           finish(); 
        }
    }

只需從OnClick(View v)中刪除finish()

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    savePreferences("CheckBox_Value", checkBox.isChecked());
    if (checkBox.isChecked())
        textView.setText("Visited.");
    else
        textView.setText("Not Visited");

}

如果您遇到“真正的崩潰”,請附加日志貓。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM