Question

I am asynchronously downloading images that will be part of a GridView. And to update the GridView within the onCreate(), I call notifyDataSetChanged(); on a runOnUiThread();

Now, my question is:

Is there a better way to do this? I am setting the Thread to sleep for 2 seconds to ensure the images will be there the time the data in the adapter gets changed. But, of course, I am hardcoding this condition (It may take more than 2 seconds), and the internet connection might fail preventing the GridView update correctly.

Here is the Thread,

private Runnable myRunnable = new Runnable(){

@Override
public void run() {
    try {
        Thread.sleep(2000); 
        updateData(); // contains notifyDataSetChanged()
        if(images[0] == null){
        Toast.makeText(getApplicationContext(), 
"Your Internet Connection is not working properly", Toast.LENGTH_SHORT).show();                 
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    }

};

Thank you very much!

Was it helpful?

Solution

You can use AsyncTask class. It has three important abstract functions. doInBackground onPostExecute onPreExecute

You can search about this on internet and also can check this link.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top