Passing data through two activities? - java

For an app I am developing, I am having the user input some information on one activity, and then on the next, the user will read something, in such that he/she won't be putting any information on it, but on the third activity, I want to display what the user put in the first. Is there a way I can carry that information from the 1st to the 3rd activity without going through the second?

Use sharedPreferences to store that piece of data on the phone. On the 3rd activity, read it and use it.
See it here-
http://developer.android.com/guide/topics/data/data-storage.html#pref

This can be done in many ways !
Why not use Intents to pass the data ?
STEP-1: <Eg:: From Activity1>
Pass the telefone into a new activity with the help of intents
Intent i = new Intent(getApplicationContext(), Activity2.class);
i.putExtra("title",telefone);
i.putExtra("descrip",telefone);
startActivity(i);
STEP-2: <Eg:: From Activity2>
Receive the string passed in another activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title= extras.getString("title");
String descrip= extras.getString("descrip");
}
STEP-3: <Eg:: From Activity2> pass data again to Activity3
Receive the string passed in another activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title= extras.getString("title");
String descrip= extras.getString("descrip");
}
Pass the data to Activity3
Intent i = new Intent(getApplicationContext(), Activity3.class);
i.putExtra("title",telefone);
i.putExtra("descrip",telefone);
startActivity(i);
Hope it helps ! ..........Let me know if you need more info

Use SharedPreference. Save in A1 and retrieve in A3.
Initialization
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
Storing Data
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
Retrieving Data
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Deleting Data
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
Clearing Storage
editor.clear();
editor.commit(); // commit changes

Related

Set<String> losing data when restored from SharedPreferences after app is restarted

Im using SharedPreference on android to store a Set of Strings. It is stored and retrived fine to my knowledge but when the app is restarted some data is lost. Strings are add one by one and before adding them I retrieve the set, add a String and then store it again.
This is how I store it:
Set<String> emptySet = null;
SharedPreferences prefs = getContext().getSharedPreferences(getContext().getString(R.string.pref_disagree_key), Activity.MODE_PRIVATE);
String newIdAgreed = getItem(position).getId();
if (prefs.contains(getContext().getString(R.string.pref_disagree_key))) {
Set<String> updateSet = prefs.getStringSet(getContext().getString(R.string.pref_disagree_key), emptySet);
updateSet.add(newIdAgreed);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(getContext().getString(R.string.pref_disagree_key), updateSet);
editor.commit();
} else {
Set<String> newSet = new HashSet<String>();
newSet.add(newIdAgreed);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(getContext().getString(R.string.pref_disagree_key), newSet);
editor.commit();
}
And this is how I get it back:
if (prefsDisagree.contains(getContext().getString(R.string.pref_disagree_key))){
disagree_set = new HashSet<String>(prefsDisagree.getStringSet(getContext().getString(R.string.pref_disagree_key), emptySet));
for (String item: disagree_set){
//stuff done here
}
}
I saw some similar questions about this topic but none of the answers solved my problem. Any ideas?
The StringSet is not persistent when you are trying to edit it all again after it was saved and therefore newer data that was just added wont get saved when you quit the app and open it again.
It is actually documented: getStringSet
You need to copy first the StringSet and then insert/add data to the copied StringSet:
Set<String> s = new HashSet<String(prefs.getStringSet(
getContext().getString(R.string.pref_disagree_key),
emptySet));

How SharedPreference.Editor actually work in Android?

