Send data amongst three activities - java

I have 3 activities, that connect like this:
A -> B -> C.
On A you input a text that will be used in C, then B opens and you input another text to be used in C. But when C opens, produces null errors.
I came up with a solution, to start A then go directly to C and onCreate of C, start B as if it was going from A to B.
Is there a better solution? Is my solution decent or will it cause more problems than it fixes? Thanks for any help.

There are several options - Intent extras, SharedPreferences, SQLite database, internal/external storage, Application class, static data classes etc.
For situation you've explained, I recommend using SharedPreferences to store data, it's relatively easy approach and you can access stored data at any time from any Activity or class, here is a simple usage guide:
Input data into SharedPreferences:
SharedPreferences.Editor editor = getSharedPreferences("YourPrefsFile", MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();
Get data from SharedPreferences:
SharedPreferences prefs = getSharedPreferences("YourPrefsFile", MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "");
int idName = prefs.getInt("idName", 0);
}

You have 4 solutions in this case the
first one is which you mentioned
the second one is using an intent with put extra in every activity that you will go from
the third solution is using a static variables so that the variables will not be affected if activity reopened (not recommended)
the fourth one you can use shared preference to save the data (which will be the best solution in my opinion)

This is not a very good idea as their may be delays in starting the activity as you would be doing some other operations as well in the onCreate method of activity B and C. Will cause performance issues in future due to delay in showing the activity.
Things you can do...
If the data is very small lets say a key value pair then why not use shared preferences.
Or use a database to store the data as and when it gets created, after which when the activity is created query it and show it.

I think, You can pass the input to next activity through intent.
Since it is a text input,
intent.putExtra("A_Activity_Input","YourinputString"); //in activity A
Then Activity B starts, Get the string using
String Input_A_Activity=getIntent().getStringExtra("A_Activity_Input");
After When you are starting C activity from B, send both data using intent
intent.putExtra("A_Activity_Input",Input_A_Activity);
intent.putExtra("B_Activity_Input","YourinputString");
In Activity C, Get the string from the intent.
Since you just need a data to process, Storing it in SQL or SharedPref or something else wastes memory

Related

Shared Preferences doesn't have to be created? [duplicate]

This question already has answers here:
can someone explain me how SharedPreferences works in Android in a very detailed yet easy understanding?
(2 answers)
Closed 6 years ago.
I'm trying to save information on an Android app I've made. I want to save a name, "Robert". For this I've been looking into Shared Preferences and I can't find a tutorial that explains how to create SharedPreferences.
All tutorials start like this:
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
But they don't explain where the getPreferences() take the object from.
When is this object (SharedPreferences object) created? Is it created along with the context? Is it created together with each activity?
I'm pretty new to Android, but an intermediate(minus) Java programmer.
SharedPreferences are created like this:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Robert");
editor.commit(); //Or use editor.apply()
Then you get them again like this:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
So, the getString() gets the value you stored before, and returns the default value if you haven't stored a string for 'name' yet.
The object you store is saved in the system, and is constantly available to be grabbed.
UPDATE:
The getSharedPreferences() method returns a SharedPreferences.Editor interface.
According to the android docs
Interface used for modifying values in a SharedPreferences object. All
changes you make in an editor are batched, and not copied back to the
original SharedPreferences until you call commit() or apply()
UPDATE 2:
This answer contains more info on the storage of SharedPreferences.
SharedPreferences are stored in your app's data folder as an xml file. It doesn't matter what context you use to getSharedPreferences from. It will pull those preferences from that file. Once loaded for the first time, the preferences file is cached process-wide so you will get the same object back on each subsequent getSharedPreferences call (even if they are from different Activities).
More information here and here.

Best place to store custom objects so all activities can see them

I am an iOS developer who is trying to learn Android and I would like to make sure that I am following best practices.
I have custom objects that need to be accessible by 1 -> m activities and they need to be saved when the application closes. Currently I am using SharedPreferences, code below, to save them but I am not sure if it is the best route. Should I be using a singleton? Is there a better way?
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(userProfile);
prefsEditor.putString("UserProfile", json);
prefsEditor.commit();
gson = new Gson();
json = mPrefs.getString("UserProfile", "");
UserProfileObject outObject = gson.fromJson(json, UserProfileObject.class);
A singleton won't be saved when the application exits. Really your options are:
*SharedPreferences. Good for a small number of key/value pairs
*Database. Good for relational data
*File on disk, in whatever format you prefer. Good for any amount of data, but you may need to write a custom parser.
Storing json in a shared preference is a bit weird. Its not horrible so long as you aren't storing a lot of keys in there, but it makes it seem like you didn't know how to write a file.
#Gabe has provided a good answer. I am adding my 2 cents to it
I personally do not like to save serialised data in SharedPreferences. Instead I would use local db storage such as SQLite or Realm to store it. The reason being serialisation/deserialisation involves marshalling/unmarshalling objects using reflection which could potentially hit performance in a negative way.
In short, Use local db for storing complex / relational data and SharedPreferences for storing simple data
I think if your UserProfileObject can be easily constructed from Json and it doesn't contain any sensitive data (i.e. password), might be fine just having it in SharedPreferences (just save the json string like what you are doing).
Using a singleton SessionManager / ProfileManager class with that should be sufficient enough. Even though it might be used by 1 -> m activities, it only hits the SharedPreferences once using the singleton. Just make sure you keep the copy of the data in the singleton and in SharedPreferences in sync when there are changes. Or just dump the singleton all together and hit the SharedPreferences every time you need it (less worries about keeping copies in sync), don't think your use case will hammer it that much.

