This is my MainActivity.java where I instanciate static SharedPreferences and it's editor:
public static SharedPreferences settings;
public static SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settings = PreferenceManager.getDefaultSharedPreferences(this);
editor = settings.edit();
Then I make an AsyncTask call to another java class where I try to store a token in onPostExecute method to this SharedPreferences.
#Override
protected void onPostExecute(String result) {
MainActivity.editor.putString("auth_token", result);
MainActivity.editor.commit();
Log.d("token", MainActivity.settings.getString("auth_token", "Nothing"));
}
This Log.d() method outprints the token value in the console, which is "OK". But then I start an acitivity Next.java where I try to get this token on a screen using this:
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
String auth_token_string = MainActivity.settings.getString("auth_token", "Nothing");
text = (TextView) findViewById(R.id.logintxt);
text.setText(auth_token_string);
And the result on the screen is the default String "Nothing".
What am I doing wrong here? ...and is this the right way to use SharedPreferences? I got this idea here in this topic.
EDIT:
Code from AuthorizeActivity.java where I call the asyncTask:
public void getToken(String code){
AsyncTask<String, Void, String> tsk = new Api().execute(code);
Intent i = new Intent(this.getBaseContext(), Next.class);
dialog.dismiss();
startActivity(i);
}
Your settings variable is static, it's initialised in onCreate method of MainActivity when you access settings in Next.java it's not initialised yet.
You have access to SharedPreferences in Next.java (it's shared).
EDIT :
add a update method in MainActivity :
public void update() {
Intent i = new Intent(this.getBaseContext(), Next.class);
startActivity(i);
}
and your postExecute should look like this :
#Override
protected void onPostExecute(String result) {
MainActivity.editor.putString("auth_token", result);
MainActivity.editor.commit();
Log.d("token", MainActivity.settings.getString("auth_token", "Nothing"));
((MainActivity) context).update();
}
Do not use the settings from MainActivity, create a new SharedPrefs instance and call getString method.
Edit: I've created an example of how this should be handled on GitHub
Firstly, I would advise that you don't make your members static; they don't need to be static.
On your Next.class (Perhaps you should rename this, it's not clear what it does), you just need to get a handle on the shared preferences again with your new context:
PreferenceManager.getDefaultSharedPreferences(this);
Please note, there's a difference between getDefaultSharedPreferences and getSharedPreferences - use whichever you think it most appropriate.
Related
I am working on an app, so basically, when the user launches the app for the first time, activity A comes up, which asks the user for a bunch of data. Now, that I have the data, I take the user to activity B. Here, if the user kills the app completely, and relaunches it, the app reopens activity A, instead of B... Is there a way to control this behaviour? I want to be able to control what activity the app should open after a particular action by the user... Note : I am a complete newbie, so I have no idea how to do this.. I tried to ask this up on a google search, but couldn't find anything proper ig.
You can store boolean by shared preference to do that. Here your AcitivityA class. Store user provided data before user land to ActivityB.
public class ActivityA extends AppCompatActivity {
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
try {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean firsttimeLoad = prefs.getBoolean("first_time_load", true);
if (!firsttimeLoad) {
sendToB();
}
} catch (Exception e) {
e.printStackTrace();
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("first_time_load", false);
editor.commit();
//Store user data here
sendToB();
}
});
}
private void sendToB() {
Intent mainIntent = new Intent(ActivityA.this, ActivityB.class);
startActivity(mainIntent);
finish();
}}
The easiest way to use user data in all over the app. Make a separate class for storing user data and make the getter and setter to get and set the data.
public class UserSharedPrefs {
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
#SuppressLint("CommitPrefEdits")
public UserSharedPrefs(Context context) {
sharedPreferences = context.getSharedPreferences("UserData", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
public void setIsLogin(boolean isLogin) {
editor.putBoolean("isLogin", isLogin);
editor.apply();
}
public boolean getIsLogin() {
return sharedPreferences.getBoolean("isLogin", false);
}
In Activity A makes the reference of that class and get the data and use it as your need. And send the user to desired Activity
if(userSharedPrefs.getIsLogin()){
moveToActivityB()
}
Some help would be most thankful for. I have two activities. MainActivity and SharedPrefs. I want the app on open to look if there is some saved preferences. If not it must go to another activity which ask for some detail. Then on pressing the submit button it must save the shared preference and go to the MainActivity. But it doesn't, it just jumps back to the SharedPrefs activity. Now I don't know if my shared preference is not being saved (I thought "editor.commit" will do the job), or is there something wrong with my loop. I did change my loop around, and it is working the other way around, but I can have the whole thing wrong since I'm quite new to Android and Java. Like I said, some help will be appreciated.
Here is my MainActivity with my loop:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
boolean check = sharedPreferences.getBoolean("Check",false);
if(!check){
//Intent intent;
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent); }
else {
setContentView(R.layout.activity_main);
TextView brands = (TextView) findViewById(R.id.brands);
brands.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent brandsIntent = new Intent(MainActivity.this, brands.class);
startActivity(brandsIntent);
}
});
}
}
And here is my SharedPrefs where I try to get some info to add to the shared preferences:
public class SharedPrefs extends AppCompatActivity {
//public static Context context;
EditText ed1,ed2,ed3;
Button b1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shared_prefs);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
Toast.makeText(SharedPrefs.this,"Thanks",Toast.LENGTH_LONG).show();
Intent BackToMainIntent = new Intent(SharedPrefs.this, MainActivity.class);
startActivity(BackToMainIntent);
}
});
}
Please add "Check" key value to SharedPreferences after setting your desired values as it's always return false on MainActivity.
You may also use .apply() instead of .commit().
It doesn't look like you are saving a Boolean Check anywhere in the second activity. So in your first activity, this Boolean never exists and you are getting the default value which you have set to false. You need a preference called `Check' to be set to true in your second activity.
In your SharedPrefs Activity
Change your this piece of code
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
With
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.putBooleon (Check,true);
editor.commit();
Then It will work as you want.
Happy coding :)
here is the Method:
public class SessionManager {
public static void setStatus(Context context, int value, String key) {
// TODO Auto-generated method stub
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = pref.edit();
editor.putInt(key,value);
editor.commit();
}
public static int getStatus(Context c,String key){
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(c);
int a = pref.getInt(key,0);
return a;
}
}
i am trying to set value "1" in shared Preferences on PostExecuteMethod() of Async Task:
protected void onPostExecute(Void result){
super.onPostExecute(result);
progressDialog.dismiss();
Log.i("Setting Status Variables Value in Customer:",""+AndroidUtil.getStatusForServices());
SessionManager.setStatus(context,1,"status");
Log.i("Setting Status Variables Value in Customer after:",""+AndroidUtil.getStatusForServices());
}
But it still it saves 0 in Variable Here is the Logcat:
01-04 03:31:32.430: I/Setting Status Variables Value in Customer:(20879): 0
01-04 03:31:32.440: I/Setting Status Variables Value in Customer after:(20879): 0
You can easily do this in the following way.
First you will need declare the SharedPreferences inside the Activity in this manner:
public class MainActivity extends Activity
{
SharedPreferences sp;
int val=2;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp=this.getSharedPreferences("service_validation", MODE_WORLD_READABLE);
val=sp.getInt("VALIDATION", val);
.
.// you can put here anything code
.
}
.
.// you can put here anything method
.
.
}
Now when you would like to save the value in background asynch task. Please put this code inside onPostExecute(..) method in this manner:
SharedPreferences.Editor editor=sp.edit();
editor.putInt("VALIDATION", 1);
editor.commit();
It is better to use this code on doInBackground(..) method.
After saving the value, refresh or re-run the Activity. It will show the effect .
Enjoy the code!!
If my answer will help you then please support my answer.
With SharedPreferences, i would like to save a value (that will be later the date of last update) and load it. It works well until i shut down my phone or force close my application. It resets the value.
Here's the code :
public class feedPlayer extends Activity
{
public final static String PARAM_USERDETAILS="userdetails";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadvars();
savevars();
}
public void savevars()
{
SharedPreferences parametres = this.getSharedPreferences(PARAM_USERDETAILS, MODE_PRIVATE);
Editor edit = parametres.edit();
edit.clear();
//Global.Maj = "maj"
TextView maj=(TextView) findViewById(R.id.datemaj);
edit.putString("gimli", Global.MAJ);
edit.commit();
maj.setText(Global.MAJ);
}
public void loadvars()
{
SharedPreferences parametres = this.getSharedPreferences(PARAM_USERDETAILS, MODE_PRIVATE);
TextView maj=(TextView) findViewById(R.id.datemaj);
String Smaj = parametres.getString("gimli", Global.MAJ);
maj.setText(Smaj);
}
}
Use onCreate() method to load your data and onDestroy() method to save data:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadvars();
}
#Override
protected void onDestroy() {
super.onDestroy();
savevars();
}
You can use too: onResume() with onPause() method but this two method are reserved for process (start process in onResume() method, stop process in onPause() method)
You are calling the savevars() method each time your activity is created. That means for sure every time your application starts.
In this method you are writing always the same value in the preferences:
edit.putString("gimli", Global.MAJ);
edit.commit();
I have two activity, first on activity "LoginActivity",and second activity "student_ activity".
Please till me how call method "call" from second activity and return value bool to first activity for know user if id and password correct or not correct.
First activity get id and password from "edittext" then send id and password to method in second activity for sure from data from server.
code first activity is :
public class LoginActivity extends Activity{
EditText EdtId;
EditText EdtPassword;
Button btn1;
SharedPreferences prefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
prefs = this.getSharedPreferences(this.getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
EdtId=(EditText)findViewById(R.id.IdStudent);
EdtPassword=(EditText)findViewById(R.id.PasswordStudent);
btn1=(Button)findViewById(R.id.btnLogin);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
createLoginSession(Integer.parseInt(EdtId.getText().toString()),EdtPassword.getText().toString());
//here call second activity for sure from data
Intent intent = new Intent(LoginActivity.this,tofi.android.Student_Activity.class);
startActivity(intent);
finish();
startActivity(new Intent(LoginActivity.this,com.jcxavier.widget.test.BadgeButtonTestActivity.class));
}
});
}
//this method store data in SharedPreferences for get this data in second activity
public void createLoginSession(int id, String password){
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("id", id);
editor.putString("password", password);
editor.commit();
}
}
code second activity is:
public class Student_Activity {
SharedPreferences prefs = this.getSharedPreferences(this.getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.program_student);
NewsLoader call = new NewsLoader();
call.execute(this, true);
}
private Context context;
private boolean pullFromServer = false;
class NewsLoader extends AsyncTask<Object, Void, List<student>> {
private Context context;
private boolean pullFromServer = false;
protected List<student> doInBackground(Object... params) {
context = (Context) params[0];
pullFromServer = (Boolean) params[1];
dataSource.open();
if (pullFromServer) {
//get attribute from SharedPreferences
int id = prefs.getInt("id", 24);
String password = prefs.getString("password","wce");
// studentHandler class for sure password content method call for send to server and //return value if correct or not correct and return value type bool.
bool s;
s = StudentHandler.getInstance().call(context,id,password);
}
}
}
1. Call startActivityForResult() (documentation) and override onActivityResult() (documentation) in the first activity.
2. In the second activity perform whatever validation you need to do (this could also be done in the first activity by passing the data via an Intent) and call setResult(int resultCode, Intent data) (documentation) and then finish(); from the second activity.
If using startActivityForResult() is not feasible for your situation, then you can simply use setResult() and startActivity(), pass any data you need via an Intent, and validate it in onActivityResult().
I just skimmed over this, but here's an example of it in action.