SharedPreference cannot save data across activities - android

I'm working on a splash screen where it will determine whether the user has previously registered or not based on SharedPreference stored values.
Please allow me to ask this question one more time, as I've gone through so many help / tutorials and examples, it didn't help a bit. I've been stuck here for 2 days now... Any help is really really appreciated.
There are 2 activities involved. The app starts with SplashScreen activity, then if sharepreference file return non-null (means user registered before), it will start mainactivity. Else if sharepreference file return null (means first time user, it brings user to the registration activity)...
PROBLEM: whenever the app restart (even with user registered), it always go to registration page !! PLEASE HELP !!
code for SPLASHSCREEN activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
Thread timerThread = new Thread(){
public void run(){
try{
sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
}
}
};
timerThread.start();
}
protected void onStart() {
super.onStart();
openNextActivity();
}
public void openNextActivity(){
SharedPreferences sp = getSharedPreferences("pref", 0);
if (sp.contains("Name")) {
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
} else {
Intent intent = new Intent(SplashScreen.this, Registration.class);
startActivity(intent);
}
}
#Override
protected void onPause() {
super.onPause();
finish();
}
below is the code for REGISTRATION activity...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
etName = (EditText) findViewById(R.id.etName);
etEmail = (EditText) findViewById(R.id.etEmail);
etMobilePhone = (EditText) findViewById(R.id.etMobilePhone);
tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); // imei
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSubmit:
writePref();
break;
}
finish();
}
private void writePref() {
String userName = etName.getText().toString(); //prepare variables values for write
String userPhone = etMobilePhone.getText().toString(); //prepare variables values for write
String userEmail = etEmail.getText().toString(); //prepare variables values for write
String userImei = tel.getDeviceId().toString(); //prepare variables values for write
SharedPreferences sp = getSharedPreferences("pref", 0); //sharepreference
SharedPreferences.Editor editor = sp.edit(); //sharepreference
editor.putString(Name, userName); //write sharepreferences
editor.putString(Phone, userPhone); //write sharepreferences
editor.putString(Email, userEmail); //write sharepreferences
editor.putString(Imei, userImei); //write sharepreferences
editor.commit(); //sharepreference
Toast toast = Toast.makeText(getApplicationContext(), "updated sharepreferences", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL,0,50);
toast.show();
}
Please guide me to the right directions. Thank you for reading and responding.

