Search code examples
androidkotlinpicassoandroid-lifecycle

Reload image after pressing back


I have two activities, A and B. When a user presses a button in A, B starts and loads an image using Picasso.

Example A to B

When the user presses back and then presses the button in A again, B shows the same image.

I want the image in B to reload in order to show a different image.

A to B image reloaded after pressing back

How do I reload it? I was thinking of moving the image loading code in B from onCreate() to onRestart() or onResume(). Is this the right idea?

Button:

val goButton = findViewById<Button>(R.id.btn_go)
        goButton.setOnClickListener {
            val intent = Intent(this, WritingActivity::class.java)
            startActivity(intent) 
        }

Load image:

private const val RAND_IMAGE_URL:String = "https://images.unsplash.com/photo-1617386564901-be7cfcaa4c60?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=800&ixlib=rb-1.2.1&q=80&w=800"


override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_writing)

        // Load the random image
        val image = findViewById<ImageView>(R.id.iv_image)
        Picasso.get().load(RAND_IMAGE_URL)
                        .error(R.drawable.ic_error_outline_72)
                        .into(image, object : Callback {
                            override fun onSuccess() {
                                // successfully loaded, start countdown timer
                                startTimer()
                                //  hide progress bar
                                progressBar.visibility = View.GONE
                            }

                            override fun onError(e: Exception?) {
                                // display error message
                                Toast.makeText(this@WritingActivity, R.string.error_loading_image, Toast.LENGTH_LONG).show()
                                Log.e(TAG, "error loading image", e)
                                //  hide progress bar
                                progressBar.visibility = View.GONE
                            }

                        })
    }

Solution

  • When you visit this URL through the browser it does some processing and shows you a random image every time.

    But in the case of Picasso, Picasso first checks its cache memory against that same URL before fetching it from the server. Since the URL is constant it going to show you the same image which was fetched first.

    So is this case either you can clear the cache for Picasso or request Picasso to load a fresh image for this URL.

    Picasso.with(this)
       .load(URL).skipMemoryCache().into(YOUR_IMAGE_VIEW);