-1

So I have an ArrayList, and I would like to create intent and switch activities using this piece of code (in ListAdapter class):

for (int i = 0; i <= activityList.size(); i++){

    if (position == i){
        Intent intent = new Intent(context, (activityList.get(i).getName()).class);
        context.startActivity(intent);
    }
}

I am getting an 'identifier expected' error around .class.

I do have a working piece of code, that does what I want, but I have to specify the class (which isn't what I want) here:

if (position == 0) {
    Intent intent = new Intent(context, NextActivity.class);
    context.startActivity(intent);
}

Not exactly sure why the 1st piece of code isn't working. Any help would be greatly appreciated.

2 Answers2

1

you need to pass Class type as Intent's second parameter, where you are using

Intent intent = new Intent(context, (activityList.get(i).getName()).class);

in this type of case you would need List<Class> like

List<Class> activityList = Arrays.asList(ActivityA.class, ActivityB.class, ActivityC.class);

the use it like this:

Intent intent = new Intent(context, activityList.get(i));

I'd suggest to change your List<String> to List<Class>.

Man
  • 2,720
  • 2
  • 13
  • 21
0

The simplest way to this job is to convert your String to class. Here is a code to do that-

for (int i = 0; i <= activityList.size(); i++){
    if (position == i){
        String activity = "YourPackageName."+arrayList.get(i).getName();
        Intent intent = null;

        try {
            intent = new Intent(context, Class.forName(activity));
        } 
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        context.startActivity(intent);
    }
}

The model should return the class name without class keyword. Eg:-Main2Activity

Raj
  • 2,997
  • 2
  • 12
  • 30
  • I tried that, but its giving me this error 'Attempt to invoke virtual method 'boolean android.content.Intent.migrateExtraStreamToClipData()' on a null object reference' – Slavic the Slavic Jul 24 '18 at 19:34
  • Plz send the model and what type of data are you adding in array list @SlavictheSlavic – Raj Jul 24 '18 at 19:36
  • I'm just sending an array list of 4 strings to my ListAdapter. Also I had to change your 'arrayList' to 'activityList', I believe that's what you meant. – Slavic the Slavic Jul 24 '18 at 19:42
  • Your array list must be of type object. Also can you mention the strings that you are passing to the list ? – Raj Jul 24 '18 at 19:44
  • Ah, alright. I'm just passing ("one", "two", "three", "four") simple test strings – Slavic the Slavic Jul 24 '18 at 19:47
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/176674/discussion-between-raj-and-slavic-the-slavic). – Raj Jul 24 '18 at 19:47