Android - 从线程返回值

时间:2013-12-18 14:28:21

标签: android multithreading gridview

我有一个函数可以从资源中检索图像并将其显示在GridView中。 Everithing工作正常,但由于性能问题,我想在运行时拇指创建,所以我创建一个新的ProgressDialog,让我们知道应用程序正在运行的用户:

import java.util.ArrayList;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import com.italiandevteam.chuck.adapter.GridViewAdapter;
import com.italiandevteam.chuck.model.ImageItem;

public class GalleriaPersonaggio extends Fragment{

    Integer personaggio = null;
    private ProgressDialog progressDialog;
    TypedArray imgs = null;

    final ArrayList imageItems = new ArrayList();

    public GalleriaPersonaggio( int personaggio ){

        this.personaggio = personaggio;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        int id = getIdPersonaggio();

        View rootView = null;

        try {
                rootView = inflater.inflate(R.layout.gallery_grid, container, false);
            } 
        catch (InflateException e) {
        }

        final GridView gridView = (GridView) rootView.findViewById(R.id.gridView);
        GridViewAdapter customGridAdapter = new GridViewAdapter(getActivity(), R.layout.gallery_row, getData(personaggio));
        gridView.setAdapter(customGridAdapter);

        gridView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//              HashMap<String, Object> hm = gridView.getAdapter().getPosition(position);
//
//                 String imgPath = (String) hm.get("flag"); //get downloaded image path
//              Intent i = new Intent(getActivity(), MostraImmagine.class); //start new Intent to another Activity.
//              i.putExtra("ClickedImagePath", imgPath ); //put image link in intent.
//              startActivity(i);
            }

    });

        return rootView;
    }

    public int getIdPersonaggio(){
        return this.personaggio;
    }

    private ArrayList getData(int personaggio) {

        // retrieve String drawable array

        switch( personaggio )
        {        
            case 1:{
                imgs = getResources().obtainTypedArray(R.array.chuck_ids);
                break;
            }
            case 2:{
                imgs = getResources().obtainTypedArray(R.array.sarah_ids);
                break;
            }

            default:{
                imgs = getResources().obtainTypedArray(R.array.chuck_ids);
            }

        }



        final ProgressDialog ringProgressDialog = ProgressDialog.show(getActivity(), "Please wait ...", "Loading Images ...", true);
                ringProgressDialog.setCancelable(true);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {

                                int THUMBNAIL_HEIGHT = 100;
                                int THUMBNAIL_WIGHT = 100;
                                for (int i = 0; i < imgs.length(); i++) 
                                {
                                    Bitmap bitmap = BitmapFactory.decodeResource(getActivity().getResources(), imgs.getResourceId(i, -1));
                                    bitmap = Bitmap.createScaledBitmap(bitmap, THUMBNAIL_HEIGHT, THUMBNAIL_WIGHT, false);
//                                  ByteArrayOutputStream baos = new ByteArrayOutputStream();  
//                                  bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//                                  byte[] imageData = baos.toByteArray();
//                                  InputStream is = new ByteArrayInputStream(imageData);
//                                  Bitmap b = BitmapFactory.decodeStream(is);
                                    imageItems.add(new ImageItem(bitmap, "Image#" + i));
                                }

                            } catch (Exception e) {

                            }
                            ringProgressDialog.dismiss();
                        }

                    }).start();


        return imageItems;

    }
}

问题是,最后代码没有返回任何内容,GridView为空,如果我删除它运行良好的线程。

2 个答案:

答案 0 :(得分:0)

线程实例无法返回值,因为run方法的返回类型为void。您可以做的是实现delegate模式(Android中的监听器),或切换到Callable接口和Executors。请注意,等待返回类型可能没有意义。如果你有什么:

伪代码 UIThread:

variable = threadInstance.getResult();

您进行了异步调用,同步

答案 1 :(得分:0)

正如323go所指出的,你可以使用 AsyncTask (更好的恕我直言)。创建一个这样的内部类:

private class MyAsyncTask extends AsyncTask<ArrayList<String>, Integer, Long> {
    ...
}

整数用于更新进度对话框(如果你不需要一个,只需改为使用Void); Long是 DoInBackground 方法的结果。像这样启动你的AsyncTask:

new MyAsyncTask().execute(passing);

现在我不知道你的目标是什么,但如果你按照323go或this tutorial建议的链接,你可以改进你的代码。

修改

在323go评论之后,最好在AsyncTask构造函数中传递对象的ArrayList:

new MyAsyncTask(passing).execute();

当然,在AsyncTask类中,您必须创建一个内部变量:

...
private ArrayList<Object> myArrayList;

private MyAsyncTask(ArrayList<Object> anArrayList) {
    myArrayList = anArrayList;
}
...