Android: Load Data in background during splash screen and use it later - android

I'm trying to load data from a webserver (getting a JSONArray back) during the start of my application.
So far I was able to get the array back only from the main activity with the following commands:
if (DEVELOPER_MODE) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());<br>
}
jsonArray = JsonParser.getJSONFromURL("cities2.php");
That gave me all the cities (or whatever data i needed) in the current class, but this is not a clean way to do it.. My Problem now is, how to get the cities from my SplashScreen Activity to the Activity where i need the data.My goal is to load all the data from the webserver during the SplashScreen (about 4500 lines of text -> approx. 50KB data) and use them in the different Activities..
So, my main problem at the moment is how to get the data from the webserver that i load during the SplashScreen onto the "last" activity (i.e. SplashScreen -> MainActivity -> SetFilterActivity -> ShowDataActivity (here i need the data) )
I was reading here; Android SplashScreen
Here: How to make a splash screen (screen visible when app starts)?
Here: http://www.androidpeople.com/android-loading-welcome-splash-spash-screen-example
And here: http://www.41post.com/4588/programming/android-coding-a-loading-screen-part-1 And others.... :-)
I tried also to write a sperate class that extends Application and "store" the data in there (getters and setters), but somehow it does not work like i want.
Can anyone guide me into the right direction on how i can do that a proper way..
Thank you for your help
PS: I could easily load the data on each screen whenever i need it, but i want to load it at one point and just use it afterwards in the programm whenever and wherever i need it

i was having the same problem so instead of creating a new activity to show the splash screen i used a Dialog, so you won't need to share the data between the activities.
The link i used to do that: http://blog.iangclifton.com/2011/01/01/android-splash-screens-done-right/

Load your accumulated data as shared preferences. You can then access them as typed key/value pairs from anywhere in your application.
See: http://developer.android.com/guide/topics/ui/settings.html
// Writing prefs
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(defaultInt, currentInt);
editor.putFloat(defaultFloat, currentFloat);
editor.putString(defaultString, currentString);
// Reading prefs
currentString = this.getResources().getString("my_string_value");
currentFloat = this.getResources().getFloat("my_float_value");
Using SharedPreferences results in much less overhead than extending Application -- it's going to be both faster and easier to maintain, particularly for 50kb of data, which is a fairly trivial amount.

Use Database to keep and put your data there. Database is not bond to activity at all so once you store your data there, you can retrieve it later from everywhere and basically that's what database is here for - to keep your data :) Suggestion to use shared preferences is not really good, as it's basically key value storage. If you need to do any sorting, or conditional data fetch then you will find yourself reinventing the wheel.

Related

Populate Android App with JSON data

I want to build an android app for a restaurant. I want it to display the menu in several activities using listviews. One for drinks, one for meals, one for deserts, etc. The menu comes from a json file which is being parsed in a splashscreen on app start.
Now i'm wondering what's the best way to populate the listviews and activities after parsing the json:
Populating the listviews from the splashscreen activity?
Storing the menu data in files and access them on the depending activity's oncreate()…?
Parsing a separate json file for each activity?
What is the best way in terms of performance, simplicity and effectiveness?
That would imply you have all you Acticities with their ListViews up & running when the splashscreen is starting. Probably not what you want.
You already said the JSON is stored in a file. You can parse that JSON in your splashscreen Activity, keep a global reference to it and let you Activities pick the part they need from that global class / JSONObject.
Tradeoff: Parse the complete JSON once and let all Activities retrieve the parts they need from it (this is basically 2.) at the 'risk' of parts of it never being used or split the JSON into several parts that are being loaded/parsed on demand by every Activity seperately, but having the overhead of doing file transactions in every Activity.
Either way, if the menu you're storing isn't immensely huge, the difference in performance will be minimal.
I'd go 2., load the whole file at startup, store the data globally and let every Activity make use of it.

Saving texture with Preferences

So what Im trying to achive is: When the user purchases a new item (a texture) they can click a button to replace the old Item(texture) with the new one.
What got in my mind first was Objectmaps. So I created this:
ObjectMap<Integer, Texture> screenMap = new ObjectMap<Integer, Texture>();
Im only using two items at the moment just to get a hang of it:
screenMap.put(prefs.getInteger("stoneOne", 0), sdStone);
screenMap.put(prefs.getInteger("stoneTwo", 1), stone_3);
Here´s the methods I use to change the texture:
public void setStone1() {
stoneImage = new Image(screenMap.get(0));
}
public void setStone(int screenId) {
stoneImage = new Image(screenMap.get(screenId));
}
And now to the part I can figure out:
Preferences prefs = Gdx.app.getPreferences("preferences");
prefs.putString("textField", textField.getText());
prefs.putString("textArea", textArea.getText());
prefs.getInteger("stone", );
prefs.putInteger("stone", );
prefs.flush();
I have no Idea what Integer to put in there as you can see I even left it out right now. I tried the screenId integer but it´s not reachable since it is in a void? P.S never mind the weird names I got for things. I took some code from an old project.
Try to walk for another way.
Save Texture to sdcard.
Save path to file into preferences.
Preferences prefs = Gdx.app.getPreferences("preferences");
prefs.putString("texture_one_path", "/sdcard/tex1.jpeg");
prefs.putString("texture_two_path", "/sdcard/tex2.jpeg");
Sergey is right. Textures are heavy and big, and you could potentially have tons of them. That's meant for the SD card.
Preferences are lightweight, secure configuration files used on mobile devices. They're usually encrypted, too, so accessing them always has a cost. They're used usually for user settings, login information, etc. The Android extrapolation of Preferences is called SharedPreferences. Here's the doc: http://developer.android.com/reference/android/content/SharedPreferences.html
The iOS concept of "SharedPreferences" is called NSUserDefaults, and here's its page: https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html
Bottom line: you shouldn't be saving much information to the preferences. Use it for strings, global values, user settings (volume level, user credentials, turn off gore, etc.) For large string data, use raws. For large media, use SD card.
Hope that helps.

