How to check if an app is being opened - Android Studio - java

I'm making a game and am saving data for the player using sharedPreferences. The way I have it set up right now, every time the main application (the first page) is loaded, the old data it held before is loaded. So, imagine a player has 100$, and they exit the app. Upon opening the app again, this data will be loaded and everything seems fine.
The problem, however, is that if a player's money is changed in ANOTHER activity, the way I have it set up right now is that any time a player navigates back to the main activity, the data is loaded. So if the player has $100 on the main activity, this info is saved every few seconds on the main activity. If the player spends 50$ on a second activity, when they return to the main activity, since the last saved data the main activity has is $100, it will load the $100.
This is a problem, and a way to fix it is to ONLY LOAD THE DATA WHEN THE APP IS OPENED. So like I don't want to load the data every time the player navigates to the main activity, but only when they open the app. I need a simple if() boolean statement to do this, but I'm not sure what the statement I need is.
Thanks!

Store a boolean in sharedPreferences and check if it exists or if it's false/true in the create of the activity, such as storing a value for "hasLoaded" with a value of either true or false. check this value in onCreate and then do your logic accordingly.
OR alternatively,
create a static variable in your mainActivity for hasLoaded, then in onCreate, do everything you want to do and then change it to true.
static boolean hasLoaded = false;
if(!hasLoaded){
//all your logic here
hasLoaded = true;
}
note:
storing it in sharedPrefs will ensure that your initialization will only happen ONCE for all usages of the app, while storing it in a static variable will make sure it only happens once PER RUN of the app

Related

Load state of particular recyclerview item

so I have recyclerview populated with data from database. Each row contains two buttons one for play and second for stop time. So what I'm trying is to save state of buttons inside recyclerview. And I used
PreferenceManager.getDefaultSharedPreferences(context).edit().
putInt(Constants.numberOfbutton, getAdapterPosition()).apply();
to save particular position. I have inserted that line of code inside button click and I checked it's saving correct position. What I'm trying to achieve is, when user enters the app after closing if he lefts any of the buttons in play mode to restore that state and continue timer. But problem is when user enters the app all buttons are running. I'm using chronometer for presentation of the time. I think here is the problem in this method:
private void startTime(int position ) {
Data data = datas.get(position);
chronometer.setBase(SystemClock.elapsedRealtime() + Long.parseLong(data.getTime()));
chronometer.start();
}
UPDATE EXPLANATION:
So I can load from database for each item of recyclerview it's time, date, name etc. But I can't figure it out how to play chronometer of just particular item when user enters the app again. NOTE AGAIN: I'm performing correct saving getAdapterAtPosition and loading data from PreferenceManager. I've checked that. Even I tried putting the number of one of rows but same issue appears.
Any help very appreciated. Thanks.
I have found the answer. I save the boolean in database actually I used 1 or 0 than parse that to true or false acordingly is button play pressed or not. Thank you all for your comments and trying to help.
Try to use handler or alarm service instead of chronometer

Android application design help, How to control which activity shows

Hello I require some advice on how to approach this problem,
bear with me as I am still new to android.
I have an activity that opens on application start and requires some information from the user, but next time the user opens the app, i want the application to open a different activity that will display the various information.
Kind of like facebooks app, where when you first run it, you have to login, and only then next time you run the app you are guided straight to the feed.
Any ideas how one could do this efficiently?
UPDATE: Ive stored the information via shared preferences and am now using a controller activity that decides which step to take.
So, Controller activity runs on start up, and decides whether to show a log in screen or whether to go straight to the information. But now im encountering a problem where i end up opening a blank activity (the controller) and then another ontop of that ( the decided activtiy). I dont want the blank activity to show, so its kinda of like a background process, any ideas?
Ideally you would have a main activity like a controller. Use a SharedPreference object to keep track of whether the user is logged in or not. So back in your main activity, read this value and if it is set go to your news feed activity else show a login screen activity. (as you do the check and redirection, you can show a progress dialog)
links for SharedPreferences
MobTuts
Android Developer

Android application with more than one screen