I am trying to save some String data using SharedPreference.
Here is my code
// SAVE
SharedPreference mySharedPref = new SharedPreference("Data", 0);
mySharedPref.edit().putString("hello", "world");
mySharedPref.edit().putString("my", "code");
mySharedPref.edit().commit();
// LOAD
String str = mySharedPref.getString("hello", ""); // I expect "world"
But it only has an empty string!
Meanwhile,
SharedPreference.Editor editor = mySharedPref.edit();
editor.putString(...);
editor.commit();
This worked....
I thought mySharedPref.edit() returns a reference and makes the code above and below the same.
I am confused now. X(
See this solution
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
in your code:
// SAVE
SharedPreference mySharedPref = new SharedPreference("Data", 0);
mySharedPref.edit().putString("hello", "world");
mySharedPref.edit().putString("my", "code");
mySharedPref.edit().commit();
You called edit() each time you put a String but you didn't call commit() after it so your changes is not saved. You should change to this:
// SAVE
SharedPreference mySharedPref = new SharedPreference("Data", 0);
mySharedPref.edit().putString("hello", "world")
.putString("my", "code");
.commit();
edit() method in SharedPreference returns NEW INSTANCE of the Editor interface. I found the comment explaining it in SharedPreferences.java file came with sdk.
Any actions performed on the new instance will be independent from other instances.
In the first part of my code, by calling edit() multiple times, I was performing actions on each independent instance.
It was interesting to notice that edit() returns a new instance instead of a reference.
/**
* Create a new Editor for these preferences, through which you can make
* modifications to the data in the preferences and atomically commit those
* changes back to the SharedPreferences object.
*
* Note that you must call {#link Editor#commit} to have any
* changes you perform in the Editor actually show up in the
* SharedPreferences.
*
* #return Returns a new instance of the {#link Editor} interface, allowing
* you to modify the values in this SharedPreferences object.
*/
Editor edit();

Parsing and displaying XML from httpGet

Hopefully someone can help me here. I have a project that I'm doing, yes it is homework so I hope that doesn't hurt my chances of an answer here. I'm supposed to write an app that collects data from bbyopen api. Best Buys web api, it delivers details about stores in your area. Any way I've gotten a response from the server that I'm certain contains the correct information as I've displayed it in logcat using System.out.println(). However, what I would like to do is turn this string into an xml document, parse out the name of the store, it's address and then display it in a text view in a new activity.
Here is the code I'm using to parse the string and put the proper data into an array which is passed to a new activity. I'm certain that nothing is actually passed to the new activity and I'm unsure whether or not the array is even being built. Any help would be greatly appreciated.
public void callback(String serviceResult){
System.out.println(serviceResult);
try {
XmlPullParserFactory parserCreator = XmlPullParserFactory.newInstance();
parserCreator.setNamespaceAware(true);
XmlPullParser parser = parserCreator.newPullParser();
parser.setInput(new StringReader(serviceResult));
int eventType = parser.getEventType();
while (eventType != parser.END_DOCUMENT){
String name = "";
String address = "";
if ((eventType == XmlPullParser.START_TAG)&& (parser.getName().equals("longName"))){
name = parser.getName();
}
if ((eventType == XmlPullParser.START_TAG)&& (parser.getName().equals("address"))){
address = parser.getName();
Store store = new Store(name, address);
arrStore.add(store);
System.out.println(arrStore);
}
else
parser.nextTag();
}
} catch (Exception e) {
}
Intent intent = new Intent(getApplicationContext(),StoreList.class);
intent.getStringArrayListExtra(arrStore.toString(), "key");
startActivity(intent);
}
I then receive the intent in the new activity like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_store_list);
getIntent();
ArrayList<String> store = getIntent().getStringArrayListExtra("key");
}
However trying to do a print line on the ArrayList store, in the new activity results in a null pointer error. I suspect that is because the array is empty..?
If it helps here is what the XML that I am receiving looks like and it is being sent as a string the parser.
<stores warnings="Distances are in terms of miles (default)" currentPage="1" totalPages="1" from="1" to="4" total="4" queryTime="0.006" totalTime="0.011" >
<store>
<longName>Best Buy - Toledo II</longName>
<address>1405 Spring Meadows Dr</address>
</store>
<store>
<longName>Best Buy - Perrysburg</longName>
<address>10017 Fremont Pike</address>
</store>
<store>
<longName>Best Buy - Toledo</longName>
<address>4505 Monroe St</address>
</store>
<store>
<longName>Best Buy Mobile - Franklin Park</longName>
<address>5001 Monroe Street</address>
</store>
</stores>
The error is here:
Intent intent = new Intent(getApplicationContext(),StoreList.class);
intent.getStringArrayListExtra(arrStore.toString(), "key");
startActivity(intent);
Try: putStringArrayListExtra().

sharedpref add strings into table

i trying to insert my string into my database tables ,but it doesnt appear, so any advice on this how do i string my text so it able to appear on android database table
btnplayer = (Button) findViewById(R.id.button1);
tw1 = (TextView)findViewById(R.id.PX2);
btnplayer.setOnClickListener(new View.OnClickListener() {
SharedPreferences myPrefs = getSharedPreferences("PREF_COUNT", 0);
SharedPreferences.Editor myEditor = myPrefs.edit();
public void onClick(View v) {
String Player = myPrefs.getString("tw1",name);
DataStorage.this.btnplayer.setText("add name [" + Player + "]");
myEditor.putString("Player", Player);
myEditor.commit();
Please make your question more clear.
If you want store your data in database in android, you can go for SQLite database available in android http://developer.android.com/training/basics/data-storage/databases.html
but I suggest use sharedpreferences if only strings need to store.
I didn't get the meaning behind this statement String Player = myPrefs.getString("tw1",name); if you already have stored the same value (first time there will be no value so you will getting back the default "name" and then you will again store that name with the new key called "Player"). Where are you storing "tw1"? Exactly what issue you are facing?

SharedPreferences Android

I have this method :
private void deleteExam(String i) {
SharedPreferences prefsContatore = getSharedPreferences("esameKey"+i, Context.MODE_PRIVATE);
SharedPreferences.Editor editorContatore = prefsContatore.edit();
editorContatore.putString("esameKey"+i, "0");
editorContatore.commit();
}
Go? Can I call recursively "esameKey"+i?
getSharedPreferences access to a file and create if it does not exist. Every time you pass a different i a new file is created. Create it once:
SharedPreferences prefsContatore = getSharedPreferences("mySharedPrefFileName", Context.MODE_PRIVATE);
SharedPreferences.Editor editorContatore = prefsContatore.edit();
first argument of putString is a key the second paramter is the value you want to store
editorContatore.putString("esameKey"+i, "0");
this way you are putting for every i the value of 0. Is really that what you want?

Categories