Looking for advice on how to store and access game information in my Android app

I'm currently making a simple RPG in Android Studio using Java, and am having trouble identifying the best way to store and modify the game variables, such as player name, money etc.
The videos and resources I have looked at have offered multiple solutions, such as passing the variables through to different intents using bundles, using singletons, using shared preferences or simply using static variables.
Originally, I was planning to use an instance of a 'PlayerInfo' class in the main activity to store the information, and use bundles to pass the data, however, as the data will be needed in almost every activity, is this the best way?
Thanks for any help!
The ideal choice in your case would be to use SharedPreferences and store items as key value pairs! You can write to sharedpreferences file this way:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
And read from the Sharedpreferences file this way:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
Here is a complete tutorial on Sharedpreferences if you dind it hard!
Note: Sharedpreferences will only be a good option if the data you are saving is small, if your data is large and has relationships in between, would advice you to use Sqlite or Realm

How to keep track of information regarding fragments in Android

I have a fragment which is sort of like a test. The user can choose from a spinners menu if this test has passed, failed or undecided. Once the user leaves this fragment and then comes back to it later, I want the spinners menu to display what the user had previously selected.
Can anyone tell me how to keep track of this information? I am a beginner with Java and Android programming. Also, let me know if further explanation is required.
It probably depends on what scope you want to be able to refer to these tests in. For example, do you want these fragments to be emptied after the user closes the app, or not?
If it is just while in the app "session", you could just create an object in your fragment and override the onResume method to populate the spinners with the appropriate data.
If you want to save the info after the app is closed, there are a couple of options. For smaller sets of data you could use shared preferences
if you have an undetermined amount of "tests", I would advise saving whatever data you need to a file, and parsing it to fill the fields in the fragments
Take a look at this to get an idea of how to save data: http://developer.android.com/intl/es/training/basics/data-storage/files.html
I've done something similar to what your doing. I used shared preferences to save the string like so
Saving the string you got from the spinner in a fragment
SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor mSharedPreferencesEditor = mSharedPreferences.edit();
mSharedPreferencesEditor.putString("my_unique_key", myString);
// commit changes
mSharedPreferencesEditor.apply();
Remember to always apply the changes after you made them and you can save as many strings as you want as long as they each have a unique key.
Then to retrieve the value just
SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String myStringValue = mSharedPreferences.getString("my_unique_key", null);
The second argument (null) will be returned if it could not find any data that had that unique key. (i.e if you haven't saved it yet)
You can also use another string instead of null like this
String myStringValue = mSharedPreferences.getString("my_unique_key", "could not find value");
or if you want to bundle a bunch of data together like say create an object to save a bunch of strings then save that object to a file I could show you that if you wanted to

How should i save my app data in my android app?

I am making my first android app. I want to save an array of strings in one activity and then in second activity i want to show those strings as a list. I am using android platform 2.2 with API 8 So i can not use putStringSet(). Is there any way to save my data as a text file in my app? Then may be i can just add a new line in that file whenever user adds a new string. And while making list view i can parse it on basis of new line and make string array.
Thanks for your help.
Use File Handling.
Easy to use for beginners and efficient for your purpose.
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
There is a method putStringArrayListExtra("id", ArrayList list) in Intent to use before starting it. Then in the launched Activity from the Intent, use getStringArrayList("id").
For example:
Intent intent = new Intent(MainActivity.this.getApplicationContext(), NewActivity.class);
intent.putStringArrayListExtra("id", yourArrayList)
MainActivity.this.startActivity(intent);
Then on NewActivity onCreate() method
ArrayList<String> list = getIntent().getExtras().getStringArrayList("id");
But you can use putStringArray, or putStringArrayList wrapped into a Bundle.
Bundle are passed via Intents.
-> http://developer.android.com/reference/android/os/Bundle.html#putStringArray(java.lang.String, java.lang.String[])
Then, if you want to save it as a file, then you have to use this method : http://www.java-forums.org/advanced-java/13852-saving-arraylist-file.html
But i think you prefer pass the String list directly.
Why are you using files for that?
Just check sharedPreferences and sqliteDb
It may work for you..shared preferences are easy to handle

Categories