When to use getSharedPreferences vs savedInstanceState?

I'm trying to figure out when to use a saved instance state versus loading information from a shared preferences file. I have two variables that I wish to save, time and score. I want to make sure that if the user returns to the game screen that their score and time is saved and restored regardless if it's from onPause state or onStop.
I have three keys:
public static final String ARG_SCORE = "score";
public static final String ARG_TIME = "time";
public static final String SHARED_PREFS = "shared_preferences";
If the game is paused and a dialog is shown, when the user returns should I do
public void onRestoreInstanceState(Bundle savedInstanceState){
int score = savedInstanceState.getInt(ARG_SCORE);
}
or should I do something like:
protected void onResume(){
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int score = sharedPref.getInt(getString(R.string.saved_high_score));
}
Overall, I need help understanding the lifecycle and when to store vital information such as time and score of the game. I simply need to avoid the user having to restart in cases they weren't able to finish the game.
Lastly, I'm assumed that the sharedPrefs saves to an xml file. Is this correct? Does anyone have a sample xml for how my sharedPrefs should appear? Do keys which are saved to bundles of savedInstanceState get stored in xml files as well? If so, any examples? If not, where is the information stored?
THANKS!
edits:
ok cool beans. Thanks! One more question, when defining a key for a key-value pair stored into sharedPreferences such as
public static final String ARG_SCORE = "score";
why is the "score" string stored? When would this ever be used? I've always placed a value into the key_value pair using something like
args.putInt(ARG_TIMER, timerINT);
and retrieved using
scoreINT=savedInstanceState.getInt(ARG_SCORE);
Why is a name needed for the key ARG_SCORE? When would I need the name? Does it have to stay type String?
use saveInstanceState when you are frequently moving back and forth between activities and use SharedPreferences when you want to keep information for long time and yes sharedpreferences stored in an xml file. you can view using DDMS in eclipse.
Remeber, in saveInstanceState, when you close app mean it get removes from memory, information will also lost. And in SharedPreferences, information will remain there if you close your app.
It will depend on how you want to manage the data. Both options (and more) are feasible:
If you want to fill once and keep the data even if the app gets
killed, use SharedPreferences.
If it's volatile data that will have to be reentered differently some
other time (i.e., days later), then use onSavedInstanceState.
If you want to keep multiple datasets on the same device, then use a
SQLiteDatabase
You usually want to use SharedPreferences when you want to persist some information between different app session. Imagine you want to store information that you want to retrieve also after the user closes the app.
SavedInstanceState is used to keep some information while user is using the app and allow you to track temporary state of your activity or fragments.
Hope it helps.
when you press home button then still your activity remains in background. since there is some memory constraints in android , there is always chance some other application can take your memory. so to resume application from same point where we have left we use saveInstanceState.
we use sharedprefrence when we have to save small info(normally primitive type) like game high score in any game.
In the Android documentation says how to relate SharedPreferences to XML but there's no need to use SharedPreferences if you don't want the data to be stored forever, you can store the game's state using the Activitys lifecycle methods with no problem, but for example, if the user turns off it's phone or presses the back button to finish your Activity, then the savedInstanceState won't work and you will lose your data.
It's your call, if you want the game to be saved even if the user turns off his phone (I think this would be kinda radical, but if it's your requirement go ahead) then use SharedPreferences or a DB if it's complex data. If you want the game to be saved only when the user navigates in and out to your app, then it's safe to use the savedInstanceState.

StringSets won't save/load to/from SharedPreferences

My app stores an ArrayList of custom Food objects which are posted to a ListView in the main Activity. The ListView portion of the app works perfectly, but I'm having an issue saving and loading these Food objects to and from SharedPreferences.
I'm saving these Food objects to SharedPreferences by saving each of its attributes as a String, putting them in a StringSet, and saving each one via the putStringSet function. When the app resumes, it reads through each StringSet from SharedPreferences and creates a new Food item with the read attributes, then adds each one to the ArrayList. The code seems like it should work, but just doesn't load the data between sessions. Can anyone help me figure out why? Thank you!
Code removed
You seem to never instantiate foodNamesSet variable. Hence the check if(foodNamesSet != null) always return false. Same thing applies to other sets as well. Besides, I think you should do the logic in onPause() rather in onStop().

How to store and retrieve a dynamic listview

I Have 2 activities: activity X & activity Y.
Y sends data to X via an intent and X displays the data in a listView.
The problem I am having is saving the listView in X so the next time a user goes to activity Y and sends an intent the listView will display the last data that was send + the new data, this way the user will continue to populate the ListView .
I was thinking about saving all the data in a sqlLite database and then retrieving it and displaying the updated listView that way?
or maybe to serialize my list and save it via SharedPrefs (not sure if that would actually work,I am a really new at this)
Any suggestions and code samples would be appreciated!!!! THANK YOU!
If you have a small amount of data (<5 variables) I suggest you to implement a Sharepreferences class with the methods you need (basically, put and get). For more than that, someone told me to use SQLite, but I've never used before, even if it seems easy to put in place.
Besides, these are methods useful if you want to store data even if the app is closed, and you could retrieve them after in another session. If data lives only for a session, put everything in a bundle and go back and forth with it.
well, You can use any of the
1) sharedPreference : for primitive data only .
2)File storage(internal/external) : limited size , no quert support , suitable when storing long string kind of data
3)SQlite : suitable for complex structure , because of query support

Categories

Resources