Save CheckBox State to SharedPreferences File in Android - android

I have a couple of check boxes that I need to save so that when the user opens the Application again, they can see the state that they left the application in. I have tried using the preferences but I can't seem to get the result correctly.
MainActivity.java
package com.example.android.documentchecklist;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
public class MainActivity extends AppCompatActivity {
CheckBox allotment, sscMarkList, hscMarkList, leaving, profomaCap, jeeScoreCard, gapCer, casteCer, casteVal, nonCreamyL, domicileCertificate, photograph, migration, adhaarCard, nationalityCertificate;
boolean hasAllotment, hasSscMarkList, hasHscMarkList, hasLeaving, hasProfoma, hasJeeScore, hasGapCertificate, hasCasteCertificate, hasCasteValidity, hasNonCreamyLayer, hasDomicileCertificate, hasPhoto, hasMigCertificate, hasadhaarCard, hasNationalityCertificate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
allotment = (CheckBox) findViewById(R.id.allot);
sscMarkList = (CheckBox) findViewById(R.id.ssc);
hscMarkList = (CheckBox) findViewById(R.id.hsc);
leaving = (CheckBox) findViewById(R.id.leaving);
profomaCap = (CheckBox) findViewById(R.id.profoma);
jeeScoreCard = (CheckBox) findViewById(R.id.jeeScore);
gapCer = (CheckBox) findViewById(R.id.gapCertificate);
casteCer = (CheckBox) findViewById(R.id.casteCertificate);
casteVal = (CheckBox) findViewById(R.id.casteValidity);
nonCreamyL = (CheckBox) findViewById(R.id.nonCreamyLayer);
adhaarCard = (CheckBox) findViewById(R.id.adhaarCard);
nationalityCertificate = (CheckBox) findViewById(R.id.nationalityCer);
domicileCertificate = (CheckBox) findViewById(R.id.domicile);
photograph = (CheckBox) findViewById(R.id.photo);
migration = (CheckBox) findViewById(R.id.migration);
}
public void checkBoxClicked(View view) {
int id = view.getId();
if (id == R.id.mahaState) {
migration.setVisibility(View.GONE);
allotment.setText(getString(R.string.allot));
allotment.setVisibility(View.VISIBLE);
hasAllotment = allotment.isChecked();
sscMarkList.setText(getString(R.string.ssc));
sscMarkList.setVisibility(View.VISIBLE);
hasSscMarkList = sscMarkList.isChecked();
hscMarkList.setText(getString(R.string.hsc));
hscMarkList.setVisibility(View.VISIBLE);
hasHscMarkList = hscMarkList.isChecked();
leaving.setText(getString(R.string.leaving));
leaving.setVisibility(View.VISIBLE);
hasLeaving = leaving.isChecked();
profomaCap.setText(getString(R.string.proforma));
profomaCap.setVisibility(View.VISIBLE);
hasProfoma = profomaCap.isChecked();
jeeScoreCard.setText(getString(R.string.jee));
jeeScoreCard.setVisibility(View.VISIBLE);
hasJeeScore = jeeScoreCard.isChecked();
gapCer.setText(getString(R.string.gap_cert));
gapCer.setVisibility(View.VISIBLE);
hasGapCertificate = gapCer.isChecked();
casteCer.setText(getString(R.string.caste_cert));
casteCer.setVisibility(View.VISIBLE);
hasCasteCertificate = casteCer.isChecked();
casteVal.setText(getString(R.string.caste_validity));
casteVal.setVisibility(View.VISIBLE);
hasCasteValidity = casteVal.isChecked();
nonCreamyL.setText(getString(R.string.non_creamy));
nonCreamyL.setVisibility(View.VISIBLE);
hasNonCreamyLayer = nonCreamyL.isChecked();
adhaarCard.setText(getString(R.string.aadhar));
adhaarCard.setVisibility(View.VISIBLE);
hasadhaarCard = adhaarCard.isChecked();
nationalityCertificate.setText(getString(R.string.nationality_cert));
nationalityCertificate.setVisibility(View.VISIBLE);
hasNationalityCertificate = nationalityCertificate.isChecked();
domicileCertificate.setText(getString(R.string.domicile));
domicileCertificate.setVisibility(View.VISIBLE);
hasDomicileCertificate = domicileCertificate.isChecked();
photograph.setText(getString(R.string.photos));
photograph.setVisibility(View.VISIBLE);
hasPhoto = photograph.isChecked();
}
}
#Override
public void onPause() {
super.onPause();
save(allotment.isChecked());
save(sscMarkList.isChecked());
save(hscMarkList.isChecked());
save(leaving.isChecked());
save(profomaCap.isChecked());
save(jeeScoreCard.isChecked());
save(gapCer.isChecked());
save(casteCer.isChecked());
save(casteVal.isChecked());
save(nonCreamyL.isChecked());
save(domicileCertificate.isChecked());
save(photograph.isChecked());
save(migration.isChecked());
save(adhaarCard.isChecked());
save(nationalityCertificate.isChecked());
}
#Override
public void onResume() {
super.onResume();
allotment.setChecked(load());
sscMarkList.setChecked(load());
sscMarkList.setChecked(load());
hscMarkList.setChecked(load());
leaving.setChecked(load());
profomaCap.setChecked(load());
jeeScoreCard.setChecked(load());
gapCer.setChecked(load());
casteCer.setChecked(load());
casteVal.setChecked(load());
nonCreamyL.setChecked(load());
domicileCertificate.setChecked(load());
photograph.setChecked(load());
migration.setChecked(load());
adhaarCard.setChecked(load());
nationalityCertificate.setChecked(load());
}
private void save(final boolean isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("check", isChecked);
editor.apply();
}
private boolean load() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean("check", false);
}
}
Thank You for your help.

