Can not access shared preferences data properly - java

I am trying to send one string through shared preferences to another activity. I want to call the same activity back.
I have multiple activities which calls one activity in common. So I want to Identify from which the common activity has been called and want to go back to the same activity from which it is called.
This I have done in 1st Activity:
SharedPreferences mPrefs = getSharedPreferences("Type", 0);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("gosend","1");
editor.commit();
In 2nd activity
SharedPreferences mPrefs = getSharedPreferences("Type1", 0);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("goride", "2");
editor.commit();
In common activity
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences mPrefs = getSharedPreferences("Type", 0);
activityType = mPrefs.getString("gosend", "1");
SharedPreferences mPrefs1 = getSharedPreferences("Type1",0);
goride = mPrefs1.getString("goride","2");
if(activityType.equals("1")) {
intent = new Intent(ChooseFromMapActivity.this, GoSend.class);
startActivity(intent);
}
if(goride.equals("2"))
{
intent = new Intent(ChooseFromMapActivity.this, GoRideActivity.class);
startActivity(intent);
}
}
});
}
Now when I am calling common activity from 1st activity , I am not returning back to the same rather 2nd activity is getting called.
whats going wrong??
Edit
I tried this : Still dose not work
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences mPrefs = getSharedPreferences("Type", 0);
activityType = mPrefs.getString("gosend", "0");
// SharedPreferences mPrefs1 = getSharedPreferences("Type1",0);
// goride = mPrefs1.getString("goride","0");
switch (activityType){
case "0":
intent = new Intent(ChooseFromMapActivity.this, GoSend.class);
startActivity(intent);
break;
case "1":
intent = new Intent(ChooseFromMapActivity.this, GoRideActivity.class);
startActivity(intent);
break;
}
}

you are calling the same sharepreference while writing both files
note from 1st activity
-->> SharedPreferences.Editor editor = mPrefs.edit();
note from 2nd activity
-->> SharedPreferences mPrefs = getSharedPreferences("Type1", 0);
and in your common activity...
-->SharedPreferences mPrefs = getSharedPreferences("Type", 0);
activityType = mPrefs.getString("gosend", "1");
SharedPreferences mPrefs1 = getSharedPreferences("Type1",0);
goride = mPrefs1.getString("goride","2");
you are referring to the same file as in your code, BUT really, what you were trying to do is to refer to 2 seperate sharepreference...
mPref & mPref1....
so, you have to decide to use either one, but not two...
EDIT --->> UPDATE CODE SUGGESTION.
in your Activity 1
SharedPreferences mPrefs = getSharedPreferences("Type", 0);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("gosend","1");
editor.commit();
in your Activity 2
SharedPreferences mPrefs = getSharedPreferences("Type1", 0);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("gosend", "2");
editor.commit();
==>> make sure the "gosend" values are the one you wanted. you are taking measure on the changes made to "gosend", because in your code, you wanted to test the "gosend" values, and open different activities based on the values.
in your common activity
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences mPrefs = getSharedPreferences("Type", 0);
activityType = mPrefs.getString("gosend", "0");
// SharedPreferences mPrefs1 = getSharedPreferences("Type1",0);
// goride = mPrefs1.getString("goride","0");
switch (activityType){
case "0":
intent = new Intent(ChooseFromMapActivity.this, GoSend.class);
startActivity(intent);
break;
case "1":
intent = new Intent(ChooseFromMapActivity.this, GoRideActivity.class);
startActivity(intent);
break;
}
}
}
** good luck, hope this help..

Try the following code in your common activity:
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences mPrefs = getSharedPreferences("Type", 0);
activityType = mPrefs.getString("gosend", "0");
SharedPreferences mPrefs1 = getSharedPreferences("Type1",0);
goride = mPrefs1.getString("goride","0");
if(activityType.equals("1")) {
intent = new Intent(ChooseFromMapActivity.this, GoSend.class);
startActivity(intent);
}
else if(goride.equals("2"))
{
intent = new Intent(ChooseFromMapActivity.this, GoRideActivity.class);
startActivity(intent);
}
}
});
}
Let me know is your problem is solved. Your default value matches with the required value so every time first if statement will become true.
Hope this helps.

Related

Put username to other activity with sharedpreference

