Android using shared preferences to check on first run - java

Hi I'm trying to detect whether my app has been opened for the first time. If it has, I need to run an activity and once it's opened for the second time it should not show it again.
This is my code:
fragment:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
//startActivity(intent);
SharedPreferences settings = this.getActivity().getSharedPreferences(PREFS_NAME, 0); // Get preferences file (0 = no option flags set)
boolean firstRun = settings.getBoolean("firstRun", true); // Is it first run? If not specified, use "true"
if(firstRun) {
Log.w("onCreate: ","first time" );
Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
startActivity(intent);
SharedPreferences.Editor editor = settings.edit(); // Open the editor for our settings
editor.putBoolean("firstRun", false); // It is no longer the first run
editor.apply(); // Save all changed settings
} else {
Log.w("onCreate: ","second time");
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
getSpecials();
}
But all it does is start the activity and when I start it again it freezes in a white screen but checking the logs it shows like the else statement is constantly running over and over. I'm fairly new to Android so some help or advice would be greatly appreciated

#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences pref = YourActivityName.this.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor= pref.edit();
boolean firstRun = pref.getBoolean("firstRun", true);
if(firstRun)
{
Log.i("onCreate: ","first time" );
editor.putBoolean("firstRun",false);
editor.commit();
Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
startActivity(intent);
}
else
{
Log.i("onCreate: ","second time");
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
// getSpecials();
}

It looks like your activity is looping because within your else statement, you tell it to restart the activity which lands again in the else statement and so on and so on.

Try using editor.commit if editor.apply not working
editor.putBoolean("firstRun", false);
editor.apply(); // Save all changed settings
editor.commit(); // Save all changed settings

In else case your starting "MainActivity.class".
Why your loading MainActivity from the oncreate of MainActivity ?
it will make a loop.
Remove the start activity from else case.

Try this approach:
public class MainActivity extends Activity {
SharedPreferences prefs = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstRun", true)) {
Intent intent = new Intent(MainActivity.this, TutorialFeaturedActivity.class);
startActivity(intent);
prefs.edit().putBoolean("firstRun", false).commit();
}
else
{
//do nothing
}
getSpecials();
}
}

Please Try this my friend
public class SessionManager {
private static String TAG = SessionManager.class.getSimpleName();
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "ManageRun";
private static final String KEY_IS_RUN = "isRun";
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setLatest(boolean isRun) {
editor.putBoolean(KEY_IS_RUN, isRun);
// commit changes
editor.commit();
Log.d(TAG, "Manage Version session modified!");
}
public boolean isLatest() {
return pref.getBoolean(KEY_IS_RUN, true);
}
}
**In first Activity Check **
private SessionManager session;
session = new SessionManager(getApplicationContext());
if (session.isLatest()) {
session.setLatest(false);
Log.w("onCreate: ","first time" );
Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
startActivity(intent);
}
else
{
Log.w("onCreate: ","second time");
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}

