Surya Teja Surya Teja - 5 months ago 30
Android Question

Generation of random Image by tapping on imageView

I simply want to generate a random image from drawable images, when i tap on the imageView. Whenever i run this code, the app on the emulator gets crashed. what's wrong with this code:

package com.example.surya.musicpleer;

import android.app.Activity;
import android.graphics.Typeface;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends Activity {

ImageView i1;
Random r = new Random();
int target = r.nextInt(3);
String drawablename = "photo" + target;

int resID = getResources().getIdentifier(drawablename, "drawable", getPackageName());

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i1 =(ImageView)findViewById(R.id.imageView);
i1.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View v) {
i1.setImageResource(resID);
}
});
}


}

Answer

I have Modified your code just copy & paste it, your problem was you are creating random no & accessing resource out of onCreate() method

 package com.example.surya.musicpleer;

import android.app.Activity;
import android.graphics.Typeface;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends Activity {

    ImageView i1;
    Random r = new Random();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        i1 = (ImageView) findViewById(R.id.imageView);
        i1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                int target = r.nextInt(3);
                String drawablename = "photo" + target;

                int resID = getResources().getIdentifier(drawablename, "drawable", getPackageName());

                i1.setImageResource(resID);
            }
        });
    }
}

You need to put four images in drawable like photo0 to photo3

EDIT

Unfortunately there is notany method to get drawable of imageview but you can do it by setTag() to imageview as below

i1.setImageResource(resID);
i1.setTag(resID); // this line is importent 

& get that tag using this method

private int getDrawableId(ImageView iv) {
    return (Integer) iv.getTag();
}

now u can compare values returned by above method if they are same means both imageview have same drawable.