GioCrem83
GioCrem83

Reputation: 27

Set the imageView src based on the value selected in a Spinner

I've been trying to set an ImageView (Default empty) based on the value selected from a Spinner. So in the mainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    sp_home = (Spinner) findViewById(R.id.spinner_home_team);
    sp_away = (Spinner) findViewById(R.id.spinner_away_team);


    sp_home.setOnItemSelectedListener(new OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                                   int arg2, long arg3) {
            if (!sp_home.getSelectedItem().toString().equals("Seleziona Squadra")) {
                setTeamLogo(sp_home.getSelectedItem().toString(), "home");
            }
        }

        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });

    sp_away.setOnItemSelectedListener(new OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                                   int arg2, long arg3) {
            if (!sp_away.getSelectedItem().toString().equals("Seleziona Squadra")) {
                setTeamLogo(sp_away.getSelectedItem().toString(), "away");
            }
        }

        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });

}

The setOnItemSelectedListener method works perfectly the problem comes when I execute the code inside setTeamLogo.

private void setTeamLogo(String teamName, String home_or_away_team){

    int resId = getResources().getIdentifier(teamName, "drawable", getPackageName());
    Toast.makeText(getBaseContext(), resId,
            Toast.LENGTH_LONG).show();


}

The exception that has been thrown is: android.content.res.Resources$NotFoundException: String resource ID #0x0

Any idea why if I use the name of the image instead of the variable teamName everything works perfectly?

Upvotes: 1

Views: 81

Answers (1)

user9130287
user9130287

Reputation:

Use String.valueOf()

If you pass it an integer it will try to look for the corresponding string resource id - which it can't find, which is your error.

check out this post:-

android.content.res.Resources$NotFoundException: String resource ID #0x0

Upvotes: 1

Related Questions