I'm making a program that requires transfer of data between Activities, I see the boolean array object I'm trying to transfer in MyIntent.mExtras.mMap, but when I do,
Intent.getBooleanArrayExtra("AnsweredBoolAR")
I get null. I'm using
Intent MyIntent = new Intent(MainActivity.this, DataSummary.class);
MyIntent.putExtra("AnsweredBoolAR", Answered.toArray());
to send my data.
I've used the debugger and the array that I'm putting into the key and value set isn't null.
When you use the toArray() method of ArrayList, it returns an array of Object[] rather than an array of the specific type contained by the ArrayList.
When you call getBooleanArrayExtra(...) on the Intent however, it will be looking specifically for boolean[] and returns null because it can't find an array of that type.
ArrayList implements Serializable so you can put the whole thing as it is by using...
MyIntent.putExtra("AnsweredBoolAR", Answered);
...then when you want to retrieve it from the Intent just use the getSerializableExtra(...) method of Intent.
Related
The are different ways how to pass data among components and apps in Android. For instance, here are some of them:
Intent intent = new Intent(this, DestinationActivity.class);
intent.putExtra("key", "value");
or
Bundle args = new Bundle();
args.putInt("someInt", someInt);
args.putParcelable("key", ParcelableObject);
Intent intent = new Intent();
intent.setAction("someAction");
intent.putExtra("key", arg);
or
fragment.setArguments(args);
As I know in java primitive values are stored in a stack and objects are placed in a heap. So, I would like to know what's happening when we call these methods: bundle.putInt(int) and bundle.putParcelable(Object), intent.putExtra("key", "string value") and fragment.setArguments(args) in Android.
Not all that much actually happens. Inside of Bundle is a Map. putInt will convert the integer primitive to an Integer object, and put the Integer into the map. putString will put the String object there. putParcelable will put an object that extends Parcelable into the map. That's all that happens at that time.
When startActivity is called, it will walk that map, and basically build a stream of data. The format isn't JSON but it serves a similar purpose- its a well understood format that can be parsed to values later on. As it walks that map, it knows how to add primitives (int, double, etc) to that file. It also knows how to do Strings. For Parcelable objects, there's a function in the object that adds the object to the stream and one to parse it out of the stream. It then takes that stream and asks the OS to pass that stream to the process that implements the intent. THe Android framework in that application will parse the stream back into a map (creating new objects) and then pass it to onCreate.
Why do all this work? Because the intent you run may not be in your process. So it can't share them directly, it needs to make copies. The extras is just a built in serialization method, making it easy to pass complex data.
Why do we sometimes use Bundle and sometimes Intent? Well, every Intent has a Bundle inside it. Calling intent.putIntExtra will call Bundle.putInt on the bundle inside that intent. Its just a convenience method so you don't need to call intent.getExtras().putInt().
I am creating an Intent and using putExtras I am adding an entity data which looks right but in onActivityResult(), some of the data is not received
Intent code:
Thanks
R
Update
When passing a Parcelable value through an Intent causes some of the information in that object to "disappear", the problem is almost always in the parceling/unparceling code of that class. Double-check to make sure that you're correctly saving and restoring all fields.
Update
In your posted code for SetFilterEntity, there is only one constructor: the one that takes a Parcel. Simply add the default constructor to this class:
public SetFilterEntity() {
// init values or just leave them default
}
A behaviour i'm observing w.r.t passing serializable data as intent extra is quite strange, and I just wanted to clarify whether there's something I'm not missing out on.
So the thing I was trying to do is that in ActivtyA I put a LinkedList instance into the intent I created for starting the next activity - ActivityB.
LinkedList<Item> items = (some operation);
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra(AppConstants.KEY_ITEMS, items);
In the onCreate of ActivityB, I tried to retrieve the LinkedList extra as follows -
LinkedList<Item> items = (LinkedList<Item>) getIntent()
.getSerializableExtra(AppConstants.KEY_ITEMS);
On running this, I repeatedly got a ClassCastException in ActivityB, at the line above. Basically, the exception said that I was receiving an ArrayList. Once I changed the code above to receive an ArrayList instead, everything worked just fine.
Now I can't just figure out from the existing documentation whether this is the expected behaviour on Android when passing serializable List implementations. Or perhaps, there's something fundamentally wrong w/ what I'm doing.
Thanks.
I can tell you why this is happening, but you aren't going to like it ;-)
First a bit of background information:
Extras in an Intent are basically an Android Bundle which is basically a HashMap of key/value pairs. So when you do something like
intent.putExtra(AppConstants.KEY_ITEMS, items);
Android creates a new Bundle for the extras and adds a map entry to the Bundle where the key is AppConstants.KEY_ITEMS and the value is items (which is your LinkedList object).
This is all fine and good, and if you were to look at the extras bundle after your code executes you will find that it contains a LinkedList. Now comes the interesting part...
When you call startActivity() with the extras-containing Intent, Android needs to convert the extras from a map of key/value pairs into a byte stream. Basically it needs to serialize the Bundle. It needs to do that because it may start the activity in another process and in order to do that it needs to serialize/deserialize the objects in the Bundle so that it can recreate them in the new process. It also needs to do this because Android saves the contents of the Intent in some system tables so that it can regenerate the Intent if it needs to later.
In order to serialize the Bundle into a byte stream, it goes through the map in the bundle and gets each key/value pair. Then it takes each "value" (which is some kind of object) and tries to determine what kind of object it is so that it can serialize it in the most efficient way. To do this, it checks the object type against a list of known object types. The list of "known object types" contains things like Integer, Long, String, Map, Bundle and unfortunately also List. So if the object is a List (of which there are many different kinds, including LinkedList) it serializes it and marks it as an object of type List.
When the Bundle is deserialized, ie: when you do this:
LinkedList<Item> items = (LinkedList<Item>)
getIntent().getSerializableExtra(AppConstants.KEY_ITEMS);
it produces an ArrayList for all objects in the Bundle of type List.
There isn't really anything you can do to change this behaviour of Android. At least now you know why it does this.
Just so that you know: I actually wrote a small test program to verify this behaviour and I have looked at the source code for Parcel.writeValue(Object v) which is the method that gets called from Bundle when it converts the map into a byte stream.
Important Note: Since List is an interface this means that any class that implements List that you put into a Bundle will come out as an ArrayList.
It is also interesting that Map is also in the list of "known object types" which means that no matter what kind of Map object you put into a Bundle (for example TreeMap, SortedMap, or any class that implements the Map interface), you will always get a HashMap out of it.
The answer by #David Wasser is right on in terms of diagnosing the problem. This post is to share how I handled it.
The problem with any List object coming out as an ArrayList isn't horrible, because you can always do something like
LinkedList<String> items = new LinkedList<>(
(List<String>) intent.getSerializableExtra(KEY));
which will add all the elements of the deserialized list to a new LinkedList.
The problem is much worse when it comes to Map, because you may have tried to serialize a LinkedHashMap and have now lost the element ordering.
Fortunately, there's a (relatively) painless way around this: define your own serializable wrapper class. You can do it for specific types or do it generically:
public class Wrapper <T extends Serializable> implements Serializable {
private T wrapped;
public Wrapper(T wrapped) {
this.wrapped = wrapped;
}
public T get() {
return wrapped;
}
}
Then you can use this to hide your List, Map, or other data type from Android's type checking:
intent.putExtra(KEY, new Wrapper<>(items));
and later:
items = ((Wrapper<LinkedList<String>>) intent.getSerializableExtra(KEY)).get();
If you are using IcePick library and are having this problem you can use Ted Hoop's technique with a custom bundler to avoid having to deal with Wrapper instances in your code.
public class LinkedHashmapBundler implements Bundler<LinkedHashMap> {
#Override
public void put(String s, LinkedHashMap val, Bundle bundle) {
bundle.putSerializable(s, new Wrapper<>(val));
}
#SuppressWarnings("unchecked")
#Override
public LinkedHashMap get(String s, Bundle bundle) {
return ((Wrapper<LinkedHashMap>) bundle.getSerializable(s)).get();
}
}
// Use it like this
#State(LinkedHashmapBundler.class) LinkedHasMap map
I want to transfer the object from one activity to another .
in my first class I have put the following
Intent intenttt ;
Intent intentttt.putExtra("user_searchh", cur.toString());
here the cur is the object of Cursor.
I want to transfer it to second class.
in my second class I have put following
Cursor c = (Cursor) getIntent().getSerializableExtra("user_searchh");
I tried to to run both the classes without the above code , it works properly .
But, when I place the above code , it prompts the force to close error.
In DDMS there is error like ... NulpointerException ... DirectCursorDriver.... etc..
I take teke reference from
How to pass an object from one activity to another on Android
having 50 votes.
help me if possible .
thanks ...
I got it ....
first of all ,, when you translate the object to string .. you can never cast it back to the object..
secondly , rather to transfer object from one Activity to another ,, it is preferable to transfer strings from one Activity to second activity .. and then compute the stuff at the second activity ...
while transfering Strings from one Activity to another Activity I made following two mistakes...
1) the first mistake I am making is ....
I use two intent object ..
e.g.
Intent i = new Intent(user_search2.this,rest_name_share.class);
Intent i1= new Intent();
i1.putExtra("restaurant_email", email_of_restaurant);
startActivity(i);
startActivity(i1);
rather you should write like below
Intent i = new Intent(user_search2.this,rest_name_share.class);
i.putExtra("restaurant_email", email_of_restaurant); // here email_of_restaurant is a String object ..
// you can aslo put more than one strings...
startActivity(i);
2) second mistake is that I call the getStringExtra() at the class level .
It should be called in the onCreate() method
the stuff to be called in onCreate() is
Intent intent = getIntent();
String email_of_restaurant = intent.getStringExtra("restaurant_detail");
thanks to all ,,....
That's not how Serializable works, you are right that at a fundamental level the object gets converted to a String, but it's much more complicated than just calling obj.toString();
The only objects that you can pass through an Intent are ones that implement the Serializable interface.
So if there is information in the Cursor that you need to pass on, take that out and wrap it in some kind of Serializable object.
OMG. This is quite a little disaster area of a question, huh?
The OP's problem is simple: he is putting a String into an Intent and then trying to retrieve a Serializable. A String is, certainly, Serializable, but the cast to a Cursor isn't going to work.
If one were to attempt to be helpful, instead of just correct, one could point out that, in general, this just isn't going to work. Attempting to Parcel or Serialize a cursor -- an object that represents a connection to a database -- is all but impossible. Consider, for a moment, what it would mean to marshal an entire cursor's data into an intent. But then, I did say "all but" because, actually, using some kind of Binder magic, Android does support Cross-process Cursors (I'd include the link, but SO forbids it). But, no: you can't put a Cursor into an Intent. At all. Ever.
Finally, though, about 3 answers ago, someone should have stopped the insanity and asked, "WTF, Dude??? What are you trying to do??" Here are some ways to accomplish whatever the OP is trying to do:
Pull the data that you need into a model object tree and pass a reference to the it
Re-run the query (this was suggested above, but with no supporting reason)
Put the cursor into a global and refer to it from both Activities.
//For passing :
intent.putExtra("MyKey", YourObj); // From First Activity
// to retrieve object in second Activity
Object obj = getIntent().getSerializableExtra("MyKey"); //In Second Activity
Now you can Convert the Object.
Hope this Helps You.
You have put String Object in this code
So try below code will work.
Intent intentttt.putExtra("user_searchh", cur.toString());
String str=getIntent().getStringExtra("user_searchh");
for Pass Cursor You need to do Something Like this make one class like below.
public class MyCursor implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
Cursor mCursor;
public void setCursor(Cursor paramCursor){
mCursor=paramCursor;
}
public Cursor getCursor(){
return this.mCursor;
}
}
Now before put Object in to PutExtra initialize it with below code
MyCursor mObject=new MyCursor();
//You can set your Cursor in Below code
mObject.setCursor(mCursor);
mIntent.putExtra("mCursor",mObject );
Now in other Activity you can get Cursor by below code.
MyCursor mGetCursor;
mGetCursor=(MyCursor) getIntent().getSerializableExtra("mCursor");
if(mGetCursor!=null){
mGetCursor.getCursor();
}
i want to know the usage of putExtra from very basic level
If you want add information to your intent you can use this method. This information is represented as tuple (key, value). There are the number of value types that can be included into the extras of intent (for instance, int, int[], Bundle, Parcelable, and so on). For each this method there is a corresponding "read" method that is used to get the information from the intent.
So here is a possible example how to use this. Imagine that you want explicitly call the activity B from activity A and pass to it an array of integers:
int intArray[] = {1,2,3,4};
Intent in = new Intent(this, B.class);
in.putExtra("my_array", intArray);
startActivity(in);
To read the information in activity B (in onCreate() method) you should use the following code:
Bundle extras = getIntent().getExtras();
int[] arrayInB = extras.getIntArray("my_array");
Add extended data to the intent.
The name must include a package prefix. For example, the app "com.android.contacts" would use names like "com.android.contacts.ShowAll".
Parameters:
name: The name of the extra data, with package prefix.
value: The double array data value.
Returns the same Intent object, for chaining multiple calls into a
single statement.