Jithin Jithin - 2 months ago 7
Android Question

Android how to use get set method for image?

In my android application i have one image . i want to change that image using get set methods. I have tried but nothing displayed on the image.

My Method class is ..

int image;

public int getImage() {
return image;
}

public void setImage(int image) {
this.imo = image;
}


My activity class 1 is ..

public class activity1 extends AppCompatActivity{
Method m=new Method;

@TargetApi(Build.VERSION_CODES.LOLLIPOP)

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

cc.setImage(R.drawable.album8);
}
}


My activity Class 2 is

public class activity2 extends AppCompatActivity{


Method aa=new Method;

@TargetApi(Build.VERSION_CODES.LOLLIPOP)

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

ImageView ss= (ImageView) findViewById(R.id.songimage);



ss.setImageResource(aa.getImage());

}

}

Answer

User yout "Method" class like this :

public class Method {

    private static Method instance;
    private int image;

    public static synchronized Method getInstance(){
        if(instance == null){
            instance = new Method();
        }

        return instance;
    }

    public int getImage() {
        return image;
    }

    public void setImage(int image) {
        this.image = image;
    }
}

After on your Activitys :

Method.getInstance().getImage();
Method.getInstance().setImage();

Problem with your code : The model instance lost when you open the other activity.

Ps :

That would be a better way, if you pass your image via intent. Link : Using intents to pass data between activities in android

Comments