Imageview does not keep the selected image after changing activity

I have a MainActivity and a EditActivity, Main shows default info, then it can be changed on EditActivity which sends new info to MainActivity. Edit has a ImageView “@+id/edit_profile_picture”, and a button “@+id/changephotobutton” to change the image with ACTION_GET_CONTENT, passing uri from EditActivity to MainActivity works and image is correctly setted on @+id/main_profile_picture, but when I get again into the EditActivity the @+id/edit_profile_picture is emptyl. If I save changes using action_save the picture I set before stills in MainActivity.

I just want to keep the photo in both imageviews until I change it, and I wanna know how to set a default drawable (“@drawable/img_avatar”)
when app is open (because its blank when app is open) and when picture is removed (i have an “@+id/deletephotobutton” but I haven’t configure it yet).

MainActivity:

package com.example.perfil

import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.ImageView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatDelegate
import com.example.perfil.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    public var UbicationButtomTest: Int = 0
    private var lat: Double = 0.0`your text`
    private var lon: Double = 0.0
    private lateinit var receiveimage: ImageView
    private var uriString: String? = null
    private var uri: Uri? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
        setContentView(binding.root)
        updateUI()

            binding.profileMostrar.setOnClickListener {
                if (UbicationButtomTest==0) {
                    binding.profileMostrar.text = "Lat: $lat, Lon: $lon"
                    UbicationButtomTest=1
                }
                else if (UbicationButtomTest==1) {
                    binding.profileMostrar.text = "Mostrar mapa"
                    UbicationButtomTest=0
                }
            }

        receiveimage = findViewById(R.id.main_profile_picture)
    }

    private fun updateUI(
        name: String = "Asking to Stack Overflow",
        correo: String = "[email protected]",
        web: String = "https://stackoverflow.com",
        phone: String = "+01 2345678910")

    {
        binding.profileTvNombre.text = name
        binding.profileTvCorreo.text = correo
        binding.profileTvWeb.text = web
        binding.profileTvPhone.text = phone

    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main,menu)
        return super.onCreateOptionsMenu(menu)
    }



    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.action_edit) {
            val intent = Intent(this, EditActivity::class.java)
            val uriString = uri.toString()
            intent.putExtra(getString(R.string.img_to_editactivity), uriString)
            intent.putExtra(getString(R.string.k_name), binding.profileTvNombre.text.toString().trim())
            intent.putExtra(getString(R.string.k_email), binding.profileTvCorreo.text.toString().trim())
            intent.putExtra(getString(R.string.k_web), binding.profileTvWeb.text.toString().trim())
            intent.putExtra(getString(R.string.k_phone), binding.profileTvPhone.text.toString().trim())
            intent.putExtra(getString(R.string.k_lat), lat.toString())
            intent.putExtra(getString(R.string.k_lon), lon.toString())

            //startActivity(Intent) <-Solo lanza una vista
            //startActivity(intent) //<- Lanza y espera una respuesta
            editResult.launch(intent)
        }
        return super.onOptionsItemSelected(item)
    }

    private val editResult =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == RESULT_OK) {
                val name = it.data?.getStringExtra(getString(R.string.k_name))
                val correo = it.data?.getStringExtra(getString(R.string.k_email))
                val web = it.data?.getStringExtra(getString(R.string.k_web))
                val phone = it.data?.getStringExtra(getString(R.string.k_phone))
                lat = it.data?.getStringExtra(getString(R.string.k_lat))?.toDouble() ?: 0.0
                lon = it.data?.getStringExtra(getString(R.string.k_lon))?.toDouble() ?: 0.0
                uriString = it.data?.getStringExtra(getString(R.string.img_to_mainactivity)) // Get the Uri string
                if (uriString != null) {
                    val uri = Uri.parse(uriString)  // Recreate the Uri
                    receiveimage.setImageURI(uri)
                    uriString = uri.toString()
                }
                updateUI(name!!, correo!!, web!!, phone!!)
            }
        }
}

EditActivity:

package com.example.perfil

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Patterns
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.example.perfil.databinding.ActivityEditBinding


