amh amh - 21 days ago 4
Android Question

Why is this putExtra passing a String instead of an int?

I want to pass an R.drawable id to another activity through an intent. I'm using a switch to find the correct drawable and then using putExtra() to pass it. But when I call getIntExtra it says I passed a String. Is there a problem with this code or is it somewhere else?

int i = getExerciseId(((TextView)getView().findViewById(R.id.fragTextView)).getText().toString());
Intent intent = new Intent(v.getContext(), LevelActivity.class);
intent.putExtra("exerciseId", ((TextView)getView().findViewById(R.id.fragTextView)).getText().toString());
intent.putExtra("image", i);
startActivity(intent);
}

public int getExerciseId(String s) {
int i = -1;
switch (s) {
case "Weather":
i = R.drawable.weather;
break;
case "Weekend":
i = R.drawable.weekend;
break;
case "Hobbies":
i = R.drawable.hobbies;
break;
case "Music":
i = R.drawable.music;
break;
case "Family":
i = R.drawable.family;
}
return i;


edit: there's no log error, I get a red line message in the code saying:

getIntExtra(String, int) in Intent cannot be applied to (String)


in this line of code:

intent.getIntExtra("image");

Answer

It's not telling you that you are getting a string, but that you are calling the getIntExtra method with insufficient parameters. Call it with

getIntExtra("image", 0); // or whichever default value you want to use.