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 classes (estimateFare and Mapping) which both send data to a an activity class (CalculateFare
). Mapping takes the data from real time network info, whereas estimateFare takes data from user input. I want CalculateFare
to be able to use the data from either class to perform the calculation, although I have run into trouble with the onCreate
method and the constructor for CalculateFare
. When the class is called during runtime of the application I get the following message in the LogCat
;
Unable to instantiate activity ComponentInfo.
A snippet from CalculateFare is as follows;
public class CalculateFare extends Activity {
TextView t;
static long length;
static int dist;
static int mMonth;
static int mDay;
public static double fare;
double rate1 = 0, rate2a, rate2b, rate3, rate4a, rate4b;
int remDist = 0;
double remLength;
private static int TTS_DATA_CHECK = 1;
private TextToSpeech tts = null;
private boolean ttsIsInit = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fare);
}
public CalculateFare(long length, int dist, int mMonth, int mDay)
{
}
public static void setLength(long l)
{
length = l;
}
public static void setDist(int d)
{
dist = d;
}
public static void setDate(int m, int d)
{
mMonth = m;
mDay = d;
}
public void calc()
{
Any Advice much appreciated
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.
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:
then you can extract the data from bundle by
Put extras before starting the activity:
and then read the extras in the onCreate method:
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.
You don't.
None of those classes will be touching each other except via
startActivity()
. Pass data between activities viaIntent
extras or via a central data model (e.g., database).That is because you need to delete your constructor.