handling intents using SharedPreferences - java

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();
}
});

Related

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();

How to check if firstrun has been skipped?

I have in my firstrun activity, a button that says "continue" and starts new activity (MainActivity intent), but I've found out it's possible skip that button and firstrun activity by restarting the app. So I would like to make sure it will be impossible to skip the activity.
That's what I have been thinking about:
firstEntry.java - In this method I'm putting new value in the shared preference that confirm that firstrun haven't been skipped (it only add the value if the button is clicked).
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(skip, false);
editor.commit();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish();
}
OnCreate() method in MainActivity
boolean skipper = prefs.getBoolean(skip, false);
if(skipper == true){
Intent i = new Intent(getApplicationContext(), firstEntry.class);
startActivity(i);
}
OnResume function:
#Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstrun", true)) {// Checks if application is on its first run
Intent i = new Intent(getApplicationContext(), firstEntry.class);
startActivityForResult(i, 1);
prefs.edit().putBoolean("firstrun", false).commit();
finish();
}
}
How can I check if shared preference method "firstrun" has skipped the continue button by using shared preference values?
change following line in btn.setOnClickListener(new View.OnClickListener()
editor.putBoolean(skip, false);
to
editor.putBoolean(skip, true);
And then in OnCreate() method of firstEntry.java
boolean skipper = prefs.getBoolean(skip, false);
if(skipper == true){
Intent i = new Intent(getApplicationContext(), MainActivity.class);
Log.i("firstEntry.java","skipped the activity");
startActivity(i);
}

"New Game" button deleting Android game progress

It's been a month since I started learning Java/Android Studio so I apologise beforehand for any silly questions.
I am currently making a simple riddle game with Android Studio - a question is asked, and the right answer gets you to the next activity/question. So, my main menu consists of a Start Interrogation button and a Continue button. Using SharedPreferences I managed to make the game "save progress" so it can get you to the last question you couldn't answer; but my problem comes with the Start Interrogation button. Whenever it is pressed and starts a new game, the continue button will still get you to the last question asked before.
So in simple terms, I want to make the New Game button delete the progress made until then. The only thing that comes to mind is to try and delete the SharedPreferences whenever the button is pressed, but I fail to write such code.
Any tips on what should I do? Help is greatly appreciated. Here's the Java code of my MainMenu.
MainMenuWithLogo.Java
public class MainMenuWithLogo extends AppCompatActivity {
private Button mStartInterrogationButton;
private VideoView mLogoprwto;
private Button mContinueButton;
MediaPlayer song;
#Override
protected void onPause() {
super.onPause();
song.release();
}
#Override
public void onResume() {
super.onResume();
setContentView(R.layout.activity_main_menu_with_logo);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
song = MediaPlayer.create(this, R.raw.chopin);
song.start();
song.setLooping(true);
mLogoprwto = (VideoView) findViewById(R.id.logoprwto);
mLogoprwto.setVideoPath("android.resource://its_destination/"+R.raw.teloslogo);
mLogoprwto.start();
mLogoprwto.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mLogoprwto.start();
}
});
mStartInterrogationButton = (Button)findViewById(R.id.StartInterrogationButton);
mStartInterrogationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
startGame();
}
});
mContinueButton = (Button)findViewById(R.id.ContinueButton);
mContinueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences prefs = getSharedPreferences("Stage", MODE_PRIVATE);
boolean question00Answered = prefs.getBoolean("QuestionZero", false);
boolean question01Answered = prefs.getBoolean("QuestionOne", false);
boolean question02Answered = prefs.getBoolean("QuestionTwo", false);
if (!(question00Answered)) {
Intent intent = new Intent(MainMenuWithLogo.this, QuestionZero.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
finish();
} else if (!(question01Answered)) {
Intent intent = new Intent(MainMenuWithLogo.this, QuestionOne.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
finish();
} else if (!(question02Answered)) {
Intent intent = new Intent(MainMenuWithLogo.this, QuestionTwo.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
finish();
}else {
Intent intent = new Intent(MainMenuWithLogo.this, End.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
finish();
}
}
});
}
private void startGame () {
Intent intent = new Intent(this, Intro.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
finish();
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
You can use SharedPreferences.Editor.remove() to delete items saved to SharedPreferences using the item's key. So, when you start a new game, call this to delete the user's progress. Or, if you want to remove ALL the stuff in SharedPreferences, call SharedPreferences.Editor.clear().

Can not access shared preferences data properly

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.

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);
}

Categories