private boolean isFirstTime() {
if (firstTime == null) {
SharedPreferences mPreferences = this.getSharedPreferences("first_time", Context.MODE_PRIVATE);
firstTime = mPreferences.getBoolean("firstTime", true);
if (firstTime) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putBoolean("firstTime", false);
editor.commit();
}
}
return firstTime;
}
if (isFirstTime()) {
Intent i = new Intent(SplashActivity.this, Intro_slider.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
} else {
final UserFunctions uf = new UserFunctions();
if (uf.isUserLoggedIn(SplashActivity.this)) {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
} else {
Intent i = new Intent(SplashActivity.this, Social_Login_Activity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
}
Try this code.

Related

My settings activity (using shared preferences) is not saving data, it is showing default values only

I am currently working on an android app, for which I created a settings activity. I used shared preferences, but it isn't working as it is supposed to. I open the settings page, toggle the switches, remove the app from memory, but when I open it again, the default settings are shown. I have no idea why. Please help. Also, I am a beginner, since I have started coding quite recently, so forgive me if I made a silly mistake.
public class SettingsActivity extends AppCompatActivity {
public static final String SETTINGS_PREFERENCES = "com.example.taskmasterv3.SettingsPreferences";
Switch switchReminder, switchNotifications;
boolean reminders;
boolean notifications;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
switchReminder = findViewById(R.id.switchReminder);
switchNotifications = findViewById(R.id.switchNotifications);
SharedPreferences prefs = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE);
boolean reminder = prefs.getBoolean("reminders",true );
boolean notification = prefs.getBoolean("notifications", false);
switchReminder.setChecked(reminder);
switchNotifications.setChecked(notification);
if (switchReminder.isChecked())
{
reminders = true;
SharedPreferences.Editor editor = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean("reminders", reminders);
editor.apply();
}
if (switchNotifications.isChecked())
{
notifications = true;
SharedPreferences.Editor editor = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean("notifications", notifications);
editor.apply();
}
}
}
I have get where you are getting error. You are actually unable to set that data.
if (switchReminder.isChecked())
{
reminders = true;
SharedPreferences.Editor editor = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean("reminders", reminders);
editor.apply();
}
if (switchNotifications.isChecked())
{
notifications = true;
SharedPreferences.Editor editor = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean("notifications", notifications);
editor.apply();
}
It directly called when you start the activity. But, this function doesn't called on changing state of switch.
So, you have to add a listener like following source code.
switchReminder.setOnClickListener(new View.OnClickListener() {
//enter your code here
if (switchReminder.isChecked())
{
reminders = true;
SharedPreferences.Editor editor = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean("reminders", reminders);
editor.apply();
}
})
Add setOnClickListener() on switchNotifications also. Than, I hope it will work.
edited :
//setOnClickListener
switchReminder.setOnClickListener(new View.OnClickListener() {
if (switchReminder.isChecked())
{
reminders = true;
SharedPreferences.Editor editor = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean("reminders", reminders);
editor.apply();
}
})
That was for only switchRemider. and, following source code is for switchNotification.
//setOnClickListener
switchNotifications.setOnClickListener(new View.OnClickListener() {
if (switchNotifications.isChecked())
{
notifications = true;
SharedPreferences.Editor editor = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean("notifications", notifications);
editor.apply();
}
})
You have add both code instead of
if (switchReminder.isChecked())
{
reminders = true;
SharedPreferences.Editor editor = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean("reminders", reminders);
editor.apply();
}
if (switchNotifications.isChecked())
{
notifications = true;
SharedPreferences.Editor editor = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean("notifications", notifications);
editor.apply();
}
Ok, so I finally got this to work. i just added a save button to save my settings. Now it works like a charm. Here is the code :
public static final String SETTINGS_PREFERENCES = "com.example.taskmasterv3.SettingsPreferences";
SwitchCompat switchReminder, switchNotifications;
Button btnSaveSettings;
boolean remind;
boolean notify;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
switchReminder = findViewById(R.id.switchReminder);
switchNotifications = findViewById(R.id.switchNotifications);
btnSaveSettings = findViewById(R.id.btnSaveSettings);
SharedPreferences preferences = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE);
boolean reminder = preferences.getBoolean("remind", true);
boolean notification = preferences.getBoolean("notify", false);
if (reminder)
{
switchReminder.setChecked(true);
}
if (notification)
{
switchNotifications.setChecked(true);
}
btnSaveSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
if (switchReminder.isChecked())
{
remind = true;
}
else
{
remind = false;
}
if (switchNotifications.isChecked())
{
notify = true;
}
else
{
notify = false;
}
SharedPreferences.Editor editor = getSharedPreferences(SETTINGS_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean("remind", remind);
editor.putBoolean("notify", notify);
editor.commit();
}
});
}
}

How to use SharedPreferences for splash activity to launch once

I want to launch splash activity only once using SharedPreference, how it could be happen. any help will be highly appreciated. Thanks
Thread thread;
MediaPlayer audio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audio = MediaPlayer.create(MainActivity.this, R.raw.iphone);
audio.start();
if (first_run == true){
thread = new Thread(){
#Override
public void run() {
try {
sleep(4000);
Intent intent = new Intent(MainActivity.this, SplashTwo.class);
startActivity(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
finish();
audio.release();
}
}
};
thread.start();
}
}
try this:
Declare
public static final String MyPREFERENCES = "MyPrefs";
public static final String ID = "idKey";
SharedPreferences sharedPreferences;
Now in your onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
audio = MediaPlayer.create(MainActivity.this, R.raw.iphone);
audio.start();
String first = (sharedPreferences.getString("First", ""));
if (!first.equals("true")) {
thread = new Thread(){
#Override
public void run() {
try {
sleep(4000);
Intent intent = new Intent(MainActivity.this, SplashTwo.class);
startActivity(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("First", "true");
editor.commit();
finish();
audio.release();
}
}
};
thread.start();
}
}
Instead of sharedprefrence ,i would like to suggest you to use static boolean value like - isFirstTime and set it true by default and on second activity (next to splash) set it to false. Whenever you kill app static value will become dead.Check in onCreate of Splash -
if(!isFirstTime){
goToNextActivity();
}else{
//continue splash code
}
If you want to use shared preference then use same Logic ,take a boolean value and save it in shared pref -
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("isFirstTime", true);
editor.commit();
and in next activity simply set it to false or clear value. by calling editor.clear(); and put a check in splash if shared pref has some value or have isFirstTime and do next code accordingly.