Change your openNextActivity() method to this:
public void openNextActivity(){
SharedPreferences sp = getSharedPreferences("pref", 0);
String defaultValue = "na";
String storedValue = sp.getString("Name", defaultValue);
if (!storedValue.equalsIgnoreCase("na")) {
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
} else { //if you get default value i.e. "na"
Intent intent = new Intent(SplashScreen.this, Registration.class);
startActivity(intent);
}
}
Instead of checking if the key exists, check for its value. If key not found return a default value and and check against the returned value.
Update (From Jelle's comment below): Also change your RegistrationActivity. Change editor.putString(Name, userName); into editor.putString("Name", userName);

Thanks guys... wanted to share the solution...
SharedPreferences sp = getSharedPreferences("pref", 0); //sharepreference
SharedPreferences.Editor editor = sp.edit(); //sharepreference
editor.putString("Name", userName); //write sharepreferences
editor.putString("Phone", userPhone); //write sharepreferences
editor.putString("Email", userEmail); //write sharepreferences
editor.putString("Imei", userImei); //write sharepreferences
editor.commit(); //sharepreference
Apparently, the solution is the ""... thanks for all the wonderful people...

Related

SharedPreferences always shows the same thing

So I'm trying to save a value to sharedpreferences by a click of a button, and then see which value it is in another activity. (to basically set a background for activity2 based on which button they pressed in activity1)
Saving code:
public void onClick(View v) {
SharedPreferences.Editor background = getSharedPreferences("Background", MODE_PRIVATE).edit();
if(btn1 == v)
{
background.remove("selectedBG");
Toast.makeText(this, "btn1", Toast.LENGTH_SHORT).show();
background.putInt("selectedBG", 1);
background.commit();
}
if(btn2 == v)
{
background.remove("selectedBG");
background.putInt("selectedBG", 2);
Toast.makeText(this, "btn2", Toast.LENGTH_SHORT).show();
background.commit();
}
if(btn3 == v)
{
background.remove("selectedBG");
background.putInt("selectedBG", 3);
Toast.makeText(this, "btn3", Toast.LENGTH_SHORT).show();
background.commit();
}
if(btn4 == v)
{
background.remove("selectedBG");
background.putInt("selectedBG", 4);
Toast.makeText(this, "btn4", Toast.LENGTH_SHORT).show();
background.commit();
}
}
And then, the Toast here always shows "chosenbackground:0":
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
LLayout=(LinearLayout)findViewById(R.id.llayout);
SharedPreferences background2 = getSharedPreferences("Background", MODE_PRIVATE);
int chosenBackground = background2.getInt("selectedBg", 0);
Toast.makeText(this,"chosenBackground:" + chosenBackground, Toast.LENGTH_SHORT).show();
if (chosenBackground != 0) {
if(chosenBackground==1)
{
LLayout.setBackgroundColor(Color.WHITE);
}
if(chosenBackground==2)
{
LLayout.setBackgroundColor(Color.rgb(34,34,34));
}
if(chosenBackground==3)
{
LLayout.setBackgroundColor(Color.rgb(51,68,85));
}
if(chosenBackground==4)
{
LLayout.setBackgroundColor(Color.rgb(68,34,17));
}
}
}
Answer for your question is that you have misspelled the key in second activity, in first one you are using "selectedBG" but in the second one "selectedBg". It is not the same, it's case sensitive. Correct in the second one for "selectedBG" and it should work.
Using the SharedPreferences here it's really bad idea, if u only want to pass a background or rather a color if I see it correctly. Just pass it in intent:
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("EXTRA_BACKGROUND_ID", background);
startActivity(intent);
Access that intent on next activity for eg. in onCreate()
String s = getIntent().getStringExtra("EXTRA_SESSION_ID");
#Updated
public class PreferencesUtils {
private SharedPreferences sharedPrefs;
private SharedPreferences.Editor prefsEditor;
public static final String KEY_BACKGROUND = "BACKGROUND";
public PreferencesUtils(Context context) {
this(context, PREFS_DEFAULT);
}
public PreferencesUtils(Context context, String prefs) {
this.sharedPrefs = context.getSharedPreferences(prefs, Activity.MODE_PRIVATE);
this.prefsEditor = sharedPrefs.edit();
}
public int getValue(String key, int defaultValue){
return sharedPrefs.getInt(key, defaultValue);
}
public boolean saveValue(String key, int value){
prefsEditor.putInt(key, value);
return prefsEditor.commit();
}
}
PreferencesUtils preferencesUtils = new PreferencesUtils(this);
preferencesUtils.saveValue(PreferencesUtils.KEY_BACKGROUND, 1); //saveValue
preferencesUtils.getValue(PreferencesUtils.KEY_BACKGROUND, 0); //getValue,
second arg is defult if not found
Use if (!background2.contains("selectedBg"))
to check ,first whether the key exists and if not getInt is not able to create a key and hence always returns default value 0.Also you can use apply() instead of commit to check whether commit has taken place successfully.Debug the code more to see all possibilities
int chosenBackground=0;
if (!background2.contains("selectedBg"))
{
//is called once when after you freshly install the app
background2.putInt("selectedBG", 0);
}
else
chosenBackground = background2.getInt("selectedBg", 0);

Personalization in Android App (Beginner)