I'm currently trying to develop an android application in eclipse(java) which shows some jokes downloaded from a database. The user is able to vote on each joke once, and to make sure they only do that once, I have made a table in the database that contains three columns.
E-mail
Username (Used when a user publishes a joke)
Encrypted Password
I have two "screens" right now:
Login screen
Main screen
At every single start up the application checks the SharedPreferences for a file containing some information, and if there is some information it should load the Main screen, but if there is no account information the Login screen should be loaded.
Any idea on how I can use different screens, and how should it be coded?
Two options:
In your Activity, check if there is account info. If there isn't then setContentView to the Log in screen. Otherwise, setContentView to your other content. If you go this route, you'll have to have the logic of both the login Activity and the other in the same Activity. Shouldn't be too bad if the logic is relatively uncomplicated.
Have two activities. The default Activity can be the login Activity, but in onCreate() you can check if the info already exists and if it does, simply start the other Activity right away and return from onCreate(). Otherwise, continue with setContentView, etc.
You can have a single top layout (e.g. FrameLayout) that contains two overlapping layouts (one for the login and one for the main). Use a single activity. When the activity starts do setContentView() to the top layout. Then define a method selectScreen(boolean isMain) that based on the argument sets the main layout on and the login off (or vice versa). You turn screens on/off using the setVisibility() method in class View. You can switch screen any time by calling that method. If you want to be extra fancy you can use standard animations when flipping screens.

For programming an android app: How do I make it display a one time setup screen

While searching this question I have seen this. One time Android setup screen?
It asks my question, but I can never get it to work. What I want to happen is when I first startup the app, it gives me the setup screen. Then when I press save, I want it to quit the app. When I click the app again, I want it to preform a task, rather than show up with a screen. So thats really 2 questions, how to make it show a setup screen one time, and then how to make it do an action(by clicking on the app) without a screen showing up at all.
Right now, I use SharedPreferences editor to input my settings.
Pretty simple, in the onCreate of your activity:
savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
if(savedPreferences.getBoolean(PREF_SHOW_ABOUT_ON_APP_START, true)){
Intent intent = new Intent(this, SetupActivity.class);
startActivity(intent);
savedPreferences.edit().putBoolean(PREF_SHOW_ABOUT_ON_APP_START, false).commit(); // YOu could do this line within the SetupActivity to ensure they have actually done what you wanted
finish();
} else {
// Go somewere else
}
You don't have to activity switch, but you get the picture
For the first time only set up screen, you simply have to use SharedPreferences. Check if a value, alreadyLaunched exists in the shared preferences. If not, show the set up screen. If yes show your app.
For the second part of your question, it would be considered very bad practice to have an icon app that does nothing at all when you click it. How would the user know that it worked or did what it was supposed to do ?
For the "I want a task to execute but I don't want the user to see it happening", I believe you should look at services. When your user closes the app clicking the save button on the set up screen, start a service ( http://developer.android.com/reference/android/app/Service.html )
When the user clicks again on your app, simply show a message and make the app call the service via an intent.
Probably you are forgetting to call
myEditor.commit()
after you are done with setting your preferences.

Saving Android application state

I understand how to save an application's state by using SharedPreferences, onSavedInstanceState() & onRestoreInstanceState(), etc as outlined in a similar post ( Saving Android Activity state using Save Instance State ), but how do I save the last activity?
To be more specific, my application starts up and goes to a login screen. Once a user logs in and navigates through several activities, lets say he or she leaves the app using the home button or in some other way. Next time the user starts the app, it will go back to the login screen and do a login again. Instead, I want the app to start up and go to the last activity that was on top of the stack when the user left the app in the previous session.
How is the last activity saved so that it can be restored on app startup?
I believe Android does this automatically. We have an app that we are working on. When I click the home button and them come back to the app, it starts in the activity where I left off. We have not written any code to make this happen. It just seems to work.
My colleague has written an article on Android application state including details on getLastNonConfigurationInstance() which retrieves the instance that was last stored. Take a look here: http://www.eigo.co.uk/Managing-State-in-an-Android-Activity.aspx
Please note that the above answer is correct only on one case: If your process does not get killed by android because the resources (memory, ...) are needed for a different reason.
To get what you describe, I would write a custom parent activity and override the correct life-cycle methods to store your application state and read it and act accordingly. Then let all your activities inherit from MyActivity (instead of android.app.Activity)
public MyActivity extends android.app.Activity {
...
#Override
public onCreate(...) {
// Read the Application state,
// check if the currently launching Activity is the right one,
// if not, start the last Activity and finish the current one.
}
#Override
public onDestroy(...) {
// Store the current Activity ID in the SharedPreferences
}
...
}
Take care to call the super.onDestroy and super.onCreate methods in all your Activites (like you should do anyways).
Happy coding and have fun with Android!

Categories