how to make same instance as new instance to top of the stack when same instance is running in android

Here the group chat activity is running currently. Group chat activity means chat window. in that chat window i retrieved the message from sqlite and showed by list view adpater. Here i am doing group chat for one event when new message is arrived for other event the notification issued. When i click the notification my group chat activity is not executed again even if i passed the intent from other class or activity.
This is my groupchatActivity code
#Override
protected void onStart() {
super.onStart();
if (activeEventMO != null) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("APPSTATUS", 1);
editor.putLong("eventId", activeEventMO.getEventId());
editor.commit();
Log.i("App", "start");
AppActivityStatus.setActivityStarted();
AppActivityStatus.setActivityContext(context);
}
}
#Override
protected void onPause() {
super.onPause();
AppActivityStatus.setActivityStoped();
}
protected void onNewIntent(Intent intent){
super.onNewIntent(intent);
processExtraData();
}
private void processExtraData() {
activeEventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
}
#Override
protected void onResume() {
super.onPause();
AppActivityStatus.setActivityStarted();
}
#Override
protected void onStop() {
super.onStop();
Log.i("App", "stop");
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("APPSTATUS", 2);
editor.commit();
AppActivityStatus.setActivityStoped();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.image_upload, menu);
return true;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final List<ChatMO> chatMOs1 = new ArrayList<>();
setContentView(R.layout.chat_main);
EventMO eventMO = new EventMO();
context = getApplicationContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
listChatMessageObjectses = chatMOs1;
inputMsg = (EditText) findViewById(R.id.inputMsg);
listViewMessages = (ListView) findViewById(R.id.list_view_messages);
//this activeEventMO is a static object
processExtraData();
// activeEventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
List<ChatMO> chatMOs = dbHelper.getGroupChatMessageForEvent(activeEventMO.getEventId());
//this for loop is for avoiding the notification coz notification also stores groupchat table in sqlite
for (ChatMO chatMO1 : chatMOs) {
chatMO1.getMessage();
chatMO1.getEvent_id();
chatMO1.getFromName();
int messageType = chatMO1.getMessage_type();
chatMO1.getDate();
chatMO1.isSelf();
if (messageType == 0) {
chatMOs1.add(chatMO1);
}
}
adapter = new MessagesListAdapter(context, chatMOs1);
//adapter functionality added for show the previous chat list of event/invite
listViewMessages.setAdapter(adapter);
sharedpreferences = getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, context.MODE_PRIVATE);
// by default first primary user is current user in sql lite
// user table
userMO = dbHelper.getUserData(1);
/* if (!sharedpreferences.getString("MessageMO", "null").equals("null")) {
MessageMO messageMO1 = (MessageMO) gson.fromJson(sharedpreferences.getString("MessageMO", "null"), new TypeToken<MessageMO>() {
}.getType());
eventMO.setEventId(messageMO1.getEventId());
Log.e("shared","eventID"+messageMO1.getEventId());
Log.e("shared","eventID"+eventMO.getEventId());
eventMO.setText(messageMO1.getEventTitle());
Log.i("message values", messageMO1.toString());
ChatMO chatMO = new ChatMO();
//chatMessageObjects.setMessage(messageMO1.getMessage());
chatMO.setSelf(0);
chatMO.setFromName(messageMO1.getfromUserName());
listChatMessageObjectses.add(chatMO);
//listViewMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
}*/
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return userDelegate.getUsersForEvent(activeEventMO.getEventId());
}
#Override
protected void onPostExecute(String eventLists) {
eventUserMOs = gson.fromJson(eventLists, new TypeToken<ArrayList<UserMO>>() {
}.getType());
Toast.makeText(getApplicationContext(), "event users " + eventUserMOs.size(), Toast.LENGTH_LONG).show();
}
}.execute(null, null, null);
Button sendButton = (Button) findViewById(R.id.btnSend);
This gcmIntent here i am passing the intent from this gcmIntent
Intent groupChatActFrag = new Intent(getApplicationContext(), GroupChatActivity.class);
EventMO eventMO = new EventMO();
//here messageMO having the details of received message here i am setting eventId from messageMO to eventMO
// Inorder to passs gropchatActivity
eventMO.setEventId(messageMO.getEventId());
groupChatActFrag.putExtra("eventMo", eventMO);
groupChatActFrag.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("MessageMO", gson.toJson(messageMO));
editor.commit();
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, groupChatActFrag, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_dialog_info).setContentTitle(messageMO.getEventTitle())
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageMO.getfromUserName())).setContentText(messageMO.getMessage()).setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mBuilder.setAutoCancel(true);
mNotificationManager.notify((int) (long) messageMO.getEventId(), mBuilder.build());
You need to do couple of things to achieve the result.
Set launch mode of groupchatactivity to SingleTask
Override onNewIntent() method in groupchatactivity
Call setIntent(intent) for new received intent in onNewIntent()
Reflect as appropriate on above answer.

