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

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

Related

Is there a way to pass data between a service and an activity without start the latter?

I'm making a galley app and I have created a background service with an IntentService that classifies images so I want to send them to an activity that will show them whenever the user wants, for this reason, I don't want to open the activity right after the service finished the task. I have read that you can use SharedPreferences to share data between activities but according to the Android documentation you can only pass a relatively small collection of key-values. In my case, I want to send an ArrayList of files.
Instead of sending list of files, you can just send the absolute path or files. So it would be only a list of strings

Send data amongst three activities

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

What is the easiest way to save an ArrayList in Android?

I'm building an app that has a favourites list, but when I exit the app, the favourites list is reset to nothing because the list is not being saved (since lists can't be saved in SharedPrefs). How can I save an ArrayList OR String[] in Android? If you recommend Serialization or a Local Database, could you please explain what these are and mean? I've heard the terms and followed tutorials but do not understand.
Maybe another approach to the same question is how would you normally build a favourites list?
There's a question that explains it in a very nice way:
Save ArrayList to SharedPreferences
From its answer (I've already tested it), after API 11 you can do something like this:
//Retrieve the values
Set<String> set = myScores.getStringSet("key", null);
//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();
I summarized his answer, but you should check the complete answer. It's really helpful!
Option1: easiest. Iterate over arraylist and save each element into sharedPreferences
option2: convert arraylist into a string. Then save into shared pref.
option3: save your data into a database. Google how to use sqllite with android
You can use Sugar ORM library for Android. It will create for you the database you need by simply making the object class of your ArrayList to extend SugarRecord.
For example, if your List type is ArrayList you have to make your Books class extend SugarRecord, and then in your Activity iterate in a loop through the items and set item.save() and it is saved to the database.
I have a sample project here.
If you have any question send me a PM.
Hope it helps!

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

Difference between Intent.ACTION_GET_CONTENT and Intent.ACTION_PICK

I'm trying to let the user choose any image that they want on their device to use as a wallpaper in this wallpaper application I'm building. For some reason when I write:
Intent myIntent = new Intent(Intent.ACTION_PICK);
myIntent.setType("image/*");
startActivityForResult(myIntent, 100);
I go straight into the gallery, but when I write:
Intent myIntent = new Intent(Intent.ACTION_GET_CONTENT, null);
myIntent.setType("image/*");
startActivityForResult(myIntent, 100);
I get to choose from Gallery, or Google Drive. What is the best way to let the user choose what app to retrieve the picture from every time? Or why do those two different intent constants make a difference?
Your first Intent is invalid. The protocol for ACTION_PICK requires you to supply a Uri indicating the collection you are picking from.
What is the best way to let the user choose what app to retrieve the picture from every time?
If you want the user to choose something based on MIME type, use ACTION_GET_CONTENT.
If you have some specific collection (identified by a Uri) that you want the user to pick from, use ACTION_PICK.
In case of a tie, go with ACTION_GET_CONTENT. While ACTION_PICK is not formally deprecated, Dianne Hackborn recommends ACTION_GET_CONTENT.
The modern action is ACTION_GET_CONTENT, which is much better supported,
ACTION_PICK :
Activity Action: Pick an item from the data, returning what was selected.
Input: getData() is URI containing a directory of data (vnd.android.cursor.dir/*) from which to pick an item.
Output: The URI of the item that was picked.
Constant Value: "android.intent.action.PICK"
Difference :-
Activity Action: Allow the user to select a particular kind of data and return it.
This is different than ACTION_PICK in that here we just say what kind of data is desired, not a URI of existing data from which the user can pick.
A ACTION_GET_CONTENT could allow the user to create the data as it runs (for example taking a picture or recording a sound), let them browse over the web and download the desired data, etc.
Reference http://developer.android.com/reference/android/content/Intent.html#ACTION_GET_CONTENT
public static final String ACTION_GET_CONTENT
Added in API level 1
Activity Action: Allow the user to select a
particular kind of data and return it. This is different than
ACTION_PICK in that here we just say what kind of data is desired, not
a URI of existing data from which the user can pick. A
ACTION_GET_CONTENT could allow the user to create the data as it runs
(for example taking a picture or recording a sound), let them browse
over the web and download the desired data, etc.
via http://developer.android.com/reference/android/content/Intent.html#ACTION_GET_CONTENT

Categories