Trouble using SharedPreferences to persist data - java

I am trying to save the value of swipesRemaining via the SharedPreferences interface. The value of the variable does not persist. I'm not sure what I am doing wrong.
Here is the source code:
public class MainActivity extends AppCompatActivity {
private TextView swipes;
private int swipesRemaining = 11;
private static final String SWIPES = "swipes";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipes = (TextView) findViewById(R.id.textView);
loadInt();
if(savedInstanceState != null) {
swipesRemaining = savedInstanceState.getInt(SWIPES);
}
updateText(swipesRemaining);
}
public void save(View view) {
saveInt("key", swipesRemaining);
}
public void reset(View view) {
swipesRemaining = 11;
updateText(swipesRemaining);
}
public void swipe(View view) {
if(swipesRemaining > 1) {
swipesRemaining--;
updateText(swipesRemaining);
} else {
Toast toast = Toast.makeText(this, "You ran out of swipes!...Resetting", Toast.LENGTH_SHORT);
toast.show();
reset(view);
}
}
private void updateText(int swipesRemaining) {
swipes.setText("Swipes: " + swipesRemaining);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt(SWIPES, swipesRemaining );
super.onSaveInstanceState(savedInstanceState);
}
private void saveInt(String key, int value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
private void loadInt() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
swipesRemaining = sharedPreferences.getInt("key", swipesRemaining);
Toast toast = Toast.makeText(this, "Swipes left: " + swipesRemaining, Toast.LENGTH_SHORT);
toast.show();
}
}

Related

Wrong calculation after using sharedpreferences

I'm building an app to check prime numbers and display them. the user need to be able to save the number and load it upon restart of the app.
I have problem when retrieving the saved int from Sharedprefrences. the codes saves the int and loads it on the "loaddata" function. But when I start checking if the saved in is a primenumber, the code jumps 2 primenumbers. Eg if I save "11", the next primenumber should be "13" but it jumps to "19".
Would be great if someone could point into the right direction since i'm a bit of newbie.
public class MainActivity extends AppCompatActivity {
private TextView textView;
private EditText editText;
private Button applyPrimeButton;
private Button saveButton;
private Button loadButton;
public static final String SHARED_PREFS = "sharedPrefs";
int max = 500;
int j = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textview);
editText = (EditText) findViewById(R.id.edittext);
applyPrimeButton = (Button) findViewById(R.id.apply_prime_button);
saveButton = (Button) findViewById(R.id.save_button);
loadButton = (Button) findViewById(R.id.load_button);
applyPrimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = j; i <= max; i++) {
if (isPrimeNumber(i)) {
textView.setText(i+"");
j = i+1;
break;
}
}
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveData();
}
});
loadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadData();
}
});
}
public boolean isPrimeNumber(int nummer) {
for (int i = 2; i <= nummer / 2; i++) {
if (nummer % i == 0) {
return false;
}
}
return true;
}
public void saveData() {
SharedPreferences sp = getSharedPreferences(SHARED_PREFS, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
int nummer = Integer.parseInt(textView.getText().toString());
editor.putInt("prime_save", nummer);
editor.commit();
Toast.makeText(this, "Data saved", Toast.LENGTH_SHORT).show();
}
public void loadData() {
SharedPreferences sp = getSharedPreferences(SHARED_PREFS, Activity.MODE_PRIVATE);
int nummer = sp.getInt("prime_save",0);
textView.setText(String.valueOf(nummer));
}
}
Several issues:
You are not updating j to the correct value when loading data, and instead relying on what you are displaying in the textview.
To find prime number, it is enough to check until the square root of the original number and not half of it.
Try this:
applyPrimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(j<max ){
if (isPrimeNumber(j)) {
textView.setText(j+"");
j++;
}
}
}
});
public void saveData() {
SharedPreferences sp = getSharedPreferences(SHARED_PREFS, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("prime_save", j);
editor.commit();
Toast.makeText(this, "Data saved", Toast.LENGTH_SHORT).show();
}
public void loadData() {
SharedPreferences sp = getSharedPreferences(SHARED_PREFS, Activity.MODE_PRIVATE);
int nummer = sp.getInt("prime_save",0);
j = nummer;
textView.setText(String.valueOf(nummer));
}

SharedPrefenrences not storing boolean value

Am trying save boolean FAVOURITE data in sharedPreferences. when phone is rotated or closed .It is not working it is taking default value. I don't know whats wrong with this code. i am unable to figure out whats the problem is can someone show me the problem with the code
//Context context =this;
String FAVOURITE = "selected";
boolean favourite = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState!=null){
favourite = savedInstanceState.getBoolean(FAVOURITE,false);
Toast.makeText(this,""+favourite,Toast.LENGTH_SHORT).show();
}
final Bundle queryBundle = new Bundle();
movieObject=(CardsClass)getIntent().getSerializableExtra("movieObject");
setTitle(movieObject.getmTitle());
setContentView(R.layout.activity_details);
final ImageView fav = (ImageView)findViewById(R.id.fav);
fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (favourite == false) {
favourite = true;
fav.setImageResource(R.drawable.fav_on);
Toast.makeText(DetailsActivity.this, favourite + " is added to favourites", Toast.LENGTH_SHORT).show();
queryBundle.putBoolean(FAVOURITE,favourite);
}
else if(favourite){
favourite=false;
fav.setImageResource(R.drawable.fav_off);
queryBundle.putBoolean(FAVOURITE,favourite);
Toast.makeText(DetailsActivity.this, movieObject.getmTitle() + " is removed from favourites", Toast.LENGTH_SHORT).show();
}
}
});
Actually, you're doing the wrong thing. You should do something like:
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(FAVOURITE, favorite); // then you can check the favorite value in onCreate as well.
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
this.favorite = savedInstanceState.getBoolean(FAVOURITE);
// do something here when restore.
super.onRestoreInstanceState(savedInstanceState);
}
To write or read in the SharedPreferences
Write:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(FAVORITE, favorite);
editor.commit();
Read:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Boolean favorite = sharedPref.getBoolean(FAVORITE, true);