How to skip second activity after first run forever?

I am working on one app which contain SplashScreen.java my first activity. After that its show LoginActivity.java for login. And my LoginActivity.java class eventually start SplashActivity.java. I want after login first time everytime i start my app SplashScreen.java calls SplashActivity.java instead of LoginActivity.java. For this i made some changes in my SplashScreen.java class but its not working fine.
SplashScreen.java Class-
public class SplashScreen extends Activity
{
private long splashDelay = 5000; //5 seconds
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if(pref.getBoolean("activity_executed", false))
{
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
finish();
}
else
{
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
}
TimerTask task = new TimerTask()
{
#Override
public void run() {
finish();
Intent mainIntent = new Intent().setClass(SplashScreen.this, LoginActivity.class);
startActivity(mainIntent);
}
};
Timer timer = new Timer();
timer.schedule(task, splashDelay);
}
}
Anyone else help me. Now the only problem after first run. App start from SplashActivity instead of starting from SplashScreen.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
Editor ed = pref.edit();
Boolean Exist=pref.getBoolean("activity_executed", false);// Check is user logged in or not
if(Exist)// if allready logged in then forward it to Splash Activity
{
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
finish();
}
else // Not logged in
{
Handler handler = new Handler();
handler.removeCallbacks(runnable);
handler.postDelayed(runnable, 2000L);
}
Runnable runnable = new Runnable() {
public void run() {
new AsyncParsing().execute();
}
};
private class AsyncParsing extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
Log.d("Splash Activity", "In pre execute");
}
#Override
protected Void doInBackground(Void... params) {
Log.d("Splash Activity", "In do in backgriund ");
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.d("Splash Activity", "In post execute");
Intent intent = new Intent(SplashScreen.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
}
Step 1 : Declare this in ur login class
SharedPreferences pref;
SharedPreferences.Editor editor;
Step 2 :Declare In onCrete method
pref = getSharedPreferences("login", MODE_PRIVATE);
editor = pref.edit();
Step 3 : OnClick of submit button in login page paste the lines below
:
String check=pref.getString("selected", "nil")
if(check.equals("TRUE"))
{
Intent intent=new Intent(this,splash.class);
startActivity(intent);
}
Step 4: put this where u r getting the success message when user credentails and db credentials matches.
editor.putString("selected", "TRUE");
editor.commit();
#John check and just refer this working code, i hope,it help u,
setContentView(R.layout.main);
pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
Log.v("","onCreate is calling");
if(pref.getBoolean("activity_executed", false))
{
Log.v("","Before if called");
setContentView(R.layout.menu_frame);
Log.v("","after if called");
new Handler().postDelayed(csRunnable1, 3000);
}
else
{
new Handler().postDelayed(csRunnable2, 3000);
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
}
}
Runnable csRunnable1=new Runnable()
{
#Override
public void run()
{
Intent intent = new Intent(SplashScreen.this, SplashActivity.class);
startActivity(intent);
finish();
}
};
Runnable csRunnable2=new Runnable()
{
#Override
public void run()
{
Intent intent = new Intent(SplashScreen.this, LoginActivity.class);
startActivity(intent);
finish();
}
};
I would think you have a logic problem there. Should be if not executed, run it and mark as executed.
if(!pref.getBoolean("activity_executed", false)) {
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
finish();
}
The problem is that calling finish does not stop the rest of onCreate from being executed. You need to put a return statement after:
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
finish();
You missing I hope It will solve your problem
public class SplashScreen extends Activity
{private long splashDelay = 5000; // 5 seconds
/** Called when the activity is first created. */
TimerTask task = new TimerTask() {
#Override
public void run() {
finish();
Intent mainIntent = new Intent().setClass(Test.this,
LoginActivity.class);
startActivity(mainIntent);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
SharedPreferences pref = getSharedPreferences("ActivityPREF",
Context.MODE_PRIVATE);
if (pref.getBoolean("activity_executed", false)) {
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
finish();
} else {
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
Timer timer = new Timer();
timer.schedule(task, splashDelay);
}
}
}
// try this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if(pref.getBoolean("activity_executed", false))
{
Intent intent = new Intent(this, SplashActivity.class);
startActivity(intent);
finish();
}
else
{
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
Timer timer = new Timer();
TimerTask task = new TimerTask()
{
#Override
public void run() {
timer.cancel();
Intent mainIntent = new Intent().setClass(SplashScreen.this, LoginActivity.class);
startActivity(mainIntent);
finish();
}
};
timer.schedule(task, splashDelay);
}
}

