vendredi 31 août 2018

Sharedpreferences save checkbox cheked

I try to follow this example Shared Preferences Example to create 2 checkbox inside this example. I tried different ways but it's not saving any changes. I just wan't to safe the checkboxes if clicked and have the last selected value. I'm new with Java and hope someone can explain me how to solves this with this example.

package example.com.max.lschennn;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

public class MainActivity extends Activity {
SharedPreferences sharedpreferences;
TextView name;
TextView email;
CheckBox check1;
CheckBox check2;

public static final String mypreference = "mypref";
public static final String Name = "name";
public static final String Email = "email";
public static final String CHECK1 = "check1";
public static final String CHECK2 = "check2";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    name = (TextView) findViewById(R.id.etName);
    email = (TextView) findViewById(R.id.etEmail);
    check1 = (CheckBox) findViewById(R.id.checkBox1);
    check2 = (CheckBox) findViewById(R.id.checkBox2);
    sharedpreferences = getSharedPreferences(mypreference,
            Context.MODE_PRIVATE);
    if (sharedpreferences.contains(Name)) {
        name.setText(sharedpreferences.getString(Name, ""));
    }
    if (sharedpreferences.contains(Email)) {
        email.setText(sharedpreferences.getString(Email, ""));

    }

}

public void Save(View view) {
    String n = name.getText().toString();
    String e = email.getText().toString();
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putString(Name, n);
    editor.putString(Email, e);
    editor.putBoolean(String.valueOf(check1), true); // Storing boolean - true/false
    editor.putBoolean(String.valueOf(check2), true); // Storing boolean - true/false
    editor.commit();
}

public void clear(View view) {
    name = (TextView) findViewById(R.id.etName);
    email = (TextView) findViewById(R.id.etEmail);
    name.setText("");
    email.setText("");

}

public void Get(View view) {
    name = (TextView) findViewById(R.id.etName);
    email = (TextView) findViewById(R.id.etEmail);

    sharedpreferences = getSharedPreferences(mypreference,
            Context.MODE_PRIVATE);

    if (sharedpreferences.contains(Name)) {
        name.setText(sharedpreferences.getString(Name, ""));
    }
    if (sharedpreferences.contains(Email)) {
        email.setText(sharedpreferences.getString(Email, ""));

    }
}

}




Aucun commentaire:

Enregistrer un commentaire