How to restart Handler after changing data value?

Good morning StackOverFlow i'm having some issues with Handler i'm trying to start in the MainActivity my Client.java after 50 seconds and also send the message and stop the client and that's work but i have to reopen the connection on every change of ip_txt or term_txt in settings.java
(data is saved from a EditText to DB by clicking on a button )
here is my MainActivity :
public class MainActivity extends AppCompatActivity {
Server server;
Client client;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
new ConnectTask().execute("");
if (client != null) {
client.sendMessage("IP#" + ipp + " " + "N#" + trm);
}
if (client != null) {
client.stopClient();
}
}
};
settings Settings;
public static TextView terminale, indr, msg;
TextView log;
String ipp,trm;
DataBaseHandler myDB;
allert Allert;
SharedPreferences prefs;
String s1 = "GAB Tamagnini SRL © 2017 \n" +
"Via Beniamino Disraeli, 17,\n" +
"42124 Reggio Emilia \n" +
"Telefono: 0522 / 38 32 22 \n" +
"Fax: 0522 / 38 32 72 \n" +
"Partita IVA, Codice Fiscale \n" +
"Reg. Impr. di RE 00168780351 \n" +
"Cap. soc. € 50.000,00 i.v. \n" + "" +
"REA n. RE-107440 \n" +
"presso C.C.I.A.A. di Reggio Emilia";
ImageButton settings, helps, allerts, home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Utils.darkenStatusBar(this, R.color.colorAccent);
server = new Server(this);
myDB = DataBaseHandler.getInstance(this);
msg = (TextView) findViewById(R.id.msg);
log = (TextView) findViewById(R.id.log_avviso);
settings = (ImageButton) findViewById(R.id.impo);
helps = (ImageButton) findViewById(R.id.aiut);
allerts = (ImageButton) findViewById(R.id.msge);
home = (ImageButton) findViewById(R.id.gab);
terminale = (TextView) findViewById(R.id.terminal);
indr = (TextView) findViewById(R.id.indr);
final Cursor cursor = myDB.fetchData();
if (cursor.moveToFirst()) {
do {
indr.setText(cursor.getString(1));
terminale.setText(cursor.getString(2));
Client.SERVER_IP = cursor.getString(1);
trm = cursor.getString(2);
} while (cursor.moveToNext());
}
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
ipp = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
handler.postDelayed(runnable,5000);
cursor.close();
server.Parti();
home.setOnClickListener(new View.OnClickListener() {
int counter = 0;
#Override
public void onClick(View view) {
counter++;
if (counter == 10) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setMessage(s1);
builder.show();
counter = 0;
}
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent impostazioni = new Intent(getApplicationContext(), settingsLogin.class);
startActivity(impostazioni);
}
});
helps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent pgHelp = new Intent(getApplicationContext(), help.class);
startActivity(pgHelp);
}
});
allerts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Server.count = 0;
SharedPreferences prefs = getSharedPreferences("MY_DATA", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.apply();
msg.setVisibility(View.INVISIBLE);
Intent pgAlert = new Intent(getApplicationContext(), allert.class);
startActivity(pgAlert);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
server.onDestroy();
}
public class ConnectTask extends AsyncTask<String, String, Client> {
#Override
protected Client doInBackground(String... message) {
client = new Client(new Client.OnMessageReceived() {
#Override
public void messageReceived(String message) {
publishProgress(message);
}
});
client.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d("test", "response " + values[0]);
}
}
}
Here is my settings.java:
public class settings extends AppCompatActivity {
TextView indr;
Client client;
EditText ip_txt,term_txt;
ImageButton home;
Button save;
DataBaseHandler myDB;
MainActivity activity;
String ipp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDB = DataBaseHandler.getInstance(this);
setContentView(R.layout.activity_settings);
Utils.darkenStatusBar(this, R.color.colorAccent);
home = (ImageButton) findViewById(R.id.stgbtn);
indr = (TextView) findViewById(R.id.ipp);
ip_txt = (EditText) findViewById(R.id.ip);
term_txt = (EditText) findViewById(R.id.nTermin);
save = (Button) findViewById(R.id.save);
Cursor cursor = myDB.fetchData();
if(cursor.moveToFirst()){
do {
ip_txt.setText(cursor.getString(1));
term_txt.setText(cursor.getString(2));
}while(cursor.moveToNext());
}
cursor.close();
AddData();
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
ipp = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
indr.setText(ipp);
}
public void AddData() {
save.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
myDB.insertData(ip_txt.getText().toString(),
term_txt.getText().toString());
MainActivity.indr.setText(ip_txt.getText().toString());
MainActivity.terminale.setText(term_txt.getText().toString());
Client.SERVER_IP = ip_txt.getText().toString();
finish();
}
}
);
}
}
( If I did not explain it i want to start the handler on the start of the app and also to start it again or immediatly after i change the data in EditText ip_txt or in EditText term_txt )
I would create Variables to store the handler and the runnable, then when you want to restart it just use:
yourHandler.removeCallback(yourRunnable);
yourHandler.postDelayed(yourRunnable,time);
and to start it, just do it as you did,
yourHandler.postDelayed(yourRunnable,5000);
Hope is what you are looking for.
How to create them:
public class ClassName{
Handler yourHandler = new Handler();
Runnable yourRunnable = new Runnable(){
#Override
public void run() {
//yourCode
}
};
// Rest of class code
}
Is just same as you did in your code but in a variable.

