Pass data between activities Android [duplicate] - android

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 5 years ago.
I want to know if there is a way to pass a class object, which can't implement serializable interface between 2 android activities.
I know that to pass data using intent you have to implement serializable interface, but unfortunately I can't do this, any idea?
public class ContactMongo implements Serializable{
private DB collection;
public ContactMongo()
{ }
}
DB doesn't implement serializable, so I can't perform intent.putExtra();

You probably want to use a service, but you haven't told us anything about what you're trying to pass, so I guess you want to use ugly hacks.
There is such an ugly hack available, but it'll quickly get out of control (especially if you cannot even search on this topic by yourself) - you can extend your Application class and use its methods to pass data between activities. Generally, it should be avoided and other ways to pass data and let activities communicate should be used (like extracting the data from the object you want to pass).
Hope this helps you, comment if you have any questions (I'll update my answer with better solution if you give more information on what you're trying to do)

You need to send an intent with whatever you want to pass.
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
Object object;
intent.putExtra("nameforyourobject", object);
startActivity(intent);
https://developer.android.com/training/basics/firstapp/starting-activity.html

Related

Can we usually skip using intents by using public variables in Android?

Many times we use intents to send data to a Fragment or get data back from a child. Can't we just put data in a public variable?
For example imagine if we want to get data from user from a dialog box.
I'm just talking about the "possibility". Undoubtedly, It is superior to use intents for code cleanness or safety...
you don't send intent's to fragments, if you want to use objects you need to have your object implement Parcelable then you can just send the object in the intent bundle
public class MyActivity extends Activity {
public int someValue = 1;
}
And in any fragment which has MyActivity as a host you can access ((MyActivity) getActivity()).someValue.
I think what he means is sending (local)broadcast... which is by the way the proper way of doing it according to my understanding.
Of course it is possible to have public (or even protected) fields and access them from a child-fragment with something like this:
assuming your parent activity is named "MainActivity"
((MainActivity) getActivity()).mMyPublicField
or:
((MainActivity) getActivity()).getPublicMethod()
- but I would never recommend doing this!
especially when you also start manipulating the public field you can run into ugly trouble when different threads are in play.
If something needs so be shared across the whole application, use SharedPreferences (if you want to store it for the next app session too) or as I mentioned first LocalBroadCastManager.

What is the best way for fetching data and for passing to another Activity?

Most the app so far I had created, I fetch the data from Network and store it in a singleton class to share data between Activities, when I'm done with those data, I usually clear those setting it to NULL, its work perfectly well
My Question is which approach is better ??
Use parcelable
Writing in database and Query for it
Singleton classes
When exactly we need to use Loaders ?? Why we can't share the data through Loaders ??
If question is repeated ... Please ignore ??
Answer to first part
Parcelable:
The best way to pass data between Activitys or Fragments is by using Parcelable objects. It is said to be more optimised than Serializable. There are couple of libraries/plugins which can help you create Parcelable objects. Lately I was referred to Parceler, created by John Carl. However, I personally use Android Parcelable code generator by Michal Charmas, plugin for IntelliJ IDEA and Android Studio.
DataBase or SharedPreferences:
Using DataBase or SharedPreferences to pass data between Activitys or Fragments sounds weird, and since they are not designed to be used this way, it will only create a mess.
Singletons:
Read this very informative post Singletons are Pathological Liars.
Conclusion:
I recommend Parcelable or if you want to be real lazy then go for Serializable (it's not terrible but it's not great either, according to most).
Don't mess up your code by using singletons, DataBases, static fields, etc. They will come back and haunt you.
Answer to second part:
When exactly we need to use Loaders
Loaders, which will be AsyncTaskLoader when you use, are basically used for situations where we want to retrieve data from the server (via web API), or doing something in background. It is similar to using Thread or AsyncTask but is very powerful as it isn't destroyed on screen rotation, unlike those two.
You should read How to Use Loaders in Android and Alex Lockwood's posts on Loaders (this is a series of 4 posts. Very detailed and great).
It all depends on the way you want to use the data.If you want to use the data in future, as in after the application is killed and re launched you should save it in a database.
I would prefer parcelable over a singleton as I don't have to bother about clear the data.
According to the Documentation we generally use loaders to load data asynchronously and to monitor a the data source for change. To my understanding you aren't doing either of them, hence loaders are not required in this case.
1.Database: If you are going to use the network data in future or you are going to do some query operation to perform filtration according to requirement,it is preferable to go with db.
2.Singleton Class: Most of the developer use this because it is more efficient,the values can be changed and retrieve easily with the help of getters and setters.
Here is a very cool way of passing data to another activity I read this somewhere else on Stackoverflow and always use it now. It may not fit your use-case but it sounds like it will.
For example, say you want to pass a parcelable "DataModel" from ActivityA to ActivityB.
Inside ActivityB create a public static method called 'start' like this.
private static final String DATAMODEL_KEY = "datamodel_key";
public static void start(Context context, DataModel dataModel) {
Intent intent = new Intent(context, ActivityB.class);
intent.putExtra(DATAMODEL_KEY, dataModel);
context.startActivity(intent);
}
To start ActivityB simply call the 'start' method above like this
ActivityB.start(this, datamodel);
Use 'this' if called from an activity, or 'getActivity()' from with a fragment.
This will contain the code for starting ActivityB inside ActivityB, like the private static final DATAMODEL_KEY field and such. To answer your question though, go with option 1 and use parcelables and try out the code I posted above to help with starting the Activity with the data.