I have value 'username' in MainActivity, get from login session.
How i can put this 'username' to other activity?
I use sharedpreference.
Can you help me? Pleasee
Try this:
To write the username:
SharedPreferences settings = getSharedPreferences("preferences", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", username);
editor.commit();
To get the username:
SharedPreferences settings = getSharedPreferences("preferences", 0);
String username = settings.getString("username", ""); //sets to "" if fails
Or you can pass it through the intent using a bundle:
Bundle bundle = new Bundle();
bundle.putString("username", username);
Intent intent = new Intent(this, JoinChatActivity.class);
intent.putExtras(bundle);
startActivity(this, NewActivity.class);
Try this:
First you initialize the SharedPreferences in Top like this
SharedPreferences sharedPreferences;
after that get the value json like(username) and put the value SharedPreferences
username= obj1.getString("username");
// Using shared preference storing the data in key value pair
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", username);
editor.apply();
And get the value in next activity like this
SharedPreferences pref = getSharedPreferences("MyPref", 0);
String username= pref.getString("username", null);
Pass the value in parameter like this
params.put("username", username);
i think it helps you
Or you can transfer the value using Intent. for example:
This is MainActivity.class
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = new Intent (getApplicationContext(), MainActivity.class);
intent.putExtra("userName", username);
getApplicationContext().startActivities(new Intent[] {intent});
}
Other.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_detail);
Intent intent = this.getIntent();
String username = intent.getExtras().toString("userName");
}

SharedPreferences Logout not working

I have 2 Activities, Authentication and Mainpage.
In Authentication, it checks if the user is logged in, if the user is logged in, redirect it to Mainpage.class. This is how Authentication checks if the user is logged in and redirect it.
SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
Intent intent = new Intent(this, Mainpage.class);
startActivity(intent);
}
In Mainpage, I have a button which is a logout button and onClick event it use the logOut function that I've created. This is how logout button works:
void logOut(){
SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
SharedPreferences.Editor blockEdit = blockSession.edit();
blockEdit.clear();
blockEdit.apply();
finish();
Intent intent = new Intent(Mainpage.this, Authentication.class);
startActivity(intent);
}
The problem here is when I click the logout button, I just kept redirecting to Mainpage.
The problem is that you are finishing the activity before starting the Intent..That is why it shows MainPage when the logout() is called..Instead, you will have to finish the activity after the intent has been called.
Thus replace your code as follows
void logOut(){
SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
SharedPreferences.Editor blockEdit = blockSession.edit();
blockEdit.clear();
blockEdit.apply();
//finish(); /****<-----commented out this line---****/
Intent intent = new Intent(Mainpage.this, Authentication.class);
startActivity(intent);
finish(); /****<------Moved to here---****/
}
UPDATE
Since you are adding onClick attribute in your xml for the button and you are getting an error
java.lang.IllegalStateException: Could not find method logOut(View) in
a parent or ancestor Context for android:onClick attribute defined on
view class android.support.v7.widget.AppCompatButton with id
'logoutButton'
Replace your function as follows
void logOut(View v){
SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
SharedPreferences.Editor blockEdit = blockSession.edit();
blockEdit.clear();
blockEdit.apply();
//finish(); /****<-----commented out this line---****/
Intent intent = new Intent(Mainpage.this, Authentication.class);
startActivity(intent);
finish(); /****<------Moved to here---****/
}
However, I dont think it's a good idea to solve this way. You should implement onClickListener inside your adapter or your fragment.
Try this, hope it helps
void logOut(){
SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
SharedPreferences.Editor blockEdit = blockSession.edit();
blockEdit.clear();
blockEdit.commit(); // to apply the changes
finish();
Intent intent = new Intent(Mainpage.this, Authentication.class);
startActivity(intent);
}
Replace your this line of code
blockEdit.apply();
with
blockEdit.commit();
Followed by your activity calling intent.Hope it helps.
Just reset your SharedPreferences KEY logged_in value to false using blockEdit.putBoolean("logged_in", false) and commit.
Try this:
void logOut(View view) {
SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
SharedPreferences.Editor blockEdit = blockSession.edit();
// Set logged_in value to false
blockEdit.putBoolean("logged_in", false);
blockEdit.commit();
// Start Authentication
Intent intent = new Intent(Mainpage.this, Authentication.class);
startActivity(intent);
// Finish MainPage
finish();
}
#. Best practice is to create a common class for session management and use this from anywhere in your application as per your needs.
Crate a SessionManager class like below:
public class SessionManager {
// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
Context context;
// Shared Preferences
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "MY_APP";
private static final String KEY_IS_LOGGED_IN = "IS_LOGGED_IN";
private static final String KEY_USER_ID = "USER_ID";
private static final String KEY_USER_EMAIL = "USER_EMAIL";
private static final String KEY_USER_USERNAME = "USER_USERNAME";
public SessionManager(Context context) {
this.context = context;
sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = sharedPreferences.edit();
}
public void setLogin(boolean isLoggedIn) {
editor.putBoolean(KEY_IS_LOGGED_IN, isLoggedIn);
// commit changes
editor.commit();
Log.d(TAG, "User login session modified!");
}
public boolean isLoggedIn() {
return sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false);
}
public void setUserId(int id) {
editor.putInt(KEY_USER_ID, id);
editor.commit();
}
public int getUserId() {
return sharedPreferences.getInt(KEY_USER_ID, 0);
}
public void setUsername(String username) {
editor.putString(KEY_USER_USERNAME, username);
editor.commit();
}
public String getUsername() {
return sharedPreferences.getString(KEY_USER_USERNAME, "user1234");
}
public void setEmail(String email) {
editor.putString(KEY_USER_EMAIL, email);
editor.commit();
}
public String getEmail() {
return sharedPreferences.getString(KEY_USER_EMAIL, "default#gmail.com");
}
}
USE:
LOGIN:
SessionManager sessionManager = new SessionManager(getApplicationContext());
sessionManager.setLogin(true);
sessionManager.setUserId(userId);
// Launch MainPage
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
LOGOUT:
SessionManager sessionManager = new SessionManager(getApplicationContext());
sessionManager.setLogin(false);
// Launch LoginPage
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
Hope this will help~
Put finish() here in the code of yours
SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
Intent intent = new Intent(this, Mainpage.class);
startActivity(intent);
finish();
}
UPDATE
I went through your code and found a small mistake in it :
In your OnCreate method you are using :
SharedPreferences blockSession = PreferenceManager.getDefaultSharedPreferences(this);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(!isLoggedIn){
Intent intent = new Intent(this, Mainpage.class);
startActivity(intent);
finish();
}
Mistakes :
You are getting your sharedPreference value in on create method But when you are clearing sharedPreference on logout it doesn't have any shaved sharedPreference value . so it takes false as default value as you mentioned here :
boolean isLoggedIn = blockSession.getBoolean("logged_in", false); // false is default value.
And you if conditioned is always true because you have false value every time you logout.
Solution :
change if condition as follows :
if(isLoggedIn){
Intent intent = new Intent(this, Mainpage.class);
startActivity(intent);
finish();
}
Try it.
SharedPreferences mySPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = mySPrefs.edit();
editor.remove(String key);
editor.apply();