you are using the single key i.e. check to store your all checkbox state so only the state of this call save(nationalityCertificate.isChecked()); will be saved ,so you need to use different keys for different checkboxes
for example
// use different keys to store state of different check boxes
save(allotment.isChecked(),"allotment");
save(sscMarkList.isChecked(),"sscMarkList");
// use same keys to fetch values which were used during save function call
allotment.setChecked(load("allotment"));
sscMarkList.setChecked(load("sscMarkList"));
private void save(final boolean isChecked, String key) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, isChecked);
editor.apply();
}
private boolean load(String key) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(key, false);
}
Note: you can also initialize your shared preference like your CheckBox views in onCreate or onStart only once instead of re-initializing it every time in save

Related

SharedPreferences in Android dosent work

I created a sharedprefreference object and tries to retrieve my data within the same activity, is that an allowed operation? The issue is that once the application starts running, and i entered the text within the textview, the entered text does not reappear in a separate textview. The application suppose to take in the user's entered text and display is just several dp downward, however, the entered text just never reappeared. Thank you all so much in advance.
final static String My_PREFERENCES= "sharedPreferences";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
foodTV = (TextView) findViewById(R.id.foodTV);
foodET = (EditText) findViewById(R.id.foodET);
display = (TextView) findViewById(R.id.displayText);
SharedPreferences sharedPreferences =
getSharedPreferences(My_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.clear();
edit.putString("foodname", foodET.getText().toString());
edit.commit();
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(My_PREFERENCES, Context.MODE_PRIVATE);
String food = sharedPreferences.getString("foodname", "");
display.setText(food);
}
});
}
change your code to
foodTV = (TextView) findViewById(R.id.foodTV);
foodET = (EditText) findViewById(R.id.foodET);
display = (TextView) findViewById(R.id.displayText);
foodET.setOnEditorActionListener(
new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId,KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH ||
actionId == EditorInfo.IME_ACTION_DONE ||
event.getAction() == KeyEvent.ACTION_DOWN &&
event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
if (!event.isShiftPressed()) {
SharedPreferences sharedPreferences =
getSharedPreferences(My_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.clear();
edit.putString("foodname", foodET.getText().toString());
edit.commit();
return true;
}
}
return false;
}
});
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(My_PREFERENCES, Context.MODE_PRIVATE);
String food = sharedPreferences.getString("foodname", "");
display.setText(food);
}
});
In fact, I would suggest you using an amazing https://github.com/pilgr/Paper
See how's simple is that:
Only two things are needed:
Initialize library inside your app (or even Activity itself) class
Make calls!
MyApp.java
Just initialize Paper
Paper.init(getApplicationContext());
MyFragment.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Sample food name
String foodName = "apple";
// Write it to paper
Paper.book().write("foodname", foodName);
// Then restore what we have just saved!
String restoredFoodName = Paper.book().read("foodname");
}
Please do note that those calls are not asynchronous! But you can write few simple AsyncTask-s to make them be so.

