-1

First of, sorry for the bad title, I couldn't think at all what to call this.

Say if I have a string with a value of "ActivityMain", and I have a Activity in my project called ActivityMain. Is there anyway I can get a new instance of the class by the string?

The overall idea is to request data from a server, what sends back some different Activity classes, then I want to start whatever activity is returned.

TMH
  • 6,096
  • 7
  • 51
  • 88

4 Answers4

2

Assuming you can get the fully qualified name for the activity's class, you could follow this answer and use:

Class<?> act = Class.forName("com.bla.TestActivity");
Community
  • 1
  • 1
Vitor M. Barbosa
  • 3,286
  • 1
  • 24
  • 36
  • I'll try this out now, I have a if else ladder at the moment, but I'd like to be able to add new activities without needed to edit the if else's – TMH Sep 12 '13 at 17:41
2

I think if else if ladder may do what you want.

if(responsefromsever.equals(NameOfActivityInString)){
 // instantiate the activity
}

use case: I am assuming there exist a Activity class whose name is MainActivity. And what you receive from server is response, (i.e String)

String nameOfActivity = "MainActivity";
if(response.equals(nameOfActivity)){
 MainActivity instantiation or whatever you want to do
}else if(response.equals("SomeOtherActivity")){
 //SomeOtherActivity or whatever you want to do
}
Gaurav Gupta
  • 4,586
  • 4
  • 39
  • 72
1

The overall idea is to request data from a server, what sends back some different Activity classes, then I want to start whatever activity is returned.

A simple way hat is coming to me is that you can have some switch condition or if-then-else conditions which would compare the string received and accordingly start the desired activity. Eg:

if ( stringReceived.equals("ActivityMain"){
//start ActivityMain
} else{
//others...
}

This might be useful, if there are not many activities to start.

Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124
0

It seems like you are sharing implementation details to your server of your client program. What if you want to hook up the server to an iOS app? Then the whole activity name returning idea wouldn't work. "Drawing a different line" for your interfaces might be the best option.

Johnny Z
  • 14,329
  • 4
  • 28
  • 35