I am new at Android. And I have to design an app where user can input his/her own profile in the app. What i would like to happen is that after the user install the app, the user will be redirected to the ProfileActivityUI to input his/her profile. After that, he/she will be redirected to MainMenuActivityUI of the app.
My problem is that after user input his/her profile info on the app and that when he/she close the app and start the app again, he/she will be redirected to ProfileActivityUI again (in which he/she shouldn't be cause he/she already inputted his/her profile). It should that the user will be redirected to MainMenuActivityUI.
ProfileActivityUI should appear one time only. and that is after installation. But when the user open the app again. it shouldn't appear anymore.
I need your help. cause i dont know how to do that. Sample codes are appreciated. thank you.
hey you need to implement share preference:-
1) on ProfileActivityUI you need to check share preference on load,
SharedPreferences sref;
SharedPreferences.Editor editor;
sref = PreferenceManager.getDefaultSharedPreferences(this);
editor = sref.edit();
String checkstring = sref.getString("RoleID",null);
if(!checkstring==null)
{
Intent i = new intent (this,MainMenuActivityUI.class)
startactivity(i);
}
2)when you ProfileActivityUI is submint successfully then right down this code:-
SharedPreferences sref;
SharedPreferences.Editor editor;
sref = PreferenceManager.getDefaultSharedPreferences(this);
editor = sref.edit();
editor.putString("RoleID", RoleID);
editor.commit();
Intent i = new Intent(this,MainMenuActivityUI.class);
startActivity(i);
finish();
then you get what you want 100%
you should try it with sharedpreferences .
public class ProfileActivityUI extends Activity {
SharedPreferences srefforsignout,sref;
Editor edtr;
int signoutcod;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sref=getSharedPreferences("SignOut", MODE_PRIVATE);
signoutcod=sre.getInt("signoutcode", 0);
if(signoutcod==1){
Intent i=new Intent(getApplicationContext(), MainMenuActivityUI.class);
startActivity(i);
finish();
}
srefforsignout=getSharedPreferences("SignOut", MODE_PRIVATE);
edtr=srefforsignout.edit();
buttonsignin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(ProfileActivityUI.this,MainMenuActivityUI.class);
edtr.putInt("signoutcode", 1);
edtr.commit();
startActivity(i);
});
}
}
I think SharedPreferences will solve your problem try to do this.
First of all make a start up screen (Splash screen) so you can check in background that is user registered or not.
public class SplashScreen extends Activity {
Thread td;
public static final String MyPREFERENCES = "MyPrefs";
String name, pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
td = new Thread(new Runnable() {
#SuppressWarnings("static-access")
#Override
public void run() {
// TODO Auto-generated method stub
try {
td.sleep(3000);
SharedPreferences sharepPreferences = getSharedPreferences(
MyPREFERENCES, Context.MODE_PRIVATE);
//Make sure You have entered same key in my case "email" or "password"..
name = sharepPreferences.getString("email", null);
pass = sharepPreferences.getString("password", null);
if (name == null) {
if (pass == null) {
Intent i = new Intent(SplashScreen.this,
ProfileActivityUI.class);
startActivity(i);
}
} else {
Intent i1 = new Intent(SplashScreen.this,
MainMenuActivityUI.class);
startActivity(i1);
}
finish();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
td.start();
}
Now Whenever user starts your application after installing it, there will be no data in shared preference, so it will be redirected to ProfileActivityUI.
Now in ProfileActivityUI you have to save data which user has entered in SharedPreferences.
Do this in your ProfileActivityUI
SharedPreferences sharedPreferences;
public static final String MyPREFERENCES = "MyPrefs"; //Make sure this is same in both activity.
sharedPreferences = getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", et1.getText().toString());
editor.putString("password", et4.getText().toString());
editor.commit();
This will Store your data permanently.
Now if you open your Application again it will redirect you to the ProfileActivityUI straight after splash screen.
What I would do is to start in the MainMenuActivityUI and if the profile it's not saved , automatically redirects him to the ProfileActivityUI.
If the UI it's not very complicated you always can make a setContentView for one or the other view (but it's kind of messy thing...)

how to kill Activity permanetly After button click Using Shared prefrance

public class MainActivity extends Activity {
Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent newpage = new Intent(MainActivity.this, PhonrRegistaion.class);
startActivity(newpage);
btn1=(Button)findViewById(R.id.button1);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent myintent=new Intent(MainActivity.this,nextActvity.class);
startActivities(null);
}
});
}
}
this is my Activity i want moving from one Activity to another Activity i want to kill my Activity permanently using shared prefrances means if open Application then it should launch second Activity . please help i dont know how to kill Activity using shred prefrances
here is the complete solution
//firstly when you register the user set the shared preferences in your register class like this
//declare pref editor
SharedPreferences prefs;
SharedPreferences.Editor prefsEditor;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefsEditor = prefs.edit();
//paste below peace of code when the registration will be success
prefsEditor.putString("register", "yes");
prefsEditor.commit();
//now in your first activity you just check the shared pref value to know the user is register or no
SharedPreferences prefs;
String register;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
register=prefs.getString("register", "");
//now check the value of shared pref and apply the condition like this
Intent intent ;
if(register.equalsIgnoreCase("yes"))
{
intent = new Intent(this, NextAct.class);
startActivity(intent);
finish();
}
else
{
intent = new Intent(this, Register.class);
startActivity(intent);
finish();
}
You cannot "kill" an activity but you can finish() it.
In onCreate() create condition:
if (<your condition>) {
startActivity(...);
finish();
}
Either finish the old activity when the new one is started:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = getSharedPreferences(LOC_PREF_FILE, MODE_PRIVATE);
Boolean startSecond = prefs.getBoolean("StartSecondActivty", false);
if (startSecond) {
Intent newpage = new Intent(this, PhonrRegistaion.class);
startActivity(newpage);
finish();
}
btn1=(Button)findViewById(R.id.button1);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent myintent=new Intent(this, nextActvity.class);
startActivities(null);
finish();
SharedPreferences prefs = getSharedPreferences(
LOC_PREF_FILE, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("StartSecondActivty", true);
editor.commit();
editor.apply();
}
});
}
}
This is not permanent as such as it will reside in memory until GC.
If you want to permanently kill you activity (and app) try killing your own process:
// Kill everything you can
public void killMyProcess() {
try {
Process process = Runtime.getRuntime().exec(
"/system/bin/kill -9 -1");
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
process.waitFor();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}

how to save toggle button state to database and if user edits then edited state should be saved to database in android

how to save toggle button state to database and if user edits then edited state should be saved to database in android.the following is my code it is working fine.but the problem is that when user edits to on it is in on state and green light displays on toggle button. and then user performs the required actions.when user again comes back to edit again it displays on only but no green light is visible.so it looks bad so please help me and following is my code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_layout);
edittext=(EditText)findViewById(R.id.device_text);
light=(ToggleButton)findViewById(R.id.light);
alarm=(ToggleButton)findViewById(R.id.alarm);
db = new DataBaseAdapter(this);
Intent i = getIntent();
if(i.hasExtra("Dname"))
val = i.getStringExtra("Dname");
if(i.hasExtra("Dlight"))
slight=i.getStringExtra("Dlight");
blight=Boolean.valueOf(slight);
if(i.hasExtra("Dalarm"))
salarm=i.getStringExtra("Dalarm");
balarm=Boolean.valueOf(balarm);
if(i.hasExtra("Daddress"))
pos=i.getStringExtra("Daddress");
db.open();
db.insertData(pos,val,slight,salarm);
c = db.getData();
edittext.setText(val);
light.setText(slight);
// light.setChecked(blight);
alarm.setText(salarm);
//alarm.setChecked(balarm);
db.close();
}
#Override
public void onBackPressed(){
db.open();
c=db.getData();
if (c.moveToFirst()) {
do {
String strSQL = "UPDATE DeviceDetails SET devicename ='"+ edittext.getText().toString() +"' WHERE uuid = '"+c.getString(c.getColumnIndex("uuid"))+"'" ;
db.select(strSQL);
slight=light.getText().toString();
salarm=alarm.getText().toString();
if(pos.equalsIgnoreCase(c.getString(c.getColumnIndex("uuid"))))
{
db.updateData(pos, edittext.getText().toString(),slight,salarm);
}
Intent intent=new Intent();
intent.putExtra("Dname", edittext.getText().toString());
intent.putExtra("Daddress",pos);
intent.putExtra("Dlight", slight);
intent.putExtra("Dalarm", salarm);
setResult(RESULT_OK, intent);
finish();
} while (c.moveToNext());
}
db.close();
super.onBackPressed();
}
}
You can use SharedPrefernce for saving the state of toggle button.
sharedpreferences = context.getSharedPreferences("Toggle_pref", Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putInt("button_state", "state");
editor.commit();
This is code for Toogle Button with saved state..
private SharedPreferences spref;
private ToggleButton tb;
private boolean on;
spref = getSharedPreferences("APP", MODE_PRIVATE);
tb = (ToggleButton) findViewById(R.id.toogleButton);
on = spref.getBoolean("On", true); //default is true
if (on)
{
tb.setChecked(true);
} else
{
tb.setChecked(false);
}
tb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (tb.isChecked()) {
//Toast.makeText(MainActivity.this, "On : Notification will be Enabled", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean("On", true); // value to store
editor.commit();
} else {
// Toast.makeText(MainActivity.this, "Off : Notification will be Disabled", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor =spref.edit();
editor.putBoolean("On", false); // value to store
editor.commit();
}
}
});
in the following way i done and my problem solved.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_layout);
edittext=(EditText)findViewById(R.id.device_text);
light=(ToggleButton)findViewById(R.id.light);
alarm=(ToggleButton)findViewById(R.id.alarm);
db = new DataBaseAdapter(this);
Intent i = getIntent();
if(i.hasExtra("Dname"))
val = i.getStringExtra("Dname");
if(i.hasExtra("Dlight"))
slight=i.getStringExtra("Dlight");
blight=Boolean.valueOf(slight);
if(i.hasExtra("Dalarm"))
salarm=i.getStringExtra("Dalarm");
balarm=Boolean.valueOf(balarm);
Log.v("___EDIT CLASS____________", "__LIGHT TEXT_____________"+slight);
Log.v("_____EDIT CLASS_____________", "___ALARM TEXT____________"+salarm);
Log.v("___EDIT CLASS____________", "__LIGHT boolean_____________"+blight);
Log.v("_____EDIT CLASS_____________", "___ALARM boolean____________"+balarm);
// edittext.setText(val);
if(i.hasExtra("Daddress"))
pos=i.getStringExtra("Daddress");
Log.v("___________edittext", "_______________"+edittext.getText());
Log.v("__________address", "_______________"+pos);
db.open();
db.insertData(pos,val,slight,salarm);
c = db.getData();
edittext.setText(val);
light.setText(slight);
// light.setChecked(blight);
alarm.setText(salarm);
//alarm.setChecked(balarm);
if(slight.equalsIgnoreCase("on"))
{
light.setChecked(true);
}
else
{
light.setChecked(false);
}
if(salarm.equalsIgnoreCase("on"))
{
alarm.setChecked(true);
}
else
{
alarm.setChecked(false);
}
db.close();
}
#Override
public void onBackPressed(){
//saveData();
db.open();
c=db.getData();
if (c.moveToFirst()) {
do {
// slight=light.setClickable(true);
//salarm= String.valueOf(balarm);
Log.v("_______BACK PRESSED", "______UUID___________"+c.getString(c.getColumnIndex("uuid")));
Log.v("_______pos", "______UUID___________"+pos);
String strSQL = "UPDATE DeviceDetails SET devicename ='"+ edittext.getText().toString() +"' WHERE uuid = '"+c.getString(c.getColumnIndex("uuid"))+"'" ;
db.select(strSQL);
Log.v("___QUERY ", "_________________"+db.select(strSQL));
slight=light.getText().toString();
salarm=alarm.getText().toString();
Log.v("___EDIT CLASS____________", "__SLIGHT ___AFTER__________"+slight);
Log.v("_____EDIT CLASS_____________", "___SALARM ___AFTER_________"+salarm);
if(pos.equalsIgnoreCase(c.getString(c.getColumnIndex("uuid"))))
{
db.updateData(pos, edittext.getText().toString(),slight,salarm);
}
/*Log.v("_______BACK PRESSED", "______UUID___________"+c.getString(c.getColumnIndex("uuid")));
Log.v("_______cccccc", "______devicename___________"+c.getString(c.getColumnIndex("devicename")));
Log.v("______EDIT IN DB", "______LIGHT___________"+c.getString(c.getColumnIndex("light")));
Log.v("______EDIT IN DB", "______ALARM___________"+c.getString(c.getColumnIndex("alarm")));
*/
/* Log.v("______device_____text", "_______________"+c.getString(c.getColumnIndex("devicename")));
Log.v("___________edittext", "_______________"+edittext.getText().toString());
Log.v("_____ADDRESS______edittext", "_______________"+pos);
*/ Intent intent=new Intent();
intent.putExtra("Dname", edittext.getText().toString());
Log.v("_____edittext in intent________", "__________"+edittext.getText().toString());
intent.putExtra("Daddress",pos);
Log.v("_____edittext in intent________", "__________"+pos);
intent.putExtra("Dlight", slight);
intent.putExtra("Dalarm", salarm);
setResult(RESULT_OK, intent);
finish();
/* Log.v("_______EDIT IN DB", "______devicename___________"+c.getString(c.getColumnIndex("devicename")));
Log.v("______EDIT IN DB", "______LIGHT___________"+c.getString(c.getColumnIndex("light")));
Log.v("______EDIT IN DB", "______ALARM___________"+c.getString(c.getColumnIndex("alarm")));
*/
} while (c.moveToNext());
}
db.close();
super.onBackPressed();
}