class EditActivity : AppCompatActivity() {
    private lateinit var binding: ActivityEditBinding
    lateinit var changephotobutton: Button
    lateinit var deletephotobutton: Button
    lateinit var Imageviewineditactivity: ImageView
    private var uri: Uri? = null
    private var uriString: String? = null
    private var restoreUri: Uri? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityEditBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.etnombre.setText(intent.extras?.getString(getString(R.string.k_name)))
        binding.etcorreo.setText(intent.extras?.getString(getString(R.string.k_email)))
        binding.etsitioweb.setText(intent.extras?.getString(getString(R.string.k_web)))
        binding.etphone.setText(intent.extras?.getString(getString(R.string.k_phone)))
        binding.etlat.setText(intent.extras?.getString(getString(R.string.k_lat)).toString())
        binding.etlon.setText(intent.extras?.getString(getString(R.string.k_lon)).toString())

        changephotobutton = findViewById(R.id.changephotobutton)
        deletephotobutton = findViewById(R.id.deletephotobutton)
        Imageviewineditactivity = findViewById(R.id.edit_profile_picture)

        changephotobutton.setOnClickListener {
            val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
                type = "image/*"
            }
            startActivityForResult(intent, 1)
        }

        // Recuperar estado si existe
        var uri = savedInstanceState?.getParcelable<Uri>("restoreUri")
        uri?.let {
            Imageviewineditactivity.setImageURI(it)
        }



        /*
        uriString = intent.getStringExtra(getString(R.string.img_to_editactivity))
        if (uriString != null) {
            uri = Uri.parse(uriString)
            Imageviewineditactivity.setImageURI(uri)
        }

         */
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1 && data != null) {
            uri = data.data // Assuming you have a 'uri' property declared
            Imageviewineditactivity.setImageURI(uri)
            }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        // Guardar estado
        outState.run {
            putParcelable("restoreUri", uri)
        }
        super.onSaveInstanceState(outState)
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        // Recuperar estado
        uri = savedInstanceState.getParcelable<Uri>("restoreUri")
        Imageviewineditactivity.setImageURI(uri)
        super.onRestoreInstanceState(savedInstanceState)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_edit,menu)
        return super.onCreateOptionsMenu(menu)
    }





    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.action_save) {
            /*if (DataValidation()==true) {
                sendData()
            }*/
            sendData()
        }

        return super.onOptionsItemSelected(item)
    }



    fun sendData() {
        val intent = Intent()
        intent.putExtra(getString(R.string.img_to_mainactivity), uri?.toString())
        intent.putExtra(getString(R.string.k_name), binding.etnombre.text.toString())
        intent.putExtra(getString(R.string.k_email), binding.etcorreo.text.toString())
        intent.putExtra(getString(R.string.k_web), binding.etsitioweb.text.toString())
        intent.putExtra(getString(R.string.k_phone), binding.etphone.text.toString())
        intent.putExtra(getString(R.string.k_lat), binding.etlat.text.toString())
        intent.putExtra(getString(R.string.k_lon), binding.etlon.text.toString())
        setResult(RESULT_OK,intent)
        finish()
    }

    private fun DataValidation(): Boolean{
        var ValidationBooleanStatus = true
    //..........
    }

}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center_horizontal"
        android:padding="@dimen/common_padding"
        >

        <androidx.cardview.widget.CardView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:cardCornerRadius="@dimen/radio_size_img"
            app:cardElevation="@dimen/card_elevation"
            android:layout_margin="@dimen/common_padding"
            >
            <ImageView
                android:id="@+id/main_profile_picture"
                android:layout_width="@dimen/size_image"
                android:layout_height="@dimen/size_image"
                tools:src="@drawable/img_avatar"
                android:scaleType="centerCrop"
                />
        </androidx.cardview.widget.CardView>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/text_nombre"
            android:layout_marginTop="@dimen/common_margin"
            />
        <TextView
            android:id="@+id/profile_tv_nombre"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="@dimen/text_size_md"
            tools:text="Nombre"
            android:textColor="@color/black"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/text_correo"
            android:layout_marginTop="@dimen/common_margin"
            />
        <TextView
            android:id="@+id/profile_tv_correo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="@dimen/text_size_md"
            tools:text="[email protected]"
            android:autoLink="email"
            android:textColorLink="@color/black"
            android:textStyle="italic|bold"
            />


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/text_sitio_web"
            android:layout_marginTop="@dimen/common_margin"
            />
        <TextView
            android:id="@+id/profile_tv_web"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="@dimen/text_size_md"
            tools:text="www.sitioweb.org"
            android:textColorLink="#00796B"
            android:autoLink="web"
            android:textStyle="italic|bold"
            />


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/text_phone"
            android:layout_marginTop="@dimen/common_margin"
            />
        <TextView
            android:id="@+id/profile_tv_phone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="@dimen/text_size_md"
            tools:text="+52 22 90 90 90 90"
            android:autoLink="phone"
            android:textColorLink="#009688"
            android:textStyle="italic|bold"
            />


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/text_location"
            android:layout_marginTop="@dimen/common_margin"
            />

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/profile_mostrar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/text_show_location"
            android:layout_marginTop="@dimen/common_margin"
            android:textSize="@dimen/text_size_md"
            android:drawableEnd="@drawable/icon_map"
            />

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/profileLocation"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/text_habilitar_ubicacion"
            android:layout_marginTop="@dimen/common_margin"
            android:textColor="#807575"
            android:textStyle="bold"
            android:textSize="@dimen/text_size_md"
            android:drawableStart="@drawable/icon_settings"
            />
    </LinearLayout>

