I have class :
public class ClassList
{
private String Language1;
private String Language2;
public ClassList(String Language1,String Language2)
{
this.Language1 = Language1;
this.Language2 = Language2;
}
public String Language1()
{
return this.Language1;
}
public String Language2()
{
return this.Language2;
}
}
I would like to send ArrayList to another activity by using an instance of this class. Is this possible?
I would like to send ArrayList to another activity by instance using.
It is possible?
Assuming you mean, sending the ClassList to another Activity by using an Intent, you
have to look at the Parcelable interface:
Here's a nice example of how to do it
Related
How do you do that? I have the object class implementing parcelable but i don't know what to do for sending the object from one fragment to another one. Help me please.
You can use the navGraph to share data between fragments.It's easy.
Sharing data between fragments is always painful, as both fragments need to define same interface description and the owner activity must bind two together.
And also need to handle the conditions like other fragment not created or not visible
But with new ViewModel, our life become easy to deal with fragment communication. All we have to do is just create a common ViewModel using the activity scope to handle the communication.
Let’s take an example where as in one fragment we need to show list of news articles , and another to show details of the selected news article.
Step1:- Create the Article model class.
public class Article {
private int articleID;
private String articleName;
private String details;
public int getArticleID() {
return articleID;
}
public void setArticleID(int articleID) {
this.articleID = articleID;
}
public String getArticleName() {
return articleName;
}
public void setArticleName(String articleName) {
this.articleName = articleName;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}
Step2:- Create a ArticleViewModel which holds the objects.
public class ArticleViewModel extends ViewModel {
private LiveData<List<Article>> articleList;
private final MutableLiveData<Article> selectedArticle = new MutableLiveData<Article>();
public MutableLiveData<Article> getSelectedArticle() {
return selectedArticle;
}
public void setSelectedArticle(Article article) {
selectedArticle.setValue(article);
}
public LiveData<List<Article>> getArticleList() {
return articleList;
}
public void loadArticles() {
// fetch articles here asynchronously
}
}
Step3:- Create a ArticleListFragment which take care of your list.
public class ArticleListFragment extends Fragment {
private SharedViewModel model;
public void onActivityCreated() {
ArticleViewModel model = ViewModelProviders.of(getActivity()).get(ArticleViewModel.class);
listItemSelector.setOnClickListener(article -> {
model.setSelectedArticle(article);
});
}
}
Step4:- Create your ArticleDetailFragment to show details of article
public class ArticleDetailFragment extends LifecycleFragment {
public void onActivityCreated() {
ArticleViewModel model = ViewModelProviders.of(getActivity()).get(ArticleViewModel.class);
model.getSelectedArticle().observe(this, { article ->
// update UI
});
}
}
If you observe, both fragments are using getActivity() while getting the ViewModelProviders. Means both fragments receive same ArticleViewModel instance, which is scoped to your parent Activity.
Its just that simple and we get more benefits like
Your Activity no need to worry about this communication
Even one fragment get destroyed, other one use the data in ViewModel.
Happy coding :)
I hope that we can pass data between android application components
by following ways.
1.we can pass data using intent object,
2.we can implement serializable , parcelable interface and pass objects by using intent,
3.we can create a new class by extending Application class, to access global members from anywhere
the android application,
4.sharedpreference ,
5.sqlite.
Are there any other mechanism to send data between android application components?
Another option is create ApplicationPool.
Follow the below steps:-
Initiate the ApplicationPool :-
ApplicationPool pool = ApplicationPool.getInstance();
modify the data on details page and add to pool
pool.put("key", object);
get the modified data on list page from pool
Object object = (Object) pool.get("key");
important notes:- notify the listview or gridview after getting the data
ApplicationPool class file
public class ApplicationPool {
private static ApplicationPool instance;
private HashMap<String, Object> pool;
private ApplicationPool() {
pool = new HashMap<String, Object>();
}
public static ApplicationPool getInstance() {
if (instance == null) {
instance = new ApplicationPool();
}
return instance;
}
public void clearCollectionPool() {
pool.clear();
}
public void put(String key, Object value) {
pool.put(key, value);
}
public Object get(String key) {
return pool.get(key);
}
public void removeObject(String key) {
if ((pool.get(key)) != null)
pool.remove(key);
}
}
Another way is to use static elements, wether it be:
Static fields (with public access for example)
Static properties (meaning private fields with getter and/or setter)
Singletons
Possibly nested classes
While the use of static variables in OOP is debatable, they introduce global state and therefore are a way to accomplish sharing of data inbetween activities too.
1) HashMap of WeakReferences, for example:
public class DataHolder {
Map<String, WeakReference<Object>> data = new HashMap<String, WeakReference<Object>>();
void save(String id, Object object) {
data.put(id, new WeakReference<Object>(object));
}
Object retrieve(String id) {
WeakReference<Object> objectWeakReference = data.get(id);
return objectWeakReference.get();
}
}
Before launching the activity:
DataHolder.getInstance().save(someId, someObject);
From the launched activity:
DataHolder.getInstance().retrieve(someId);
2) Or strange method: store data on server O_o
I have been looking for a long time for a simple way to pass data (string type) from class to activity.
I found some tutorials about passing data from activity to class but is it possible to do the opposite, passing data from class to activity ?
if you import the class in your activity (which is also a class by the way) you can easily access the classes attributes.
example: MyClass.java
package edu.user.yourappname;
public class MyClass {
public string infoToPass = "whatever";
}
MyActivity.java
package edu.user.yourappname;
import edu.user.yourappname.MyClass
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
String myString = MyClass.infoToPass;
}
}
i have no IDE to type this in atm it might contain some errors :S but i hope you get the idea.
if you need more specific help you have to provide a code sample.
also, what do you want to achieve exactly? maybie there's a different approach.
cheers!
Create Interface and implement that in your activity. Pass the activity instance in your class and and call that instance with interface method whenever you like.
To be more clear, create an interface and use it as following:
public interface SomeInterface{
public void passValue(String value);
}
public SomeActivity extends Activity implements SomeInterface{
// place any code you want in your activity, onCreate, onResume, etc.
private void someMethod(){
// Wherever in your activity, initialize your class with your activity.
SomeClass someClass = new SomeClass(this);
someClass.someMethod();
}
public void passValue(String value){
// do whatever you want with your value
}
}
public class SomeClass{
private SomeInterface someInterfaceInstance;
public SomeClass(SomeInterface someInterfaceInstance){
this.someInterfaceInstance = someInterfaceInstance;
}
public void someMethod(){
// Some code...
someInterfaceInstance.passValue("Hello World!");
// Some more code...
}
}
Here is a easy way of doing it -
By defining static variables
In your class, make the String whose value you want to pass public static like this -
public static String pass;
And then in you activity, you can directly access it since it's a public variable like this -
String receive = className.pass;
I have an activity Detail that start a new activity List via Intent.
In List I do stuff and then I need to pass some data back to Detail.
The stack, before calling back from List, should contain Detail (on Pause) and List (running).
The data I need to pass back are an ArrayList<MyObject>, where MyObject implements Parcelable (and all its needed methods), so I can use
intent.putParcelableArrayListExtra("myList", myListOfParcelableObjects);
to send data via Intent.
The problem now is on the called activity, Detail.
I've tried to catch the new intent via onNewIntent(Intent intent) and onResume(..) method, but the first (even using setIntent(intent)) and the second doesn't get the new intent sent from List and the data contained in intent.
How can I get the new intent in Detail, manage new datas and "resume" Detail as it was before calling List?
create a Singleton Manager save the Data there and use the data when needed.
public class DataManager {
private static DataManager instance = new DataManager();
private int mData;
private DataManager() {}
public static DataManager getInstance() {
return instance;
}
public void setData(int number) {
mData = number;
}
public int getData() {
return mData;
}
}
Activity A
DataManager manager = DataManager.getInstance();
manager.setData(1);
Activity B
DataManaget manager = DataManager.getInstance();
int data = manager.getData();
this is an Example.
Hope it helps.
You can use Singleton class for storing common data. Hope it will help.
I have a problem passing an arraylist of complex object between 2 activity, the object (ObjA) is something like this:
ObjA:
-String
-Array of ObjB
where ObjB is:
ObjB:
-String
-Array of ObjC
where ObjC is:
ObjC:
-String
-String
the 3 object are serializable:
public class Obj implements Serializable{
private static final long serialVersionUID = 1L;
}
I try to pass the object as a normal extras but the app crash without any log, how can I pass this array?
The 3 obj are serialazible, they have this form:
public class Materia implements Serializable{
private static final long serialVersionUID = 1L;
String titolo;
String icona;
ArrayList<Sezione> sezioni;
public Materia (){}
public String getTitolo() {
return titolo;
}
public void setTitolo(String titolo) {
this.titolo = titolo;
}
public String getIcona() {
return icona;
}
public void setIcona(String icona) {
this.icona = icona;
}
public ArrayList<Sezione> getSezioni() {
return sezioni;
}
public void setSezioni(ArrayList<Sezione> sezioni) {
this.sezioni = sezioni;
}
}
1. Using Application class
You can do this using your Application object. This way, you can define a getter and setter method in your application class and use them in activities:
public class MyApp extends Application {
private Object obj;
public void setObject(Object obj) {
this.obj = obj;
}
public Object getObject() {
return obj;
}
}
Usage in activities:
MyApp app = (MyApp) getApplication();
app.setObject(/* your complex object */);
And in your second Activity:
MyApp app = (MyApp) getApplication();
Object complexObj = app.getObject();
This is a bad approach. User when switches to another app, Android may kill your app (i.e. the process your app in running in), specially when device is running on low memory. After your app being killed, if user comes back to your app, the Application class is re-instantiated and thereby the obj reference inside being null.
2. Make your complex object implements Serializable or Parcelable
Refer to: Android: Difference between Parcelable and Serializable?
If all the three objects are serializable then,
In Calling activity:
ObjA a = new ObjA();
Intent i = new Intent(this, SecondActivity.class);
i.putExtra("t", a);
startActivity(i);
In called activity:
ObjA a=(ObjA) getIntent().getSerializableExtra("t");