handling intents using SharedPreferences

Please how can i use a button in an intro activity that when pressed will take me to the main activity. The intro page is meant to show on the first use of the app.
here is my IntroActivity.java onCreate method
Button switchButton = (Button) findViewById(R.id.switchButton);
switchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if (pref.getBoolean("activity_executed", false)) {
Intent switchSwag = new Intent(IntroActivity.this, MainActivity.class);
startActivity(switchSwag);
finish();
} else {
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
}
}
});
I am assuming you want to show the intro activity only during the first time the app is started. Add the following code inside onCreate and NOT in on button click.
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if (pref.getBoolean("activity_executed", false)) {
Intent switchSwag = new Intent(IntroActivity.this, MainActivity.class);
startActivity(switchSwag);
finish();
} else {
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
}
Then managing button click:
Button switchButton = (Button) findViewById(R.id.switchButton);
switchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent switchSwag = new Intent(IntroActivity.this, MainActivity.class);
startActivity(switchSwag);
finish();
}
});

Run activity only once, then always run the main one

As the title says, Scenario is:
On first time using the app, Show Screen A.
Once you are done with screen A, the button will lead to you Screen B.
From now on and forever, the Screen B will always be main "Screen"(Activity?) when you start the app.
I am trying this 2 days and i can't get it.
Somebody please explain a little detailed, or even better throw me a code.rar so i can research it. I'm going crazy with this!!!
Just declare your Activity A as a launcher Activity in your AndroidManifest.xml and inside your Activity A onCreate() you can simply do this
private SharedPreferences mSharedPreferences;
private Editor mEditor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
mSharedPreferences = getSharedPreferences("yourPrefsFileName", Context.MODE_PRIVATE));
mEditor = mSharedPreferences.edit();
if (mSharedPreferences.getBoolean("isfirstTime", true)) {
mEditor.putBoolean("isFirstTime",false);
mEditor.apply();
}else{
startActivity(new Intent(this, ActivityB.class));
overridePendingTransition(0, 0);
finish();
}
}
All you have to check like this
SharedPreferences prefs = getSharedPreferences("mySHaredpref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
boolean isFirst = prefs.getBoolean("isfirstTime", true);
if(isFirst) {
Intent intent = new Intent(this, ActivtyA.class);
editor.putBoolean(KEY_IS_FIRST_TIME, false);
editor.commit();
startActivity(intent);
}
else{
Intent intent = new Intent(this, MainActivty.class);
startActivity(intent);
}
public class FirstActivity extends Activity {
public void onCreate(Bundle saved){
super.onCreate();
SharedPreferences prefs = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
if (!prefs.getBoolean("firstStart", true)){
startActivity(this, SecondActivity.class);
finish(); // Finish the current one, is like forwarding directly to the second one
}
}
}
Whenever you are done with showing the first activity simple set the shared prefs boolean flag to false:
prefs.getEditor.setBoolean("firstStart", false).commit();
SharedPreferences sp = getSharedPreferences("checking",MODE_PRIVATE);
String data = sp.getString("check", "");
if (data.equals("success")) {
//one time proccess code
//with follow code
SharedPreferences sp= getSharedPreferences("checking",MODE_PRIVATE);
Editor e1 = sp.edit();
e1.putString("check","success");
e1.commit();
} else {
// code for main
Intent intent = new Intent(this, MainActivty.class);
startActivity(intent);
}

How to keep login user on an application in Android

I have an app that requires user to register.
User opens the app, registers and logs in.
Does some stuff with the app and closes it.
Opens the app again, the user is recognized so he doesn't need to login again.
This is the code used for login:
ArrayList<ArrayList<Object>> data = dm.getAllRowsAsArrays();
for (int position=0;position<data.size();position++)
{
ArrayList<Object> row = data.get(position);
mail1=row.get(0).toString();
pass1=row.get(2).toString();
if((mail1.equals(mail))&&(pass1.equals(pass)))
{
Toast.makeText(getApplicationContext(),"Login Success",Toast.LENGTH_LONG).show();
Intent i=new Intent(getApplicationContext(),usermain.class);
startActivity(i);
}
}
After login goto usermain activity, but if I press the emulator back button then I can see the login page with the details I typed for login.
How can I remove it?
You can use startActivityForResult instead of startActivity and then use this sample onActivityResult method in your login activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == LOGIN_CODE) { // this code you should provide in startActivityForResult
this.finish();
}
}
This will prevent you from going back to login activity. If you'd like to persist user's data, use also SharedPreferences as described by others.
public class SaveSharedPreference
{
static final String PREF_USER_NAME= "username";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, String userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putBoolean(PREF_USER_NAME, userName);
editor.commit();
}
public static boolean getUserName(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}
in your main activity check this first:
if(SaveSharedPreference.getUserName(MainActivity.this).length() == 0)
{
// call Login Activity
}
else
{
// Call Next Activity
}
Use SharedPreference for that in your onCreate() methos like..
SharedPreferences sp=getSharedPreferences("pref",0);
if(sp.getInt("PREFERENCES_LOGIN", 99)==0)
{
setContentView(R.layout.activity_login_screen);
}else if(sp.getInt("PREFERENCES_LOGIN", 99)==1)
{
Intent intent=new Intent(GetLoginDetailsScreen.this,MenuScreen.class);
startActivity(intent);
finish();
super.onBackPressed();
}else{
setContentView(R.layout.activity_login_screen);
}
after login Successful add this..
sp=getSharedPreferences("pref",0);
SharedPreferences.Editor edit= sp.edit();
edit.putInt("PREFERENCES_LOGIN", 1);
edit.commit();
try this
if((mail1.equals(mail))&&(pass1.equals(pass)))
{
Toast.makeText(getApplicationContext(),"Login Success",Toast.LENGTH_LONG).show();
Intent i=new Intent(getApplicationContext(),usermain.class);
finish();
startActivity(i);
}
so here is your solution when the user successfully logged in set the shared preferences in your login class 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 loginwill be success
prefsEditor.putString("remember", "yes");
prefsEditor.commit();
//now in your first activity you just check the shared pref value to know the user is logged in or not
SharedPreferences prefs;
String Log;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
Log=prefs.getString("remember", "");
//now check the value of shared pref and apply the condition like this
Intent intent ;
if(register.equalsIgnoreCase("yes"))
{
intent = new Intent(this, Home.class);
startActivity(intent);
finish();
}
else
{
intent = new Intent(this, Login.class);
startActivity(intent);
finish();
}

Categories