How save state of checkbox? if is enabled or disabled

I'm making an app that have a lot of checkbox. I wanted save the states of these but only could save if these are checked, but now I want save if is enabled or disabled, since some checkbox active states to other checkbox. How can i do that?
...
if (view.equals(contador11)){
if(contador11.isChecked()){
contador14.setEnabled(true);
}else{
contador14.setEnabled(false);
}
}
if (view.equals(contador12)){
if(contador12.isChecked()){
contador13.setEnabled(true);
contador26.setEnabled(true);
}else{
contador13.setEnabled(false);
contador26.setEnabled(false);
}
}
if (view.equals(contador7)){
if(contador7.isChecked()){
contador15.setEnabled(true);
}else{
contador15.setEnabled(false);
}
}
...
I'm not following your code exactly, but assuming you want to save all of them at the same time, you could save code by just putting them in a list or something. Here's an example.
private SharedPreferences prefs;
private CheckBox[] contadors;
private CheckBox contador1, contador2, contador3, contador4, contador5, contador6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
contador1 = (CheckBox) findViewById(R.id.contador1);
contador2 = (CheckBox) findViewById(R.id.contador2);
contador3 = (CheckBox) findViewById(R.id.contador3);
contador4 = (CheckBox) findViewById(R.id.contador4);
contador5 = (CheckBox) findViewById(R.id.contador5);
contador6 = (CheckBox) findViewById(R.id.contador6);
}
public void clickContador(View view) { // Just for testing
CheckBox contador = (CheckBox) view;
view.setEnabled(false);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveContadors();
}
#Override
protected void onResume() {
super.onPostResume();
contadors = new CheckBox[]{contador1, contador2, contador3, contador4, contador5, contador6};
loadContadors();
}
private void saveContadors() {
SharedPreferences.Editor editor = prefs.edit();
for (int i = 0; i < contadors.length; i++)
editor.putBoolean("contador" + i, contadors[i].isEnabled());
editor.apply();
}
private void loadContadors() {
for (int i = 0; i < contadors.length; i++)
contadors[i].setEnabled(prefs.getBoolean("contador" + i, true));
}
<CheckBox
android:id="#+id/contador1"
android:onClick="clickContador"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
To put the state of your CheckBox, we can use SharedPreferences:
CheckBox contador = (CheckBox) findViewById(R.id.contador1);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();
if (contador.isChecked()) {
prefs.edit().putBoolean("key", true).commit(); // put true value
}else{
prefs.edit().putBoolean("key", false).commit(); // put false value
}
To get the value you saved back:
boolean myContador = prefs.getBoolean("key", false);
if (myContador == true) {
// do your thing
}else{
// the value is false, do something
}

Sharedpreferences doesnt work, checkbox should stay in the same state when I am closing/opening the app

Hey guys I want to make my checkbox stay in the same state every time I open my app.. I get this with the 'ja/nein' string, the string states when i close and open again my application... but my checkbox.setchecked(true/false) doesnt work.. please help
public void changeVisitStatus(){
SharedPreferences visitStatus = mData.getVisitStatus();
SharedPreferences.Editor editor = visitStatus.edit();
if(visitStatus.getString(mData.getVisitKey(), "nein").equals("nein")){
editor.putString(mData.mVisitKey, "ja");
editor.commit();
mGUI.mBtnVisit.setChecked(true);
}
else{
editor.putString(mData.mVisitKey, "nein");
editor.commit();
mGUI.mBtnVisit.setChecked(false);
}
mGUI.getVisitStatus().setText(visitStatus.getString(mData.mVisitKey, "Nein"));
}
EDIT: I tried it another way.. I thought it would be better but doesnt work as well..
public void changeVisitStatus(){
SharedPreferences visitStatus = mData.getVisitStatus();
SharedPreferences.Editor editor = visitStatus.edit();
if(visitStatus.getString(mData.getVisitKey(), "nein").equals("nein")){
editor.putString(mData.mVisitKey, "ja");
editor.putBoolean("isChecked", true);
editor.commit();
}
else{
editor.putString(mData.mVisitKey, "nein");
editor.putBoolean("isChecked", false);
editor.commit();
}
mGUI.getVisitStatus().setText(visitStatus.getString(mData.mVisitKey, "Nein"));
}
and put this one into my onCreate(Bundle savedInstanceState) in my Activity
mGUI.mBtnVisit.setChecked(mData.getVisitStatus().getBoolean("isChecked", false));
Try like this:
public void putBooleanInPreferences(boolean isChecked,String key){
SharedPreferences sharedPreferences = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, isChecked);
editor.commit();
}
public boolean getBooleanFromPreferences(String key){
SharedPreferences sharedPreferences = this.getPreferences(Activity.MODE_PRIVATE);
Boolean isChecked = sharedPreferences.getBoolean(key, false);
return isChecked;
}
and in onCreate()
CheckBox checkBox = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkBox = (CheckBox) findViewById(R.id.my_check_box);
boolean isChecked = getBooleanFromPreferences("isChecked");
Log.i("start",""+isChecked);
checkBox.setChecked(isChecked);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
Log.i("boolean",""+isChecked);
TestActivity.this.putBooleanInPreferences(isChecked,"isChecked");
}
});
}
Hope this may help you!
You're showing us only the code for changing the status, probably called from OnClick listener for the check box.
You should also add code that only reads status from SharedPreferences and sets check box state according to that (could be same code, but the if condition negated).
You need to call that code from OnCreate event.
public void setVisitStatus(){
SharedPreferences visitStatus = mData.getVisitStatus();
mGUI.getVisitStatus().setText(visitStatus.getString(mData.mVisitKey, "Nein"));
}