How to get data from getter setter class?

I am beginner in android development , I have some issue please help me.
I have 2 screen Login and After Login , I have set User id in login class and i want to use that user_id in after login how to get , when I use get method find Null how to resolve this problem.
here is my Login Code`public class LoginActivity extends FragmentActivity {
private EditText userName;
private EditText password;
private TextView forgotPassword;
private TextView backToHome;
private Button login;
private CallbackManager callbackManager;
private ReferanceWapper referanceWapper;
private LoginBean loginBean;
Context context;
String regid;
GoogleCloudMessaging gcm;
String SENDER_ID = "918285686540";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
static final String TAG = "GCM";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
Utility.setStatusBarColor(this, R.color.tranparentColor);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/OpenSans_Regular.ttf");
setupUI(findViewById(R.id.parentEdit));
userName = (EditText) findViewById(R.id.userName);
userName.setTypeface(tf);
userName.setFocusable(false);
userName.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent paramMotionEvent) {
userName.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
password = (EditText) findViewById(R.id.passwordEText);
password.setTypeface(tf);
password.setFocusable(false);
password.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
password.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setTypeface(tf);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ForgotPasswordActivity.class);
startActivity(intent);
}
});
backToHome = (TextView) findViewById(R.id.fromLogToHome);
backToHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
login = (Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLoginTask();
// Intent intent = new Intent(getApplicationContext(), AfterLoginActivity.class);
// startActivity(intent);
}
});
}
private void doLoginTask() {
String strEmail = userName.getText().toString();
String strPassword = password.getText().toString();
if (strEmail.length() == 0) {
userName.setError("Email Not Valid");
} else if (!Utility.isEmailValid(strEmail.trim())) {
userName.setError("Email Not Valid");
} else if (strPassword.length() == 0) {
password.setError(getString(R.string.password_empty));
} else {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.putOpt(Constants.USER_NAME, strEmail);
jsonObject.putOpt(Constants.USER_PASSWORD, strPassword);
jsonObject.putOpt(Constants.DEVICE_TOKEN, "11");
jsonObject.putOpt(Constants.MAC_ADDRESS, "111");
jsonObject.putOpt(Constants.GPS_LATITUDE, "1111");
jsonObject.putOpt(Constants.GPS_LONGITUDE, "11111");
} catch (JSONException e) {
e.printStackTrace();
}
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
CustomJSONObjectRequest jsonObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, Constants.USER_LOGIN_URL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
Log.e("LoginPage", "OnResponse =" + response.toString());
getLogin(response);
//LoginBean lb = new LoginBean();
//Toast.makeText(getApplicationContext(),lb.getFull_name()+"Login Successfuly",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),AfterLoginActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Something, wrong please try again",Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.e("LoginPage", "Url= " + Constants.USER_LOGIN_URL + " PostObject = " + jsonObject.toString());
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
}
public void getLogin(JSONObject response) {
LoginBean loginBean = new LoginBean();
if (response != null){
try {
JSONObject jsonObject = response.getJSONObject("data");
loginBean.setUser_id(jsonObject.getString("user_id"));
loginBean.setFull_name(jsonObject.getString("full_name"));
loginBean.setDisplay_name(jsonObject.getString("display_name"));
loginBean.setUser_image(jsonObject.getString("user_image"));
loginBean.setGender(jsonObject.getString("gender"));
loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(),"User id is "+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
finish();
}
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
}
}
}
`
here is my AfterLogin class`public class AfterLoginActivity extends FragmentActivity {
private ImageView partyIcon;
private ImageView dealIcon;
private ImageView deliveryIcon;
private TextView txtParty;
private TextView txtDeals;
private TextView txtDelivery;
boolean doubleBackToExitPressedOnce = false;
int backButtonCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
Utility.setStatusBarColor(this, R.color.splash_status_color);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
partyIcon = (ImageView)findViewById(R.id.party_Icon);
dealIcon = (ImageView)findViewById(R.id.deals_Icon);
deliveryIcon = (ImageView)findViewById(R.id.delivery_Icon);
partyIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), BookPartyActivity.class);
startActivity(intent);
}
});
dealIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), DealsActivity.class);
startActivity(intent);
}
});
deliveryIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginBean loginBean = new LoginBean();
Toast.makeText(getBaseContext(),"Auth"+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),MyAuction.class);
startActivity(intent);
}
});
}
/*
public void onBackPressed()
{
if (doubleBackToExitPressedOnce)
{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
doubleBackToExitPressedOnce = true;
Toast.makeText(this, "you have logged in ,plz enjoy the party", Toast.LENGTH_LONG).show();
new Handler().postDelayed(new Runnable()
{
public void run()
{
doubleBackToExitPressedOnce = false;
}
}
, 2000L);
}*/
#Override
public void onBackPressed()
{
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
}`
here is LoginBean`public class LoginBean {
private String user_id;
private String full_name;
private String display_name;
private String user_image;
private String gender;
private String authorization_key;
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_id() {
return user_id;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getFull_name() {
return full_name;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
public String getDisplay_name() {
return display_name;
}
public void setUser_image(String user_image) {
this.user_image = user_image;
}
public String getUser_image() {
return user_image;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}
public void setAuthorization_key(String authorization_key) {
this.authorization_key = authorization_key;
}
public String getAuthorization_key() {
return authorization_key;
}
}`
//in your both activity or create class
private SharedPreferences mSharedPreferences;
//in your login on getLogin() method ;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
//save actual drawable id in this way.
if(mSharedPreferences==null)
return;
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putInt("userId", loginBean.getUser_id());
editor.commit();
// in your after login acvtivity on deliverable method
private SharedPreferences mSharedPreferences;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
if(mSharedPreferences==null)
return;
string userId = mSharedPreferences.getString("userId", "");
You can write and apply below mentioned steps (Please ignore any syntactical error, I am giving you simple logical steps).
step 1 - Make a global application level loginObject setter and getter like below. Make sure to define Application class in your manifest just like you do it for your LoginActivity
public class ApplicationClass extends Application{
private LoginBean loginObject;
public void setLoginBean(LoginBean object) {
this.loginObject = object;
}
public LoginBean getName() {
return this.loginObject
}
}
Step - 2 Get an instance of ApplicationClass object reference in LoginActivity to set this global loginObject
e.g. setLogin object in your current Loginactivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
appObject.setLoginBean(loginObject)
}
Step - 3 Get an instance of ApplicationClass object reference in any other Activity get this global loginObject where you need to access this login data.
e.g. getLogin object in your otherActivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
LoginBean loginObject = appObject.getLoginBean();
}