Android intent extra message versus static variable

What is the purpose of using an intent with a message instead of just declaring a static variable in java and calling it from the new activity? It seems easier to me this way because you can have the static variable be anything you want (i.e. ArrayList, Object, etc.).
public class FirstActivity extends Activity {
public static String name;
...
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
name = "Robert";
startActivity(intent);
}
public class SecondActivity extends Activity {
...
textView.setText(FirstActivity.name);
}
By using extras to start SecondActivity, you make it more reusable. Many of the stock activities work this way, that's why you can reuse for example the camera activity to take and save photos, because it does not make assumptions about who is calling it.
In your case SecondActivity depends on FirstActivity having been loaded in the JVM. I would not count on that, and it's certainly not a recommended practice to have such dependency between activities. Don't do this. Use extras to pass values between activities, as recommended by the SDK.
To clarify, the OP's strategy won't work if another app outside of his/hers wants to handle the Intent. Because of this, it's not a "best practice".
There are roughly 30 different putExtra variations for an Intent, each representing a different data type you can add. They include general purpose data types such as Bundle, Parcelable, Serializable, and so forth. I can't think offhand of anything that these don't cover.
I don't use statics or variables defined by overriding Application or other similar ways of assuming that some data is floating about in storage. It's much more robust to assume that my Activity or Fragment is totally independent.
Using Intent make you slower than static
For example if you use mvp or mvvm
At least you have to pass like id through layer by later

Android Intent :-Use Intent to pass class objects from Activities [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to send an object from one Android Activity to another using Intents?
I want to pass a class object from an Activity to other when one Activity calls to the other. I am trying to use Intent.putExtra(name, value) to make that but then I donĀ“t have Intent.getExtra(name) method. There are a lot of methods like getStringExtra(name), getDataExtra(name) and so on but what I put in the value of putExtra is a class object that have a lot of different values as String, Data and int. How can I make to pass that class?
You can use Serializable or Parcelable
If you use Serializable you only have to implement it by writing implements Serializable
If you use Parcelable you have to fill in the used methodes. See: http://developer.android.com/reference/android/os/Parcelable.html
Read about the differences here: http://www.mooproductions.org/node/6
Conclusion: Parcelable is really alot faster but takes more time to implement.
In order to pass your custom objects through Intent, you need to make sure that your class implements Parcelable.
For more info, read this tutorial.

Learning about Intents, passing Data

Does anyone know any good resources where a beginner and understand Intents and Contexts. I understand the basics of activities, but i don't really understand how Intents go along with this.
Also, anyone know any good resources to learn about passing information between activities? For example, I have a splash screen, and I have multiple levels for an addition activity. I created an addition activity, but i want to be able to press different buttons to determine different difficulties. So obviously I dont want to create like 5 different layouts with the same activity with just the difficulty changed. So since I already have the code for the addition activity, how can I pass data from the splash activity to the addition activity? The data might be an int that designates a difficulty level. I would then be able to access the int from the addition activity and base it off of that.
Thanks
You can easily pass Int between activities using Intents.
Activity1
Intent intent = new Intent(Activity1.this,Activity2.class);
intent.putExtra("param", 1);
startActivity(intent);
Activity2
onCreate(Bundle b) {
int param = getIntent().getIntExtra("param");
}
All primary datatypes Integer,Long,String,etc can be passed as an extra. Technically, anything that is Serializable can be an extra.
Eg.
class Student implements Serializable
{
//...
}
Intent intent = //...
intent.putSerializable("key", new Student());
To retrieve it,
Student s = (Student)getIntent().getSerializableExtra();
http://developer.android.com/guide/topics/intents/intents-filters.html
http://www.vogella.de/articles/AndroidServices/article.html
I really recommend a lot of Vogella's tutorials. They've really helped me out a lot.

Categories

Resources