sharedPreferences.getString() return null - java

Im trying to display the user email in a textView using SharedPreferences.
Shared preferences is created in loginActivity.
I try to access it from mainActivity.
My session using sharedPreference work well (with a login boolean saved in sharedPreferences files).
So what's wrong?
- A context error?
- Because I try to access the data from an another activity?
Please help :) Thanks a lot!
Here is the code im using :
Login Activity :
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
//If we will get true
if(loggedIn){
//We will start the Profile Activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
}
...
//Creating a shared preference in a login()
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences.edit();
//Adding values to editor
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true);
editor.putString(Config.EMAIL_SHARED_PREF, email);
//Saving values to editor
editor.commit();
...
Main Activity :
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
email_session = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Private");
usernameText.setText(email_session);
}

to read the stored preferences you need to do:
to save
SharedPreferences spref = getSharedPreferences("your_prefs_name", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = spref.edit();
editor.putString("myTextViewValue", prefVal); //
editor.commit();
to read it
SharedPreferences preferences = getPreferences(Activity.MODE_PRIVATE);
String storedPreference = preferences.getStr("myTextViewValue", null);

This happens because your value is not stored in the shared preferences.
SharedPreferences pref = getSharedPreferences("your Pref Name", 0) // 0 for Private Mode
String name = pref.getString("your key store when login", null); // null is the default value you can put it here "No value". then you will not get null pointer.

Related

How to skip the login activity in relaunching app after a successful login....?

I'm a kinda beginner...and i am working on a project that have a login activity and i want to skip the login activity in relaunching... after a successful login.
Pleas define it well if possible!
Maybe, It's help you.
LoginActivity.java
public void onCreate(){
/*your code in top*/
SharedPreferences prefs= this.getSharedPreferences("APP", Context.MODE_PRIVATE);
if(press.contains("loggedIn")){
startActivity(new Intent(this, NextActivity.class));
finish();
}
/*END*/
}
use shared preferences set a tag after login lets loggedin=true and put a check onCreate() if preferences values is true direct it to next activity
Store a variable in Shared Preferences off the app and check it in oncreate of Login Activity if the value is saved move to main activity using intent.
Setting values in Preference:
// MY_PREFS_NAME - a static String variable like:
public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,
MODE_PRIVATE).edit();
editor.putString("login", "true");
editor.apply();
Retrieve data from preference in Oncreate on Login Activity:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("login", null);
if (restoredText.equals("true")) {
Intent i=new Intent();
i.startActivity(this,Activity_you_want_to_show.class);
finish();
}

Start splash screen after application termination