How can I make my android app have SharedPreferences as just one set of preferences, so that I can control it and clear the preferences with a button

I am trying to have SharedPreferences once and control it to different methods rather than having different SharedPreferences in different methods. I have SharedPreferences in the onCreate, LoadPreferences, SavePreferences and ClearTextViews methods. I want to make it so that I have preferences saved to the TextViews from entered text in the EditText and then be able to clear them all with a button. Please help me if you can. Here is the relevant code:
public class notesActivity extends Activity implements OnClickListener
{
Button saveNote;
Button clearText;
EditText note;
TextView textSavedNote1, textSavedNote2, textSavedNote3, textSavedNote4, textSavedNote5, textSavedNote6;
SharedPreferences spNote;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
saveNote = (Button)this.findViewById(R.id.saveNotes);
saveNote.setOnClickListener(this);
clearText = (Button)this.findViewById(R.id.clearAllText);
clearText.setOnClickListener(this);
textSavedNote1 = (TextView)findViewById(R.id.stringSavedNote1);
textSavedNote2 = (TextView)findViewById(R.id.stringSavedNote2);
textSavedNote3 = (TextView)findViewById(R.id.stringSavedNote3);
textSavedNote4 = (TextView)findViewById(R.id.stringSavedNote4);
textSavedNote5 = (TextView)findViewById(R.id.stringSavedNote5);
textSavedNote6 = (TextView)findViewById(R.id.stringSavedNote6);
note = (EditText)this.findViewById(R.id.notes);
spNote = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = spNote.edit();
edit.putString("note"+saveNote,note.getText().toString());
edit.commit();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Goes back to the home screen
case R.id.item1: Intent i = new Intent(notesActivity.this, UserSettingActivity.class);
startActivity(i);
case R.id.item2:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
// Refreshes the page.
case R.id.item3:
finish();
startActivity(getIntent());
default:
return super.onOptionsItemSelected(item);
}
}
public void onClick (View v){
if(v==saveNote){
SavePreferences("NOTE1", note.getText().toString());
LoadPreferences();
note.setText("");
if(textSavedNote1.getText().toString().length()>0){
SavePreferences("NOTE2", note.getText().toString());
LoadPreferences();
note.setText("");
}
else{
}
}
else if(v==clearText){
ClearTextViews();
}
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedNote1 = sharedPreferences.getString("NOTE1", "");
String strSavedNote2 = sharedPreferences.getString("NOTE2", "");
String strSavedNote3 = sharedPreferences.getString("NOTE3", "");
String strSavedNote4 = sharedPreferences.getString("NOTE4", "");
String strSavedNote5 = sharedPreferences.getString("NOTE5", "");
String strSavedNote6 = sharedPreferences.getString("NOTE6", "");
textSavedNote1.setText(strSavedNote1);
textSavedNote2.setText(strSavedNote2);
textSavedNote3.setText(strSavedNote3);
textSavedNote4.setText(strSavedNote4);
textSavedNote5.setText(strSavedNote5);
textSavedNote6.setText(strSavedNote6);
}
private void ClearTextViews(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
}
There are some links that can be helpfull
How to use SharedPreferences in Android to store, fetch and edit values
http://developer.android.com/reference/android/content/SharedPreferences.html
Examples
How to use SharedPreferences
http://android-er.blogspot.com.br/2011/01/example-of-using-sharedpreferencesedito.html
Try the code below.
/*I have added one more button, on click on that button i have set call clearText function and set all text empty, each time before clicking on save button you click first clear button then next value will be inserted in next textview.*/
public class SharedPreferenceJustOneSetOfPreferencesActivity extends Activity implements OnClickListener{
private Button saveNote,clearText,ClearAll;
static TextView textSavedNote1, textSavedNote2, textSavedNote3, textSavedNote4, textSavedNote5, textSavedNote6;
private EditText note;
private SharedPreferences spNote;
private static final String TAG = SharedPreferenceJustOneSetOfPreferencesActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
saveInPreference();
}
private void initView() {
textSavedNote1 = (TextView)findViewById(R.id.textSavedNote1);
textSavedNote2 = (TextView)findViewById(R.id.textSavedNote2);
textSavedNote3 = (TextView)findViewById(R.id.textSavedNote3);
textSavedNote4 = (TextView)findViewById(R.id.textSavedNote4);
textSavedNote5 = (TextView)findViewById(R.id.textSavedNote5);
textSavedNote6 = (TextView)findViewById(R.id.textSavedNote6);
note = (EditText)findViewById(R.id.note);
saveNote = (Button)findViewById(R.id.saveNote);
clearText = (Button)findViewById(R.id.clearText);
ClearAll = (Button)findViewById(R.id.ClearAll);
saveNote.setOnClickListener(this);
clearText.setOnClickListener(this);
ClearAll.setOnClickListener(this);
}
private void saveInPreference() {
spNote = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = spNote.edit();
edit.putString("note"+saveNote,note.getText().toString());
edit.commit();
}
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.item1: Intent i = new Intent(SharedPreferenceJustOneSetOfPreferencesActivity.this, UserSettingActivity.class);
startActivity(i);
case R.id.item2:
Intent intent = new Intent(SharedPreferenceJustOneSetOfPreferencesActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
case R.id.item3:
finish();
startActivity(getIntent());
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View view) {
if (view == saveNote) {
String textvedNote1 =textSavedNote1.getText().toString();
String textvedNote2= textSavedNote2.getText().toString();
String textvedNote3 =textSavedNote3.getText().toString();
String textvedNote4= textSavedNote4.getText().toString();
String textvedNote5 =textSavedNote5.getText().toString();
String textvedNote6= textSavedNote6.getText().toString();
if (textvedNote1.equals("")) {
SavePreferences("NOTE1", note.getText().toString());
Log.e(TAG,"textvedNote1: Inside "+textvedNote1.length());
LoadPreferences();
note.setText("");
}else if (textvedNote2.equals("")&& !textvedNote1.equals("")) {
SavePreferences("NOTE2", note.getText().toString());
Log.e(TAG,"textvedNote2: Inside "+textvedNote1.length());
LoadPreferences();
note.setText("");
} else if (textvedNote3.equals("")&& !textvedNote2.equals("")) {
Log.e(TAG,"textvedNote3: Inside "+textvedNote2.length());
SavePreferences("NOTE3", note.getText().toString());
LoadPreferences();
note.setText("");
} else if (textvedNote4.equals("")&& !textvedNote3.equals("")) {
Log.e(TAG,"textvedNote4: Inside "+textvedNote3.length());
SavePreferences("NOTE4", note.getText().toString());
LoadPreferences();
note.setText("");
} else if (textvedNote5.equals("")&& !textvedNote4.equals("")) {
Log.e(TAG,"textvedNote5: Inside "+textvedNote4.length());
SavePreferences("NOTE5", note.getText().toString());
LoadPreferences();
note.setText("");
} else if (textvedNote6.equals("")&& !textvedNote5.equals("")) {
SavePreferences("NOTE6", note.getText().toString());
Log.e(TAG,"textvedNote6: Inside "+textvedNote5.length());
LoadPreferences();
note.setText("");
}
} else if (view == clearText) {
ClearTextViews();
}else if (view == ClearAll){
ClearTextViews();
textSavedNote1.setText("");
textSavedNote2.setText("");
textSavedNote3.setText("");
textSavedNote4.setText("");
textSavedNote5.setText("");
textSavedNote6.setText("");
}
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedNote1 = sharedPreferences.getString("NOTE1", "");
String strSavedNote2 = sharedPreferences.getString("NOTE2", "");
String strSavedNote3 = sharedPreferences.getString("NOTE3", "");
String strSavedNote4 = sharedPreferences.getString("NOTE4", "");
String strSavedNote5 = sharedPreferences.getString("NOTE5", "");
String strSavedNote6 = sharedPreferences.getString("NOTE6", "");
if (!strSavedNote1.equals("")) {
Log.e(TAG,"LoadPreferences1: "+strSavedNote1);
textSavedNote1.setText(strSavedNote1);
} else if (!strSavedNote2.equals("")) {
Log.e(TAG,"LoadPreferences2: "+strSavedNote2);
textSavedNote2.setText(strSavedNote2);
} else if (!strSavedNote3.equals("")) {
Log.e(TAG,"LoadPreferences3: "+strSavedNote3);
textSavedNote3.setText(strSavedNote3);
} else if (!strSavedNote4.equals("")) {
textSavedNote4.setText(strSavedNote4);
} else if (!strSavedNote5.equals("")) {
textSavedNote5.setText(strSavedNote5);
} else if (!strSavedNote6.equals("")) {
textSavedNote6.setText(strSavedNote6);
}
}
private void ClearTextViews(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
}

Categories

Resources