Use back button to save sharedPreferences

I'm having some issue with my application... I have a Settings Activity where the user can pick a theme for the app, then I have a button that says "Back" and returns the user to the main Activity. After that the theme get's saved and everything works fine. But my problem is if the user hit's the "Android back button", my theme doesn't get's saved. There is a way to fix it?
Here is my Settings Activity:
public class SettingsActivity extends Activity implements OnClickListener {
public static final String PREF_NAME = "MyPrefsFile";
public static int newTheme;
public final static int THEME_DARK = R.style.DarkTheme;
public final static int THEME_LIGHT = R.style.LightTheme;
public final static int THEME_COLORS = R.style.ColorsTheme;
public final static int THEME_PERF = R.style.Performance;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences settings = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
newTheme = settings.getInt("themeCustom", 0);
if(newTheme == THEME_DARK) {
setTheme(R.style.DarkTheme);
} else if(newTheme == THEME_LIGHT){
setTheme(R.style.LightTheme);
} else if(newTheme == THEME_COLORS) {
setTheme(R.style.ColorsTheme);
} else {
setTheme(R.style.Performance);
}
setContentView(R.layout.activity_settings);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
findViewById(R.id.button6).setOnClickListener(this);
}
#Override
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor edit;
edit = settings.edit();
Intent intent = getIntent();
Intent main = new Intent(SettingsActivity.this,MainActivity.class);
switch (v.getId()) {
case R.id.button2:
newTheme = THEME_DARK;
edit.clear();
edit.putInt("themeCustom", newTheme);
edit.commit();
finish();
startActivity(intent);
break;
case R.id.button3:
newTheme = THEME_LIGHT;
edit.clear();
edit.putInt("themeCustom", newTheme);
edit.commit();
finish();
startActivity(intent);
break;
case R.id.button5:
newTheme = THEME_COLORS;
edit.clear();
edit.putInt("themeCustom", newTheme);
edit.commit();
finish();
startActivity(intent);
break;
case R.id.button6:
newTheme = THEME_PERF;
edit.clear();
edit.putInt("themeCustom", newTheme);
edit.commit();
finish();
startActivity(intent);
break;
case R.id.button4:
startActivity(main);
break;
default:
break;
}
}
}
Thank you very much!! :)
You can use onBackpressed()
public void OnBackpressed()
{
// do stuff ( same as what you did in your button click)
}
It is called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.
you should override the onBackPressed() method
#Override
public void onBackPressed() {
super.onBackPressed();
// to do
}
#Override
public void onBackPressed() {
//do whatever to save the settings
super.onBackPressed();
}
This way you can do whatever you want on the button + the original intention of it.
You can use the following way
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("themeCustom", newTheme);
editor.commit();
}

Categories

Resources