in my project I have static member as User.current.
If I run the app after it terminates in background, User.current will be null. I get user from server on splash screen.
I want to start splash screen when I run terminated application.
How I can solve this problem?
If you call a server, you probably use an Async task. In Async task
...
#Override
protected Boolean doInBackground(Void... params) {
...
value = jsonObj.getString("value");
return true;
}
protected void onPostExecute(Boolean iHaveValue) {
if(iHaveValue){
// use case 1 or 2
// 1
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("value", value);
startActivity(i);
// 2
SharedPreferences sharedpreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("value", value);
editor.commit();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
}
You get the user on the doInBackground(Void... params). And in the onPostExecute(Boolean iHaveValue) method you simply go to the MainActivity.
You can use the intent to put the value and receive on MainActivity (1) or use a shared preference (2)
(1)
in SplashScreen
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("value", value);
startActivity(i);
in MainActivity
Intent editIntent = new Intent(getApplicationContext(), Splashscreen.class);
(2)
in SplashScreen
SharedPreferences sharedpreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("value", value);
editor.commit();
in MainActivity
SharedPreferences prefs = getSharedPreferences("user", MODE_PRIVATE);
value = prefs.getString("value", "null");
If you need use this value for multiple locations, sharedPreferences helps a lot (case 2). If not, use putExtra to send info to MainActivity (case 1).

How to use shared preferences to save data that get from database? [duplicate]

This question already has answers here:
Shared preferences for creating one time activity
(14 answers)
How to use SharedPreferences in Android to store, fetch and edit values [closed]
(30 answers)
Closed 6 years ago.
I have this button code and it was connect to database
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String name = jsonResponse.getString("name");
String email = jsonResponse.getString("email");
String alamat = jsonResponse.getString("alamat");
int notelp = jsonResponse.getInt("notelp");
String username = jsonResponse.getString("username");
String password = jsonResponse.getString("password");
Intent intent = new Intent(MainActivity.this, adminarea.class);
intent.putExtra("name", name);
intent.putExtra("email", email);
intent.putExtra("alamat", alamat);
intent.putExtra("notelp", notelp);
intent.putExtra("username", username);
intent.putExtra("password", password);
MainActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Login Gagal")
.setNegativeButton("Ulangi", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
i have a table called admin thats contain field name, email and etc.. how can i take the data from databse then save my data like name, email, alamat and the other to shared prefences. then can you help me to call it to another activity?
First of all you have to create SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("YOUR_PREF_NAME", MODE_PRIVATE);
Editor edt = pref.edit();
To add value in preference:
edt.putString("name", name);
edt.putString("email", email);
edt.putString("alamat", alamat);
edt.putString("notelp", notelp);
edt.putString("username",username);
// Save your changes
edt.commit();
Now for getting data from preference:
String name=pref.getString("name", null);
String email=pref.getString("email", null);
String alamat=pref.getString("alamat", null);
String notelp=pref.getString("notelp", null);
String username=pref.getString("username", null);
If you want to clear the preference data:
edt.clear();
edt.commit();
Save like below.
SharedPreferences getPref = PreferenceManager.getDefaultSharedPreferences(this);
Intent intent = new Intent(MainActivity.this, adminarea.class);
intent.putExtra("name", name);
getPref.edit().putString("name",name).apply();
intent.putExtra("email", email);
getPref.edit().putString("email",name).apply();
intent.putExtra("alamat", alamat);
getPref.edit().putString("alamat",name).apply();
intent.putExtra("notelp", notelp);
intent.putExtra("username", username);
intent.putExtra("password", password);
MainActivity.this.startActivity(intent);
Retrieve like this.
SharedPreferences getPref = PreferenceManager.getDefaultSharedPreferences(this);
String name = getPref.getString("name","");
String email = getPref.getString("email","");
String alamat = getPref.getString("alamat","");
Create a class SharePrefUtil
private Context context;
private SharedPreferences prefs;
public SharePrefUtil(Context mContext) {
this.context = mContext;
prefs = this.context.getSharedPreferences("your package name", Context.MODE_PRIVATE);
}
public void setValueInSharePref(String keyName, String value) {
prefs.edit().putString(keyName, value).apply();
}
public String getValueFromSharePref(String keyName) {
return prefs.getString(keyName, "");
}
}
When ever you want to store the value
Just Make a object of class in you activity to get or set a value
for example
SharePreUtil shef = new SharePreUtil(this);
When ever you what to set a value in the activity
shef.setValueInSharePref("key", "yourvalue");
when you want to get value
shef.getValueFromSharePref("key");
All the best...
onCreate() method
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
to get all data server after
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(name, name);
editor.putString(email, email);
.....
editor.commit();
quoting the training guide at https://developer.android.com/training/basics/data-storage/shared-preferences.html
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
and to read
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
In your other activity....first receive data from intent...like this
String name = getIntent().getExtras().getInt("name");
now,save this data into shared prefrences....to do that...you need sharedPreferences.Editor to write data.....like this...
SharedPreferences sp = Your_Activity.this.getSharedPreferences("SharedPreferences_Name", Context.MODE_PRIVATE);
SharedPreferences.Editor spwriter = sp.edit();
spwriter.putString("name",name);
spwriter.commit();
if (success) {
// once you retrieve all the required data
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// Writing data to SharedPreferences
Editor editor = prefs.edit();
editor.putString("name", name);
editor.putString("email", email);
editor.putInt("notelp", notelp);
editor.commit();
// start your AdminArea activity here
}
Retrieve data inn AdminArea class:
// Reading from SharedPreferences
String value = prefs.getString("name", "DEFAULT_STRIGN"); // if the given key not found, it'll take the default string as value
int intValue = prefs.getInt("notelp", -1); // instead of -1, you can give any default value
hope this helps :)
You can save data in SharedPreferences in your activity class as below:
SharedPreferences sharedPreferences = getSharedPreferences("USER_INFO", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name", name);
editor.putString("email", alamat);
editor.putString("alamat", alamat);
editor.commit();
And in your activity where you want to fetch them, do as below:
SharedPreferences sharedPreferences = getSharedPreferences("USER_INFO", Context.MODE_PRIVATE);
String name=sharedPreferences.getString("name", "abc");
String email=sharedPreferences.getString("email", "abc#gmail.com");
To put int,
editor.putInt("number",0);
And to retrive it,
sharedPreferences.getInt("number",0);

SharedPreferences Login

I'm trying to create something that needs to get information in the first time and save it. The app starts at the MainActivity, if it does not have the information needed, the app send you to the MotoActivity. Once the app has the information you don't need to go to the MotoActivity anymore. I know i'm wrong but I don't know how to do.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("valid", 0);
editor.commit();
int n = sp.getInt("valid", -1);
if(n == 0){
editor.putInt("valid", 1);
editor.commit();
startActivity(new Intent(MainActivity.this, MotoActivity.class));
MainActivity.this.finish();
}
First check for the very first time that, if "userLoggedBefore" is true or false from the SharedPreferences, if the user had used the application before and had entered the right credentials, we will save authenticated to true and if he hasn't we will set the default value as false.
SharedPreferences sharedPref = getSharedPreferences("Save", 0);
boolean authenticated = sharedPref.getBoolean("userLoggedBefore", false);
then check -
if (authenticated){
//show your MainActivity
} else {
// show your MotoActivity
}
in your MotoActivity,
//if credentials matches
if(credentialMatches)
SharedPreferences sharedPref = getSharedPreferences(
"Save", 0);
SharedPreferences.Editor prefEditor = sharedPref
.edit();
prefEditor.putBoolean("userLoggedBefore", true);
prefEditor.commit();
else{ // if credentials doesn't match
SharedPreferences sharedPref = getSharedPreferences("Save", 0);
SharedPreferences.Editor prefEditor = sharedPref
.edit();
prefEditor.putBoolean("userLoggedBefore", false);
prefEditor.commit();
}
Try this:
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
// app already has the needed info.
if(sp.getInt("valid", -1) == 1){
// do something
}
// app needs info. first, when you have got the info. in MotoActivity then set preferences key 'valid' to 1
else{
startActivity(new Intent(MainActivity.this, MotoActivity.class));
finish();
}

SharedPreferences not working as expected, cannot read nor write preferences

private void init() {
SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);
// SET VALUE RECORD
record = prefs.getInt("record", 0);
prefs.edit().commit();
}
private void setRecord(int i ) {
SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);
if(i > prefs.getInt("record", 0))
prefs.edit().putInt("record", i);
prefs.edit().commit();
}
private int getRecord() {
int rec;
SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);
rec = prefs.getInt("record", 0);
prefs.edit().commit();
Toast toast = Toast.makeText(this, rec+"", Toast.LENGTH_SHORT);
toast.show();
return rec;
}
this code should set an int and retrieve it, but it doesn't seem to ever set it... can you see why is that?
Think it is best to call the interface SharedPreferences.Editor to edit preferences instead of using prefs.edit().putInt("record", i);. The docs say...
Modifications to the preferences must go through an
SharedPreferences.Editor object to ensure the preference values remain
in a consistent state and control when they are committed to storage.
If you change your setMethod to the following it should work...
private void setRecord(int i ) {
SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
if(i > prefs.getInt("record", 0))
editor.putInt("record", i);
editor.commit();
}
And I guess you are calling the above method setRecord somewhere in your code as I can't see it being called anywhere in the code snippet you pasted.
try
Editor editor = prefs.edit();
editor.putInt("record",i);
editor.commit();

Categories

Resources