In android, how can I create a constructor
for a class
which is also an Activity
?
My problem is,
I want to have two activity cl
Activities can't have user defined constructors, only the default one; they can be instantiated only indirectly via intent creation. If you need to pass data between activities, do it by putting extras to bundles, for example:
bundle.putInt("dist",dist);
then you can extract the data from bundle by
int dist = bundle.getInt("dist");
Put extras before starting the activity:
Intent i = new Intent(this, CalculateFare.class);
Bundle b = new Bundle();
b.putInt("dist",dist);
i.putExtras(b);
startActivity(i);
and then read the extras in the onCreate method:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
int dist;
if (b != null)
{
dist = b.getInt("dist");
}
}
In android, how can I create a constructor for a class which is also an Activity?
You don't.
I want to have two activity classes (estimateFare and Mapping) which both send data to a an activity class (CalculateFare).
None of those classes will be touching each other except via startActivity()
. Pass data between activities via Intent
extras or via a central data model (e.g., database).
When the class is called during runtime of the application I get the following message in the LogCat
That is because you need to delete your constructor.
Move your data into a separate class that isn't an activity at all but is shared between activities. The data can be structured into those data that come from the user and those that come from the network. See, for example, this thread for approaches to sharing data between activities.
Instantiating a CalculateFare object that happens to be an activity won't help when the framework creates another instance when it needs an Activity.
I tried to instantiate Activity inside itself to pass it to a method of another class. I got OutOfMemoryError. So I had that method inside Activity itself and passed it as this object.