Saving Checkbox states

I am very new and would appreciate if someone could demonstrate the code required to save a number of checkbox states in java inside of an android application.
Say i have a list of tools (Ten or more) a user needs to complete a task and would like them to be able to check off each one and have that data saved (within the app, not sQlite) so that it is recorded when they return to the application.
I have some idea of how this is done but really feel like i need to see the code to understand correctly.
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.CheckBox;
public class CheckBoxTest extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.checkboxtest);
CheckBox cb1,cb2,cb3,cb4;
cb1 = (CheckBox)findViewById(R.id.checkBox1);
cb2 = (CheckBox)findViewById(R.id.checkBox2);
cb3 = (CheckBox)findViewById(R.id.checkBox3);
cb4 = (CheckBox)findViewById(R.id.checkBox4);
}
}
Use the below code to store and retrive the data in SharedPreference. Your save each check box state in SharedPreference
//To get value from SharedPreference
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
boolean value = preferences.getBoolean("KEY", false);
String value = preferences.getString("KEY");
//To Save value in SharedPreference
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("KEY", value);
editor.putBoolean("KEY", value);
editor.commit();
look into it few minor changes::::
public class CheckBoxTest extends Activity implements OnCheckedChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites_add_button);
CheckBox cb1,cb2,cb3,cb4;
cb1 = (CheckBox)findViewById(R.id.checkBox1);
cb1.setChecked(getFromSP("cb1"));
cb1.setOnCheckedChangeListener(this);
cb2 = (CheckBox)findViewById(R.id.checkBox2);
cb2.setChecked(getFromSP("cb2"));
cb2.setOnCheckedChangeListener(this);
cb3 = (CheckBox)findViewById(R.id.checkBox3);
cb3.setChecked(getFromSP("cb3"));
cb3.setOnCheckedChangeListener(this);
cb4 = (CheckBox)findViewById(R.id.checkBox4);
cb4.setChecked(getFromSP("cb4"));
cb4.setOnCheckedChangeListener(this);
}
private boolean getFromSP(String key){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}
private void saveInSp(String key,boolean value){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
switch(buttonView.getId()){
case R.id.checkBox1:
saveInSp("cb1",isChecked);
break;
case R.id.checkBox2:
saveInSp("cb2",isChecked);
break;
case R.id.checkBox3:
saveInSp("cb3",isChecked);
break;
case R.id.checkBox4:
saveInSp("cb4",isChecked);
break;
}
}
}
Hi I tried the above but after rebooting or restarting my android device, I would lose the checked state of the options menu. I'd say, to solve the problem:
You have 2 options:
Get shared preference value during the life-cycle of the activity.
Call .clear before .commit
See my answer:
Android Persistent Checkable Menu in Custom Widget After Reboot Android

Android:problem in remember me functionality of login Activity