</ScrollView>

activity_edit.xml:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".EditActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="vertical"
        android:padding="@dimen/common_padding"
        >
        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="@dimen/size_image"
            android:layout_height="@dimen/size_image">

            <androidx.cardview.widget.CardView
                android:id="@+id/image_container"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:cardCornerRadius="0dp"
                >
                <ImageView
                    android:id="@+id/edit_profile_picture"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_centerInParent="true"
                    android:scaleType="centerCrop"
                    tools:src="@drawable/img_avatar" />

                <Button
                    android:id="@+id/changephotobutton"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom|end"
                    android:text="Cambiar foto" />

                <Button
                    android:id="@+id/deletephotobutton"
                    android:layout_width="60dp"
                    android:layout_height="60dp"
                    android:layout_gravity="top|right"
                    android:text="X" />

            </androidx.cardview.widget.CardView>
        </androidx.constraintlayout.widget.ConstraintLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/box_nombre"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="@dimen/common_padding"
            android:layout_marginTop="@dimen/common_padding"
            android:hint="@string/text_nombre"
            >
            <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/etnombre"
                android:inputType="textPersonName"
                />
        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/box_correo"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="@dimen/common_padding"
            android:layout_marginTop="@dimen/common_padding"
            android:hint="@string/text_correo"
            >
            <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/etcorreo"
                android:inputType="textEmailAddress"
                />
        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/box_web"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="@dimen/common_padding"
            android:layout_marginTop="@dimen/common_padding"
            android:hint="@string/text_sitio_web"
            >
            <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/etsitioweb"
                android:inputType="textWebEditText"
                />
        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/box_contacto"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="@dimen/common_padding"
            android:layout_marginTop="@dimen/common_padding"
            android:hint="@string/text_phone"
            >
            <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/etphone"
                android:inputType="phone"/>
        </com.google.android.material.textfield.TextInputLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="@dimen/common_padding"
            android:layout_marginHorizontal="@dimen/common_padding"
            >
            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/box_lat"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="50"
                android:hint="@string/txt_lat"
                >
                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/etlat"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginEnd="@dimen/min_margin"
                    android:inputType="numberDecimal|numberSigned"
                    />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/box_lon"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="50"
                android:hint="@string/txt_lon"
                >
                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/etlon"
                    android:inputType="numberDecimal|numberSigned"
                    />
            </com.google.android.material.textfield.TextInputLayout>
        </LinearLayout>
    </LinearLayout>
</ScrollView>

strings.xml:

<resources>
    <string name="app_name">Perfil</string>
    <string name="text_nombre">Nombre</string>
    <string name="text_correo">Correo</string>
    <string name="text_sitio_web">Sitio Web</string>
    <string name="text_phone">Contacto</string>
    <string name="text_location">Ubicación</string>
    <string name="text_show_location">Mostrar mapa</string>
    <string name="text_habilitar_ubicacion">Habilitar ubicación</string>
    <string name="mm_modificar_info">Modificar Info.</string>
    <string name="txt_lat">Latitud</string>
    <string name="txt_lon">Longitud</string>
    <string name="k_name">k_name</string>
    <string name="k_email">k_email</string>
    <string name="k_web">k_web</string>
    <string name="k_phone">k_phone</string>
    <string name="k_lat">k_lat</string>
    <string name="k_lon">k_lon</string>
    <string name="img_to_editactivity">img_to_editActivity</string>
    <string name="img_to_mainactivity">img_to_mainActivity</string>
</resources>

New contributor

user24737139 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật