matgod
matgod

Reputation: 49

SharedPreferences - Android (different data types)

I have a problem with with sharing data between two different activities. I have data like :

 int number
 String name 
 int number_2
 int time
 int total

I'm trying to make something like order list with this set of data . So it will take one set of data , then back to previous activity , move forward and again add data to it .

I have an idea of making it in array of object - but data inside was cleared after changing activity.

How can I make it ?

I don't know if and how to add Array of object to SharedPreferences , and get value of one element from there.

Upvotes: 0

Views: 1255

Answers (3)

Android
Android

Reputation: 437

Why not to use Intents

Intent intent = new Intent(FirstActivity.this, (destination activity)SecondActivity.class);
intent.putExtra("some_key", value);
intent.putExtra("some_other_key", "a value");
startActivity(intent);

in the second activity

Bundle bundle = getIntent().getExtras();
int value = bundle.getInt("some_key");
String value2 = bundle.getString("some_other_key");

EDIT if you want to read more about adding array to shared preferences check this

Is it possible to add an array or object to SharedPreferences on Android

also this

http://www.sherif.mobi/2012/05/string-arrays-and-object-arrays-in.html

Upvotes: 0

horvste
horvste

Reputation: 636

Don't used share preferences for this...Use the singleton pattern, extend Application, or just make a class with static variables and update them...

You can use .putExtra but since you are communicating with more than one activity the above suggestions are probably the best.

public class ShareData {
private String s;
private int s;
private static ShareData shareData = new ShareData();
private ShareData(){}

public static ShareData getInstance(){ return shareData} 
//create getters and setters;
}

Upvotes: 0

Simone Casagranda
Simone Casagranda

Reputation: 1215

You should have a look at the documentation of the Intent(s) if you want to do that on the fly associating a key to the value(s) that you want to pass to your second activity.

Anyway, you can think any(sharedpref, database,...) way to pass your parameters but for those kind of things it's a convention and a good practice to follow that.

Upvotes: 1

Related Questions