Using SharedPreferences with more activities

I would like to save a given that then has to be shared between the main and secondary activity. I can not understand why my app does not work.
This is the Second activity:
switch (find)
{
case 0:
lunedi1.setBackgroundColor(getResources().getColor(R.color.green));
Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
pref=0;
SharedPreferences prefs = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("pref", pref);
editor.commit();
break;
And this is the MainActivity:
SharedPreferences prefs = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
int pref=100;
// Leggiamo l'informazione associata alla proprieta TEXT_DATA
int dato = prefs.getInt("pref", pref);
// Lo impostiamo alla TextView
if(pref==0)
{
lunedi1.setBackgroundColor(getResources().getColor(R.color.green));
}
lunedi1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int a=0;
final Intent intent = new Intent(MainActivity.this, Second.class);
intent.putExtra("info1", info1);
intent.putExtra("a", a);
intent.putExtra("id",id);
startActivity(intent);
}
in this way it should pass the data, and then the background should turn green but this does not happen.
You declare and initialize a new variable pref here
int pref=100;
so here
if(pref==0)
pref == 100 not 0
Not positive but I think you mean
if(dato == 0)
For storing data using SharedPreferences:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Tag","value");
editor.commit();
For retrieving data from SharedPreferences:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Tag","");

Categories

Resources