Android线程通讯AsyncTask [英] Android thread communication AsyncTask

查看:93
本文介绍了Android线程通讯AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前方案:该示例应用程序将来自多个URL的图像存储在SD缓存中,并将其显示在 ListView 中.

任务:不是在 MainActivity 的私有方法中采用硬编码的URL,而是从放置在URL资源中的JSON数据中检索它们.

我正在检索JSON并很好地解析了数据,但是在如何将解析后的数据发送到 MyImageLoaderAdapter 上遇到了困难,因为返回的列表似乎稍后出现.>

文件: MainActivity.java

 公共类MainActivity扩展了Activity {...@Override公共无效onCreate(捆绑保存的InstanceState){...尝试{SimpleAsyncTask mTask = new SimpleAsyncTask();mTask.execute(资源);ArrayList list = mTask.list;String [] strArray = new String [list.size()];int length = strArray.length;//长度= 0mStrings = new String [list.size()];int length = strArray.length;for(int j = 0; j< length; j ++){mStrings [j] = list.get(j).toString();}}捕获(异常e){}//为列表视图创建自定义适配器adapter = new MyImageLoadAdapter(this,mStrings);...}私人字串[] mStrings = {"http://resourse1.com","http://resourseN.com",};} 

文件: SimpleAsyncTask.java

 公共类SimpleAsyncTask扩展了AsyncTask< String,String,String> {ArrayList list = new ArrayList();受保护的字符串doInBackground(String ... uri){//工作代码}@Override受保护的void onPostExecute(String response){super.onPostExecute(response);...返回列表//期望值;}} 

解决方案

您可以这样做:

 公共类MainActivity扩展Activity实现OnTaskCompleteListener {私有ArrayList列表;...@Override公共无效onCreate(捆绑保存的InstanceState){...尝试{SimpleAsyncTask mTask = new SimpleAsyncTask();mTask.execute(资源);}捕获(异常e){}...}私人字串[] mStrings = {"http://resourse1.com","http://resourseN.com",};@Override私人无效onTaskComplete(ArrayList taskList){list = taskList;//String [] strArray = new String [list.size()];//int length = strArray.length;//长度= 0//mStrings = new String [list.size()];//int length = strArray.length;//for(int j = 0; j< length; j ++){//mStrings [j] = list.get(j).toString();//}//除了上面的代码,您还可以使用此代码String [] array = list.toArray(new String [list.size()]);//为列表视图创建自定义适配器adapter = new MyImageLoadAdapter(this,array);}} 

现在如下更改您的Asynctask:

 公共类SimpleAsyncTask扩展了AsyncTask< String,String,String> {私有的OnTaskCompleteListener侦听器;公共SimpleAsyncTask(OnTaskCompleteListener监听器){this.listener =侦听器;}受保护的字符串doInBackground(String ... uri){//工作代码}@Override受保护的void onPostExecute(String response){super.onPostExecute(response);...//将响应转换为列表并呼叫您的听众listener.onTaskComplete(list);//返回列表//期望值;//现在不需要它.}} 

在您的程序包中创建一个接口.

 公共接口OnTaskCompleteListener {void onTaskComplete(ArrayList list);} 

这里您要在活动中实现接口,并在创建接口时将其传递给异步任务,一旦在异步任务中调用了onpostexecute,您便会使用传递的接口对象来调用在活动中实现的方法.

希望这会有所帮助.

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.

这篇关于Android线程通讯AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