To pass parameters from one activity to another is used the method "intent.putExtra()"
Does this method only allows to add primitive data or I can add a parameter that is a java bean?
if you can not, how I can send a java bean from one activity to another?
Thanks!!
Look at the API entry for Intent. You've got a load of possible data types you can enter, not the least of which is Parcebles, Bundles, and Serializable. If you really want simple object marshalling I would convert your beans to JSON and put it as a String, then convert it back to a POJO on the receiving end.
You can send objects if they implements serializable.
//At your entity Object:
public class Objeto implements Serializable{
}
//At the sender Activity:
//create an instance of the object
Objeto object = new Objeto();
//creates an intent from the current activity to the destiny activity with the data to be transferred.
Intent proximo = new Intent(this,TelaDestino.class);
//transfers the object as a bundle to the next activity
proximo.putExtra("OBJETO",objeto);
startActivity(proximo);
//At the destine activity:
private Objeto objeto;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
objeto = (Objeto)getIntent().getSerializableExtra("OBJETO");
}
//You can use that and be happy :D
If your object is is Serializable you can add it with putExtra like this.
i.putExtra(String key, Serializable value);
Another way to share data between activities is extend the application class.
My answer explains how to use it.
getApplicaiton return which object among applicaitons
Related
I have a data of custom List type (finalHolder.data)
Earlier I had to send this data to a Fragment constructor it is working fine
Fragment fragment;
fragment = new RouteMap(finalHolder.data);
((Activity)getContext()).getFragmentManager().beginTransaction().replace(R.id.content_frame,fragment).commit();
The Fragment constructor code
public RouteMap() {
// Required empty public constructor
}
public RouteMap(MyListEntity data) {
this.data = data;
}
Activity constructor :
public Map() {
}
public Map(MyListEntity data) {
this.data = data;
}
But now I want this same data to reach a Activity (Map2)
I tried putExtra with intent but Intent but it doesnt work
In Short I want the "finalHolder.data" to be send to Activity constructor while calling it .
If it isnt possible then please suggest solution
Thanks
It is not recommended to use Activity constructor. To send data object to activity you can use Intent extras with Parcelable. For that you need to do the follow way.
Implement your data class from Parcelable
Ex: MyListEntity implements Parcelable
Override the following methods in your data class(MyListEntity) writeToParcel(), readFromParcel()
3.Implement the CREATOR class in your data class(MyListEntity)
Reference link for Parcelable example: passing object to activity
Send the data object using Intent as mentioned below
Intent i = new Intent(this,Activity(Map2).class);
i.putExtra("mylistdata",finalHolder.data);
startActivity(i);
And finally get the same data at your Activity(Map2) onCreate() method as mentioned below
MyListEntity listEntry = getIntent().getParcelableExtra("mylistdata");
Now your object is ready at your second activity.
Hope this will help for you.
To send an object in intent the object's class must be serializable so make your
MyListEntity implements serializable then use the Intent's putExtra(String name, Serializable value) and in the other activity use the intent's getSerializableExtra (String name) but don't forget to cast the returned value
One option could be letting your custom class implement the Serializable interface and then you can pass object instances in the intent extra using the putExtra(Serializable..) variant of the Intent#putExtra() method.
Your data should implement Serializable ie
MyListEntity implements Serializable
//Use this to send the data
intent.putExtra("MyClass", finalHolder.data);
// To retrieve object in second Activity
getIntent().getSerializableExtra("MyClass");
Regarding your Fragment: it is not smart to pass data via c-tor to fragments!
Use arguments mechanism:
Fragment f = new SomeFragment();
Bundle args = new Bundle();
args.putExtra("data", someData);
f.setArguments(args);
And retreive them:
getArguments().getParcelableExtra("data")
More info here.
But (to return to your question), for that, your data have to implement Serialisable (Java approach) or, by Google advised Parcelable (Android style)
More info about Parcelable here.
Implementing Parcelable interface can be boring and error prone, so some cool people created this: http://www.parcelabler.com/
If i have an object form interface in my class, how i can pass it to activity?
My solution was to change it as static object, it's work fine but sometimes it create a memory leaks because of all the old references which the garbage collector cannot collect, and i cannot implement 'Serializable' on my interface.
public class MyClass {
protected OnStringSetListener onstringPicked;
public interface OnStringSetListener {
void OnStringSet(String path);
}
//......//
public void startActivity(){
Intent intent=new Intent(context,Secound.class);
// ?! intent.putExtra("TAG", inter);
context.startActivity(intent);
}
}
In my opinion, using Bundles would be a nice choice. Actually bundles internally use Parcelables. So, this approach would be a good way to go with.
Suppose you would like to pass an object of type class MyClass to another Activity, all you need is adding two methods for compressing/uncompressing to/from a bundle.
To Bundle:
public Bundle toBundle(){
Bundle bundle = new Bundle();
// Add the class properties to the bundle
return bundle;
}
From Bundle:
public static MyClass fromBundle(Bundle bundle){
MyClass obj = new MyClass();
// populate properties here
return obj;
}
Note: Then you can simply pass bundles to another activities using putExtra. Note that handling bundles is much simpler than Parcelables.
Passing in custom objects is a little more complicated. You could just mark the class as Serializable
and let Java take care of this. However, on the android, there is a serious performance hit that comes with using Serializable. The solution is to use Parcelable.
Extra info
I am trying to pass an object from an activity to another activity. Here is what i do:
MyApplication.db= dbToOpen;
Intent i = new Intent(mContext, OpenDbActivity.class);
i.putExtra("PARENT_GROUP", dbToOpen.root);
mContext.startActivity(i);
Here, MyApplication is the class that extends application, and db object is a static object. My extra object dbToOpen.root is an object of the class DBGroupv1.
Then i get this extra in onCreate method of OpenDbActivity class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_opendb);
db = MyApplication.db;
groupToOpen = (DBGroupv1) getIntent().getSerializableExtra("PARENT_GROUP");
}
Then i try this boolean expression:
MyApplication.db.root == groupToOpen
and it returns false. When i look at the objects dbToOpen.root and groupToOpen, every single value of the variables inside those objects are the same. But they are are different objects. Why is this happening? Is it because of casting, or does Intent.putextra() method passes a copy of an object, not a reference? If that is the case how can i pass the object as a reference?(Except using static variables)
Thanks
You should use the .equals()-method to compare instances of objects. if you use == you will only get true if the two objects are exactly the same reference. Since the instance in your intent is newly created when deserialized from the bundle, it is no longer a reference to the same instance (although the two objects contains the same data).
So, instead of
MyApplication.db.root == groupToOpen //bad
use
MyApplication.db.root.equals(groupToOpen) //good
Also make sure that if you made the root-object, you implement the equals method properly, so it takes all appropriate variables into consideration.
You can read a bit more here: What is the difference between == vs equals() in Java?
I am making a boolean variable value in one class and accessing the status of that variable in another class , on the basis of the boolean variable status my list view shows items,
So my question is
how to create a global boolean varible
how to pass it to another class
how the second class check it
1. Variable in class A
public class A{
public String aClassVar="hello";
}
Using it in Class B
A obj=new A();
String inBClass=obj.aClassVar;
2. To pass data from one Activity to Another Activity you can use Intent remember your Class should extends Activity only than you will be able to pass data by using Intent
Example
Send Data From First Activity using :
Intent i = new Intent(this, SecondClassName.class);
i.putExtra("key", "Value");// key is used to get value in Second Activiyt
startActivity(i);
Receive Data on Second Activity using:
Intent intent = getIntent();
String temp = intent.getStringExtra("key");// usr getStringExtra() If your extra data is represented as strings:
And you Must set Activity Name inside AndroidManifest.xml
like:
<activity android:name="yourPackageName.SecondClassName" />
Let me suggest 3 options.
Do you want to pass a boolean variable between Android Activities? If so, You may want to use a Bundle. Yes, those little things given to Activities on onCreate(). You can pass variables of your own into these, in your case a boolean, with putBoolean() and getBoolean()
Would you prefer using Android's SharedPref? It's an interface for sharing small preferences, like boolean flags, between parts of your app and storing it for later.
Or, you could just implement a singleton class that has the boolean variable and other variables you need to store and check by different classes within your app.
If you just want to access the value of an object or variable in another class, make it Static and then when you need its value, do like
public class tempClass {
public void tempMethod() {
boolean status = myClass.myVariable ; // where myVariable is static boolean varaible of myClass
}
}
But make sure to access the variable after some value is stored in it.
If you want to send the value to another activity then send the value by using intent.
Eg.
Bundle myBund = new Bundle();
myBund.putBoolean(myBool);
Intent intent = new Intent(myClass.this, tempClass.class);
intent.putExtras("myKey",myBund);
startActivity(myBund);
Im tryin to bundle an Array of Arrays but is not working. Heres a snipped of code for better understanding:
Declaring and Initializing the variable
Inversor[][] reg_equipment= new Inversor[7][5];
for(int i=0; i<7; i++)
{
for(int j=0;j<5;j++)
{
reg_equipment[i][j]= new Inversor();
}
}
//....
Putting the variable in the bundle
bundle.putSerializable("reg_equipment", reg_equipment);
Intent myIntent =new Intent(RegisterEquipmentInversor.this,RegisterEquipmentMain.class);
myIntent.putExtras(bundle);
startActivity(myIntent);
At this point, the reg_equipment is filled with Inversors [Inversor[0],Inversor[1]....,Inversor[6]] and inside those There are more Inversors.
But when I go "get" the bundle in the other class
reg_equipment = (Inversor[][]) extras.getSerializable("reg_equipment");
This is whats inside de reg_equipment - [Object[0],Object[1],...,[Object[6]] and inside those Objects there are Inversors. Why does this happens ? How can I fix it ?
The class Inversor implements Serializable
Thanks
You should try to create a Serializable class that has only one property, which should be your array of Inversor arrays and put that object in your intent.
something like
public class InversorArrays implements Serializable {
public final static int serialVersionUID = //let eclipse generate your uid
public Inversor[][] myArray = null;
public InversorArrays (Inversor[][] _myArray){
this.myArray = _myArray;
}
}
and then, in your activity, create an instance of InversorArrays an pass it to the intent
Of course, Inversor and its properties should be serializable too.
This workaround sometimes saved me a lot of time and problems with typecasting and conversion problems
I am not sure, but have you made the investor class serializable? I think if we could get a basic view of the investor class, that may lead to some light.
I would say start off by making Investor serializable. http://www.tutorialspoint.com/java/java_serialization.htm