How to Create an Object of an Activity in Other Class

Can I create an object of an Activity in other class?

Activity A should have a variable

static ActivityA activityA;

In onCreate state:

activityA = this;

and add this method:

public static ActivityA getInstance(){
return activityA;
}

In activity B, call

ActivityA.getInstance().myFunction(); //call myFunction using activityA

How to pass an object from one activity to another on Android

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.

Actual Code:

In Your Custom Model/Object Class:

public class YourClass implements Serializable {

At other class where using the Custom Model/Class:

//To pass:
intent.putExtra("KEY_NAME", myObject);

myObject is of type "YourClass".
Then to retrieve from another activity, use getSerializableExtra
get the object using same Key name. And typecast to YourClass is needed:

// To retrieve object in second Activity
myObject = (YourClass) getIntent().getSerializableExtra("KEY_NAME");

Note: Make sure each nested class of your main custom class has implemented Serializable interface to avoid any serialization exceptions. For example:

class MainClass implements Serializable {

public MainClass() {}

public static class ChildClass implements Serializable {

public ChildClass() {}
}
}

How to create object of Activity

If you are looking to start a new activity (like from your main activity to ABC activity), you do it this way

Intent i = new intent(this, ABC.class);
startActivity(i);

if you looking for passing data, use putExtra() method with the intent.
if your data is much larger, you can always use SharedPreferences or SqlLite database, depending on your need.
Hope it helps

How to instantiate an object of an Activity Class from non-Activity Class?

You need to pass current context to your MPLDataBase constructor

 public NotifyArrayAdapter(Context con) {
mplOpenHelperDB = new MPLDataBase(con);
}

like if you call this from any Activity then

 NotifyArrayAdapter notifyarrayAdapter = new NotifyArrayAdapter(yourActivity.This);

like if you call this from any Fargment then

 NotifyArrayAdapter notifyarrayAdapter = new NotifyArrayAdapter(getActivity());

How to send an object from one Android Activity to another using Intents?

the most easiest solution i found is..
to create a class with static data members with getters setters.

set from one activity and get from another activity that object.

activity A

mytestclass.staticfunctionSet("","",""..etc.);

activity b

mytestclass obj= mytestclass.staticfunctionGet();


Related Topics



Leave a reply



Submit