Search code examples
javaandroidandroid-sharedpreferences

How to pass image View to another layout and save it inside the layout?


I was able to pass image view to another layout but once I close the app or change the layout and go back to the layout with the passed image view. The image view disappears. My question is how do I keep the image view inside the layout it was passed too? Here's what I found online to pass image view.

FirstClass.java

RandomImageHere.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(getApplicationContext(), SecondClass.class);

            intent.putExtra("resourseInt", R.drawable.picture);
            startActivity(intent);

        }
    });

SecondClass.java

private ImageView imageView;

Bundle extras = getIntent().getExtras();
  imageView = (ImageView) findViewById(R.id.image_view);

    if (extras == null)
    {
        return;
    }
    int res = extras.getInt("resourseInt");
    imageView.setImageResource(res);

SecondClass.xml

<ImageView
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:id="@+id/image_view"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />

Solution

  • I was able to pass image view to another layout but once I close the app or change the layout and go back to the layout with the passed image view. The image view disappears.

    You are adopting the wrong solution. If you are passing data from Activity FirstClass to -> SecondClass and require to access that data without the awareness of the FirstClass the next time, then you ought to save that specific info in storage. You can use SharedPreferences for this, this is how you do it:

    In your FirstClass :

    RandomImageHere.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
    
            SharedPreferences pref = getSharedPreferences("Images", Context.MODE_PRIVATE);
            SharedPreferences.Editor ed = pref.edit();
            ed.putInt("IMG", R.drawable.picture);
            ed.apply();
            Intent intent = new Intent(getApplicationContext(), SecondClass.class);
            startActivity(intent);
    
        }
    });
    

    Then in your SecondClass :

        private ImageView imageView;
        imageView = (ImageView) findViewById(R.id.image_view);
        SharedPreferences pref = getSharedPreferences("Images", Context.MODE_PRIVATE);
        int res = pref.getInt("IMG",0);
        if(res!=0)
        {
            imageView.setImageResource(res);
    
        }