i have create login page with 2 EditText and checkbox and login button.
if i set checkbox to Enabled i want to save data so next time user doesn't need to fill that fields..
i have uses this code but no luck..
public class LoginPage extends Activity {
EditText d_ID;
EditText password;
CheckBox cb;
ImageButton ib;
public static final String PREFS_NAME = "MyPrefsFile";
public String PREFS_USER;
public String PREFS__PASS;
String username;
String upass;
SharedPreferences pref
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.loginpage);
d_ID = (EditText) findViewById(R.id.dulzuID);
password = (EditText) findViewById(R.id.dulzuPASS);
cb = (CheckBox) findViewById(R.id.remember);
ib = (ImageButton) findViewById(R.id.login);
pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
username = pref.getString(PREFS_USER, null);
upass = pref.getString(PREFS__PASS, null);
d_ID.setText(username);
password.setText(upass);
ib.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
startActivity(new Intent(LoginPage.this, Features.class));
}
});
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton cb1, boolean bln) {
PREFS_USER = d_ID.getText().toString();//get user name from EditText
PREFS__PASS = password.getText().toString();//get user Password from EditText
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit().putString(PREFS_USER, username).putString(PREFS__PASS, upass).commit();
}
});
}
}
Any help??
Thanks...
I think you are confusing the variables for retrieving the value of the users password and the variables that identify the username/password values in the preferences. I think that you intend these:
public String PREFS_USER;
public String PREFS__PASS;
to be the identifiers for your stored username and password, however you then set them to be the values that you have pulled from the corresponding EditTexts. I have rewritten some of the code for you:
public static final String PREFS_NAME = "MyPrefsFile";
public static final String PREFS_USER = "prefsUsername";
public static final String PREFS__PASS = "prefsPassword";
...
pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
username = pref.getString(PREFS_USER, "");
upass = pref.getString(PREFS__PASS, "");
...
public void onCheckedChanged(CompoundButton cb1, boolean bln) {
username = d_ID.getText().toString();//get user name from EditText
upass = password.getText().toString();//get user Password from EditText
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit().putString(PREFS_USER, username).putString(PREFS__PASS, upass).commit();
}
Personally, I wouldn't do it like that though. I would check the value of the checkbox when the user submits the form, and only save the username & password at that point. What if the user unchecks and then rechecks the tick box before they have entered their password? You will save empty values and annoy your users.
You are doing small mistake in this part:
if (cb.isChecked()) {
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
username = pref.getString(PREFS_USER, null);
upass = pref.getString(PREFS__PASS, null);
d_ID.setText(username);
password.setText(upass);
}
As your view is rendered each time when new activity starts.cb.isEnabled() will always give false because it is not enabled that time.
You can do stuff for your sol like this.
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
if(!pref.getstring(PREFS_USER,null).equals(null)||!pref.getstring(PREFS_USER,null).equals(""))
{username = pref.getString(PREFS_USER, null);
d_ID.setText(username);}
and same for password field
One thing that I would like to tell you: do not store the values when user clicks on check box save it when user presses login button.
If user clicked that check box when he has not entered details the you will save null values.
And why don't you serialize both the objects and save it to memory and again deserialize it when you need to read it?
public void serializeCredentials(String Username,String Password) {
try {
FileOutputStream fStream = openFileOutput(namefile.bin, Context.MODE_PRIVATE) ;
ObjectOutputStream oStream = new ObjectOutputStream(fStream);
oStream.writeObject(Username) ;
FileOutputStream fos = openFileOutput(passwordfile.bin, Context.MODE_PRIVATE) ;
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(Password) ;
oStream.flush() ;
oStream.close() ;
oos.flush() ;
oos.close() ;
Log.v("Serialization success", "Success");
} catch (Exception e) {
Log.v("IO Exception", e.getMessage());
}
}
Don't forget to deserialize when reading data; you can deserialize it similarly.
I think you need to write/initialize this line inside onCreate() method.
SharedPreferences pref;
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.loginpage);
pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
...
}
try doing the editing line by line.. at least in my case, it did the trick..
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton cb1, boolean bln) {
PREFS_USER = d_ID.getText().toString();//get user name from EditText
PREFS__PASS = password.getText().toString();//get user Password from EditText
SharedPreferences.Editor prefEditor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
prefEditor.putString(PREFS_USER, username);
prefEditor.putString(PREFS__PASS, upass);
prefEditor.commit();
}
});
And it would be much better if you follow N-JOY's suggestion to trigger saving data to SharedPreferences during login button click..

Categories

Resources