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();
}
Related
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
}
i'm developing an app that, when i press a button, downloads a XML file, put the xml data in a custom object and passes it to a second activity.
The problem is that something is wrong: when a call the startActivity() function the app crashes with a Runtime error.
My code is:
public void onClickBtn1(View view)
{
final ProgressDialog dlg = ProgressDialog.show( this, "Data wait", "Waiting data from the site ..");
// Thread to wait data
Thread th = new Thread() {
public void run() {
// Download and parse xml data
final DatiSport dati = new DatiSport();
boolean ret = dati.download();
dlg.dismiss();
// check result
if (ret==true)
{
// -- Ok
handlerUI.post( new Runnable() {
public void run() {
Intent intSec = new Intent(AICSActivity.this, SportActivity.class);
intSec.putExtra("datiSport", dati);
startActivity(intSec);
}
});
}
else
{
The app crashes on the startActivity() call. When i break on the startActivity() line i'm not able to look the variable called 'dati' and i guess this is not well defined.
If i substitute dati with 12345, there is not problem.
Which is the problem with dati ?
--- Changed here cause I'm not enabled to reply myself ---
Ok guys. Thanks for replies!
My guess is that i need to re-design the app data.
My first attempt was: download the XML text and accommodate the data into a (rather) complex object. This object contain a list of championships, each of them contains a list of categories, each of them contains a list of teams.
The problem is that, since the Serializable is not working, the implementation of Parcelable is too complex and it should generate almost the same data as the xml file.
I'm wondering if it should be easier passing directly the xml text to other activities (they have to show in turn the list of championships, then the categories of a selected championship, then the list of teams for a selected category...)
Any other idea?
Extract from this Answer :
Serializable is a standard Java interface. You simply mark a class Serializable by implenting the interface, and Java will automatically serialize it in certain situations.
Parcelable is an Android specific interface where you implement the serialization yourself. It was created to be far more efficient that Serializable, and to get around some problems with the default Java serialization scheme.
Extract from this answer :
Seeing Parcelable might have triggered the question, why is Android
not using the built-in Java serialization mechanism? It turns out that
the Android team came to the conclusion that the serialization in Java
is far too slow to satisfy Android’s interprocess-communication
requirements. So the team built the Parcelable solution. The
Parcelable approach requires that you explicitly serialize the members
of your class, but in the end, you get a much faster serialization of
your objects.
After seeing some answer on StackOverFlow, i come to conclusion that Parcelable is optimized than Serialization in android.
How to make class to Parcelable ?? (Check out this, this & this tutorials)
Use a Serializable or Parcelable when passing objects
You need a class to implement the Serializable class
//to pass :
intent.putExtra("MyClass", obj);
// to retrieve object in second Activity
getIntent().getSerializableExtra("MyClass");
Your class would look something like this;
import java.io.Serializable;
#SuppressWarnings("serial") //with this annotation we are going to hide compiler warning
public class MyClass implements Serializable {
public Deneme(Object obj){
this.obj= obj;
}
private Object obj;
}
The Intent class has a method as
putExtra(String name, int value)
thats why it works when you put 12345 at the place of "value", but there is no overloaded version of putExtra that takes "DatiSport" object.
You must ensure that "DatiSport" is Serializable or Parcelable.
See below for more info-
http://developer.android.com/reference/android/content/Intent.html#putExtra%28java.lang.String,%20java.io.Serializable%29
How to send an object from one Android Activity to another using Intents?
How to pass an object from one activity to another on Android
Make your class implement Serializable interface and then pass object instances in intent extra.
To pass data from one Activity to another :
intent.putExtra("ClassName", obj);
To retrieve data in the Second Activity from the First Activity :
getIntent().getSerializableExtra("ClassName");
I found the problem !!!
An internal class were not implementing Serializable!
In the dump window i saw the internal object 'ioe' that said that there was a NotSerializable error and the name of the class!!
Now i checked each internal class and the data is passed to the next activity.
Thanks a lot
How do you pass an object between views in an android application. I have googled and found that your class needs to implement the appropriate interface. How though do we do it if we do not own the class/object type we are passing (for example from an external library or a random class within the sdk)
I need to pass a HtmlSelect item object (from HtmlUnit open source project) to another class to process it but I cant bundle it up.
Thanks
My best guess is you create a static helper object and pass it like that.
HelperObject class {
static HtmlSelect myHtmlObject
}
source activity:
HelperObject.myHtmlObject = currentHtlmlObject;
startActivity(intent);
Destination activity:
onCreate() {
HtmlSelect htmlSelect = "create a copy copy of HelperObject.myHtmlObject not to have problems and then set it to null"
}
Just use the putExtra() method of your Intent to pass parameters.
At times you need to first "deconstruct" your object into simple elements (Strings, Integers) and then reconstitute it at the other end with getExtras().
Is something wrong with this construct in Android?
class A extends Activity {
private Object myObject = new Object();
#Override
protected void onCreate(Bundle savedInstanceState) {
//myObject = new Object();
}
}
Because at some point(s) later I get (sometimes, not reproducible yet) exceptions because myObject is null. I don't know if it's because I have to initialize in onCreate.
Edit: Additional details:
The actual class of myObject is List<Object> (Where Object is a domain specific type)
At some point later in the activity I'm storing myObject as a static field of a "Parameter passer" class and starting other Activity (because I'm avoiding to implement Parcelable. If this is good or bad practice should not be discussed here, unless that's causing my error). In the other Activity I pick up myObject. There it's (sometimes) null.
Edit 2: I don't understand why this object becomes null if I'm storing a reference to it as static field of my parameter passer class (a standalone, dedicated class). That's how garbage collection works, right, it just removes when the objects are not referenced anymore. So since I have a static reference this object should not be removed. According to this thoughts, if they are correct, the problem should be somewhere else.
When you start a new activity your old one goes on the block for possible garbage collection (including any classes instantiated in it, including your parameter passer class), so your object is not necessarily going to be available (which is why you see an intermittent failure.).
I see two option:
1) Pass it along in the bundle with your intent that starts the new activity. As you were trying to avoid this, probably not your best choice.
2) Extend the Application class and store the object in there.
EDIT
I think the accepted answer to this SO Question might fix your issue (and explain what is actually happening).
No. That code is just fine. You can create objects in the constructor.
You may want to check a previous question about it Instance variable initialization in java and the section 3.2.4. Field Defaults and Initializers which basically states that the first case:
private Object myObject = new Object();
is identical to an initialization in the class constructor. (NOTICE onCreate is NOT the constructor).
So, myObject should never be null, except in the case the "new Object()" instruction failed, generating an exception.
Isn't this possible your code is changing the contents of myObject later on the code?
This question already has answers here:
How to pass an object from one activity to another on Android
(35 answers)
Closed 9 years ago.
I need to be able to use one object in multiple activities within my app, and it needs to be the same object. What is the best way to do this?
I have tried making the object "public static" so it can be accessed by other activities, but for some reason this just isn't cutting it. Is there another way of doing this?
When you are creating an object of intent, you can take advantage of following two methods
for passing objects between two activities.
putParcelable
putSerializable
You can have your class implement either Parcelable or Serializable. Then you can pass around your custom classes across activities. I have found this very useful.
Here is a small snippet of code I am using
CustomListing currentListing = new CustomListing();
Intent i = new Intent();
Bundle b = new Bundle();
b.putParcelable(Constants.CUSTOM_LISTING, currentListing);
i.putExtras(b);
i.setClass(this, SearchDetailsActivity.class);
startActivity(i);
And in newly started activity code will be something like this...
Bundle b = this.getIntent().getExtras();
if (b != null)
mCurrentListing = b.getParcelable(Constants.CUSTOM_LISTING);
You can create a subclass of Application and store your shared object there. The Application object should exist for the lifetime of your app as long as there is some active component.
From your activities, you can access the application object via getApplication().
This answer is specific to situations where the objects to be passed has nested class structure. With nested class structure, making it Parcelable or Serializeable is a bit tedious. And, the process of serialising an object is not efficient on Android. Consider the example below,
class Myclass {
int a;
class SubClass {
int b;
}
}
With Google's GSON library, you can directly parse an object into a JSON formatted String and convert it back to the object format after usage. For example,
MyClass src = new MyClass();
Gson gS = new Gson();
String target = gS.toJson(src); // Converts the object to a JSON String
Now you can pass this String across activities as a StringExtra with the activity intent.
Intent i = new Intent(FromActivity.this, ToActivity.class);
i.putExtra("MyObjectAsString", target);
Then in the receiving activity, create the original object from the string representation.
String target = getIntent().getStringExtra("MyObjectAsString");
MyClass src = gS.fromJson(target, MyClass.class); // Converts the JSON String to an Object
It keeps the original classes clean and reusable. Above of all, if these class objects are created from the web as JSON objects, then this solution is very efficient and time saving.
UPDATE
While the above explained method works for most situations, for obvious performance reasons, do not rely on Android's bundled-extra system to pass objects around. There are a number of solutions makes this process flexible and efficient, here are a few. Each has its own pros and cons.
Eventbus
Otto
Maybe it's an unpopular answer, but in the past I've simply used a class that has a static reference to the object I want to persist through activities. So,
public class PersonHelper
{
public static Person person;
}
I tried going down the Parcelable interface path, but ran into a number of issues with it and the overhead in your code was unappealing to me.
It depends on the type of data you need access to. If you have some kind of data pool that needs to persist across Activitys then Erich's answer is the way to go. If you just need to pass a few objects from one activity to another then you can have them implement Serializable and pass them in the extras of the Intent to start the new Activity.
Your object can also implement the Parcelable interface. Then you can use the Bundle.putParcelable() method and pass your object between activities within intent.
The Photostream application uses this approach and may be used as a reference.