I would like to dynamically start an activity based on the previous activity's input. I have input a string through the previous activity, the only thing is this specific code throws the error
cannot resolve constructor 'Intent(com.MentalMathWorkout.EasyCountDown, java.lang.String)'
Is there a way to make this work?
public class EasyCountDown extends AppCompatActivity {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ecd);
Intent intent = getIntent();
String test = intent.getStringExtra(MainActivity.TEST_TYPE);
String cstring = ".class";
final String activity = test.concat(cstring);
Intent intent = new Intent(EasyCountDown.this, activity);
startActivity(intent); //Start test
}
The ComponentName object does just that:
String activity = intent.getStringExtra(MainActivity.TEST_TYPE);
Intent intent = new Intent(this, new ComponentName(this, activity));
startActivity(intent);
That's assuming this
is an instance of Activity
. (for a Fragment
, use getActivity()
, obv.)
I have a class on here:
com.yasinkacmaz.newproject.activity.ProfileActivity
My test string like that:
"com.yasinkacmaz.newproject.activity.ProfileActivity"
And it working good:
public class EasyCountDown extends AppCompatActivity {
final Activity thisActivity = this;
private Intent previousIntent,nextIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
previousIntent = getIntent();
String test = previousIntent.getStringExtra(MainActivity.TEST_TYPE);
final String activity = test;
Class newclass = null;
try {
newclass = Class.forName(activity);
} catch (ClassNotFoundException c) {
c.printStackTrace();
}
if(newclasss != null) {
nextIntent = new Intent(thisActivity, newclass);
startActivity(nextIntent);
} else {
Toast.makeText(getApplicationContext(),"new class null",Toast.LENGTH_SHORT).show();
}
}
}
Dont forget you can use switch case or etc., because in this way you can get ClassNotFoundException
and your intent will be null
.