简体   繁体   中英

Android thread communication AsyncTask

Current scenario: Example app which stores images from several URLs in the SD cache and displays them in a ListView .

Task: instead of take hard-coded URLs inside a private method in the MainActivity retrieve them from JSON data placed in a URL resource.

I'm retrieving the JSON and parsing the data well, but I'm having difficulties on how to send this parsed data to the MyImageLoaderAdapter because the returned list seems to come later..

File: MainActivity.java

public class MainActivity extends Activity {    
    ...
    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...
        try{
            SimpleAsyncTask mTask = new SimpleAsyncTask();
            mTask.execute(resource);
            ArrayList list = mTask.list;
            String[] strArray = new String[ list.size() ];
            int length = strArray.length; // lenght = 0
            mStrings = new String[ list.size() ];
            int length = strArray.length;
            for( int j = 0; j < length; j++ ) {
                mStrings[j] = list.get(j).toString();
            }   

        }catch (Exception e){}

        // Create custom adapter for listview
        adapter=new MyImageLoadAdapter(this, mStrings);
       ...
    }

    private String[] mStrings={
        "http://resourse1.com",
        "http://resourseN.com",
    };      
}

File: SimpleAsyncTask.java

public class SimpleAsyncTask extends AsyncTask<String, String, String>{
    ArrayList list = new ArrayList();
    protected String doInBackground(String... uri) {
        //working code
    }


    @Override
    protected void onPostExecute(String response) {
        super.onPostExecute(response);
        ...
        return list //expected value;
    }
}

You could do it like this:

public class MainActivity extends Activity implements OnTaskCompleteListener{    

private ArrayList list;
    ...
    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...
        try{
            SimpleAsyncTask mTask = new SimpleAsyncTask();
            mTask.execute(resource); 
        }catch (Exception e){}


       ...
    }

    private String[] mStrings={
        "http://resourse1.com",
        "http://resourseN.com",
    };   

    @Override
    private void onTaskComplete(ArrayList taskList){
    list = taskList;
            //String[] strArray = new String[ list.size() ];
            //int length = strArray.length; // lenght = 0
            //mStrings = new String[ list.size() ];
            //int length = strArray.length;
            //for( int j = 0; j < length; j++ ) {
            //    mStrings[j] = list.get(j).toString();
            //}  
//Instead of the above code you can also use this 
String[] array = list.toArray(new String[list.size()]);

// Create custom adapter for listview
adapter=new MyImageLoadAdapter(this, array);      
}
        }

Now change your Asynctask as follows:

    public class SimpleAsyncTask extends AsyncTask<String, String, String>{

private OnTaskCompleteListener listener;

public SimpleAsyncTask(OnTaskCompleteListener listener) {
    this.listener = listener;
}

    protected String doInBackground(String... uri) {
        //working code
    }


    @Override
    protected void onPostExecute(String response) {
        super.onPostExecute(response);
        ...//Convert the response to list and call your listener
listener.onTaskComplete(list);
        // return list //expected value;// no need of it now.
    }
}

Create an interface in your package.

public interface OnTaskCompleteListener {
void onTaskComplete(ArrayList list);
}

Here you are implementing an interface in your activity, passing it to the async task while creating it, once the onpostexecute is called in the async task you are calling the method implemented in the activity using the passed interface object.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM