I have an activity that contain a list of data (TextView), i need to save this data that have been choose (onClick) in the list and been able to get and read it in another activity(history)
I understand that is exist a possibility with the "serializable" but i did not success to understand how it could help me.
i will be happy if someone can clarify this subject for me,example?.
Thank you for helping!!
If you're trying to pass a String to another activity, you can do this with putExtra and getStringExtra:
Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra("parameter", myStringParameter);
startActivity(intent);
and then read it in OtherActivity's onCreate method:
String parameter = getIntent().getStringExtra("parameter");
The Serializable interface is useful for marshalling more complicated objects; you don't need this if you're just dealing with String.
Edit - if you need to store small amounts of data persistently you could use SharedPreferences:
final String TAG = "MyApplication";
SharedPreferences prefs = getSharedPreferences(TAG, MODE_PRIVATE);
prefs.edit().putString("parameter", myStringParameter).commit();
and then to read the preferences:
final String TAG = "MyApplication";
SharedPreferences prefs = getSharedPreferences(TAG, MODE_PRIVATE);
String parameter = prefs.getString("parameter", null);
This data will be available even after your application closes.
Yes, use classes that implement Serializable. See my answer on this question: How to pass several variables of different types from one function to another on android?
Create some model classes which will hold data:
public class Page implements Serializable {
private String name;
private String description;
//and so on...
public Page(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
}
Now you can create a Page object and fill it with data(name, description) via the constructor. Optionally make some setters.
Page p = new Page("James", "Hello World");
startActivity(new Intent(context, MyActivity.class).putExtra("Page", p));
Retrieve your Page in MyActivity in its onCreate method:
Page p = (Page)getIntent().getExtras().getSerializable("Page");
Toast.makeText(this, "Name: " + p.getName() + ", Description:" + p.getDescription(), Toast.LENGTH_LONG).show();
I am aware about the methods mentioned above. But just for alternative thoughts, since you are mentioning the history word, how about using SQLite for this purpose?
In first activity, you can save the data, and in second activity, retrieve the data.
You can share data between your activities in various ways depending on how much data you need to save and how long the data needs to be saved.
Intents : Useful when transferring small bits of data between 2-3 screens
Singleton / Static data store classes : useful when sharing lot of data between various activities
SQLite DB : Large amount of data to be shared , also useful to save the same between app launches
Shared Preferences : Small amount of data , between app launches.
For your use-case its best to use intents unless the data is shared between more than 2-3 activities where option 2 would be a better solution
Sending immutable stateful objects between activities (messaging) is commendable, IMHO. It can be argued that OOP is about messaging, not objects. Two suggestions. 1) use the fully qualified name for the name:value pair so do:
private void launchManagePassword() {
Intent i= new Intent(this, ManagePassword.class); // no param constructor
PasswordState outState= new PasswordState(lengthKey,timeExpire,isValidKey,timeoutType,"",model.getIsHashPassword());
Bundle b= new Bundle();
b.putSerializable("jalcomputing.confusetext.PasswordState", outState);
i.putExtras(b);
startActivityForResult(i,REQUEST_MANAGE_PASSWORD); // used for callback
}
This will minimize runtime casting errors.
2) When you have the app working well and the object interface is stabilized consider refactoring the code to a Parcel for speed.
JAL
EDIT: AS REQUESTED Code
Related
I'm working with Steppers. So currently i have one Activity with 3 Fragments in which the user must complete with some information, like a Form.
There are a lot of information so i made 4 classes to separate that information.
In addition, some information is got it automatically so in fragments i ask for permissions...
For Example:
public class UserIds {
#Nullable
#Expose String phone;
#Expose String Email;
#Expose String phone2;
#Expose String ModCel;
#Expose String Doc;
//Setters, getters and another simple method
public class UserLocation {
#Nullable
#Expose String street;
#Expose int number;
....
//Setters, getters and another simple method
...
And so on with 2 classes more.
So, as you can see i'm working with retrofit too.
How can I correctly handle something like that?
I read about Parceler , Interfaces, EventBus...
Should I declare all objects instances in the Activity and then modify in each fragment ( Some objects are modified by differents fragments) or maybe create instances in each fragment, store the information and in when the Complete button is pressed, obtain the information? How should i save this objects in case of OnDestroy() call?
Another things to take into account is that finally, when the form is end. Other activity may have all the information and ask for more (yeah, a LOT OF INFORMATION IS NEEDED).
Finally, every time the user complete the form (with the complete button and then when the other activity ask for more, this data is sended to the server)
I chose the Parceler way and work perfectly. Maybe help somebody, i put #Parcel in each POJO class, then as i am handling with fragments with StepperAdapter (because of stepstone library) in the fragment which i want to save data i did this:
// Obtaing all the fragments
List<Fragment> steps = getFragmentManager().getFragments();
// save states
Bundle bundle = new Bundle();
Parcelable wrapped = Parcels.wrap(obj1);
Parcelable wrapped2 = Parcels.wrap(obj2);
bundle.putParcelable("OBJ1", wrapped);
bundle.putParcelable("OBJ2", wrapped2);
steps.get(fragment2reference).getArguments().putAll(bundle);
Then in the fragment that receive, you have to create a constructor and then you can receive the data (because of fragment was already created, so the bundle throw error)
//Constructor
public fragment2(){
super();
setArguments(new Bundle());
}
When fragment2 shows :
OBJ1 a = Parcels.unwrap(getArguments().getParcelable("OBJ1"));
OBJ2 b = Parcels.unwrap(getArguments().getParcelable("OBJ2"));
Hope somebody help!
I know, there are plenty of questions in regards to saving/retrieving data on here. I was doing find looking things up on my own and really thought I could manage to find my answers without having to "ask a question", but I began to wonder something that I haven't seen an answer for on here.
MY SITUATION:
Naturally, I'm making an app. Upon closing the app, I want to save a simple array of numbers (0 or 1) or boolean values as it were. Upon starting the app, I want to search for that array, if it exists, and retrieve it for use within the app.
I began placing my code into the activity in which the array would be used. But, I started wondering if I would have to copy/paste the overridden onStop() function into all of my activities? Or do I do it in the main activity and somehow link the other activities.
Basically, no matter what state/activity the app is currently on when the app is closed, I want to be able to save the array of int/bool and open it back up when the app is started.
Maybe I didn't know how to search for what I wanted, so explaining it felt like the right thing to do.
I don't mind doing more searching, but if someone would point me in the right direction at the very least, I'd be extremely grateful.
EDIT: If there's a better way to do what I want than what I described (i.e. using a different state instead of onStop(), for instance), please feel free to throw out ideas. This is my first time actually having to deal with the activities' lifecycles and I'm a bit confused even after looking through the android development tutorials. I really think they're poorly done in most cases.
When you application needs to save some persistent data you should always do it in onPause() method and rather than onStop(). Because if android OS kills your process then onStop() and onDestroy() methods are never called. Similarly retrieve data in onResume() method.
Looking at the purpose you want to fulfill, SharedPreferences is all you want.
The documentation states:
"SharePreferences provides a general framework that allows you to save
and retrieve persistent key-value pairs of primitive data types. You
can use SharedPreferences to save any primitive data: booleans,
floats, ints, longs, and strings. This data will persist across user
sessions (even if your application is killed)."
Use SharedPreference to store small amount of data or use SQLite to store large amount of data.
See this link
http://developer.android.com/guide/topics/data/data-storage.html
Serialize an object and pass it around which is more dependable than shared preferences (had lots of trouble with consistency with shared preferences):
public class SharedVariables {
public static <S extends Serializable> void writeObject(
final Context context, String key, S serializableObject) {
ObjectOutputStream objectOut = null;
try {
FileOutputStream fileOut = context.getApplicationContext().openFileOutput(key, Activity.MODE_PRIVATE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(serializableObject);
fileOut.getFD().sync();
} catch (IOException e) {
Log.e("SharedVariable", e.getMessage(), e);
} finally {
if (objectOut != null) {
try {
objectOut.close();
} catch (IOException e) {
Log.e("SharedVariable", e.getMessage(), e);
}
}
}
}
Then use a class to use:
public class Timestamps implements Serializable {
private float timestampServer;
public float getTimestampServer() {
return timestampServer;
}
public void setTimestampServer(float timestampServer) {
this.timestampServer = timestampServer;
}
}
Then wherever you want to write to the variable use:
SharedVariables.writeObject(getApplicationContext(), "Timestamps", timestampsData);
Best way to achieve that is:
create a class. Call it MySettings, or whatever suits you
in this class, define the array of ints / booleans you are going to share, as static. Create getter & setter method (property) to access that (also as static methods)
add a static load() method to MySettings that reads from SharedPreferences. When you launch the app (in your first activity or better in a subclass of Application) call MySettings.load(). This load method sets the array
add a static save() method. Public also. Now you can save from anywhere in you app. This save() method reads the array and writes in SharedPreferences
Code sample:
public class MySettings {
private static List<Integer> data;
public static void load() {
data = new ArrayList<Integer>();
// use SharedPreferences to retrieve all your data
}
public static void save() {
// save all contents from data
}
public static List<Integer> getData() {
return data;
}
public static void setData(List<Integer> data) {
MySettings.data = data;
}
}
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.
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.
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;
}
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
I have created an application that takes in user name and other details for a transaction and then fills them in a database. At times the application shows odd behavior by filling the SAME details in the database twice as two transactions. Even though the new values are read but not STORED in the static variables.
Therefore I needed help in flushing the values of all my static variables at the end of each activity to avoid overriding of the previous values in a fresh transaction.
EDIT :
public class One
{
static String var;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
var="blah";
}
}
public class Two
{
static String variable = One.var;
// This is where i am accessing the value of the variables from previous activities.
//CODE
}
May these help you..
Using Static Variables is like a nightmare in any activity as it stores memory through out the activity..
I think you can try some other memory store to overcome your problem of passing value from one activity to another..
In my opinion u can store values in SharedPreference or either you can pass value through intent to other activity where ever it is required..
Hope these will help you..
EDIT:
Intent in = new Intent(MainActivity.this,SecondActivity.class);
You can use more than one putExtra() method to put several values and can fetch then in Second Activity
in.putStringArrayListExtra(String name, ArrayList<String> value);
StartActivity(in);
In Second Activity:
Intent in = getIntent();
ArrayList<String> Roleids = new ArrayList<String>;
RoleId = in.getStringArrayListExtra(String name, ArrayList<String> value)
I would like to be able to transfer data from one activity to another activity. How can this be done?
Through the below code we can send the values between activities
use the below code in parent activity
Intent myintent=new Intent(Info.this, GraphDiag.class).putExtra("<StringName>", value);
startActivity(myintent);
use the below code in child activity
String s= getIntent().getStringExtra(<StringName>);
There are couple of ways by which you can access variables or object in other classes or Activity.
A. Database
B. shared preferences.
C. Object serialization.
D. A class which can hold common data can be named as Common Utilities it depends on you.
E. Passing data through Intents and Parcelable Interface.
It depend upon your project needs.
A. Database
SQLite is an Open Source Database which is embedded into Android. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements.
Tutorials -- http://www.vogella.com/articles/AndroidSQLite/article.html
B. Shared Preferences
Suppose you want to store username. So there will be now two thing a Key Username, Value Value.
How to store
// Create object of SharedPreferences.
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("userName", "stackoverlow");
//commits your edits
editor.commit();
Using putString(),putBoolean(),putInt(),putFloat(),putLong() you can save your desired dtatype.
How to fetch
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");
http://developer.android.com/reference/android/content/SharedPreferences.html
C. Object Serialization
Object serlization is used if we want to save an object state to send it over network or you can use it for your purpose also.
Use java beans and store in it as one of his fields and use getters and setter for that
JavaBeans are Java classes that have properties. Think of
properties as private instance variables. Since they're private, the only way
they can be accessed from outside of their class is through methods in the class. The
methods that change a property's value are called setter methods, and the methods
that retrieve a property's value are called getter methods.
public class VariableStorage implements Serializable {
private String inString ;
public String getInString() {
return inString;
}
public void setInString(String inString) {
this.inString = inString;
}
}
Set the variable in you mail method by using
VariableStorage variableStorage = new VariableStorage();
variableStorage.setInString(inString);
Then use object Serialzation to serialize this object and in your other class deserialize this object.
In serialization an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
If you want tutorial for this refer this link
http://javawithswaranga.blogspot.in/2011/08/serialization-in-java.html
Get variable in other classes
D. CommonUtilities
You can make a class by your self which can contain common data which you frequently need in your project.
Sample
public class CommonUtilities {
public static String className = "CommonUtilities";
}
E. Passing Data through Intents
Please refer this tutorial for this option of passing data.
http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/
When you passing data from one activity to another activity perform like this
In Parent activity:
startActivity(new Intent(presentActivity.this, NextActivity.class).putExtra("KEY_StringName",ValueData));
or like shown below in Parent activity
Intent intent = new Intent(presentActivity.this,NextActivity.class);
intent.putExtra("KEY_StringName", name);
intent.putExtra("KEY_StringName1", name1);
startActivity(intent);
In child Activity perform as shown below
TextView tv = ((TextView)findViewById(R.id.textViewID))
tv.setText(getIntent().getStringExtra("KEY_StringName"));
or do like shown below in child Activity
TextView tv = ((TextView)findViewById(R.id.textViewID));
TextView tv1 = ((TextView)findViewById(R.id.textViewID1))
/* Get values from Intent */
Intent intent = getIntent();
String name = intent.getStringExtra("KEY_StringName");
String name1 = intent.getStringExtra("KEY_StringName1");
tv.setText(name);
tv.setText(name1);
Passing data from one activity to other in android
Intent intent = new Intent(context, YourActivityClass.class);
intent.putExtra(KEY, <your value here>);
startActivity(intent);
Retrieving bundle data from android activity
Intent intent = getIntent();
if (intent!=null) {
String stringData= intent.getStringExtra(KEY);
int numberData = intent.getIntExtra(KEY, defaultValue);
boolean booleanData = intent.getBooleanExtra(KEY, defaultValue);
char charData = intent.getCharExtra(KEY, defaultValue); }
Hopefully you will find the answer from here Send Data to Another Activity - Simple Android Login
You just have to send extras while calling your intent
like this:
Intent intent = new Intent(getApplicationContext(), SecondActivity.class); intent.putExtra("Variable Name","Value you want to pass"); startActivity(intent);
Now on the OnCreate method of your SecondActivity you can fetch the extras like this
If the value u sent was in "long"
long value = getIntent().getLongExtra("Variable Name which you sent as an extra", defaultValue(you can give it anything));
If the value u sent was a "String"
String value = getIntent().getStringExtra("Variable Name which you sent as an extra");
If the value u sent was a "Boolean"
Boolean value = getIntent().getStringExtra("Variable Name which you sent as an extra",defaultValue);
Your Purpose
Suppose You want to Go From Activity A to Activity B.
So We Use an Intent to switch activity
the typical code Looks Like this -
In Activity A [A.class]
//// Create a New Intent object
Intent i = new Intent(getApplicationContext(), B.class);
/// add what you want to pass from activity A to Activity B
i.putExtra("key", "value");
/// start the intent
startActivity(i);
In Activity B [B.class]
And to Get the Data From the Child Activity
Intent i = getIntent();
if (i!=null) {
String stringData= i.getStringExtra("key");
}
This works best:
Through the below code we can send the values between activities
use the below code in parent activity(PARENT CLASS/ VALUE SENDING CLASS)
Intent myintent=new Intent(<PARENTCLASSNAMEHERE>.this,<TARGETCLASSNAMEHERE>.class).putExtra("<StringName>", value);
startActivity(myintent);
use the below code in child activity(TARGET CLASS/ACTIVITY)
String s= getIntent().getStringExtra(<StringName>);
Please see here that "StringName" is the name that the destination/child activity catches while "value" is the variable name, same as in parent/target/sending class.