简体   繁体   中英

Android - return value from thread

I have a function that retrieve images from the resource and display it in a GridView . Everithing works fine but due to a performance issue I would like to create at runtime thumbs so I create a new ProgressDialog to let know the user that the app is working:

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;

    }
}

The problem is that at the end the code doesn't return anything, the GridView is empty, if I remove the thread it works well.

Thread instances can not return values, since the run method has return type void. What you can do is to to implement the delegate pattern (Listener in Android), or switch to the Callable interface and Executors . Please be aware that waiting for the return type could not make sense. If you something:

Pseudo code UIThread:

variable = threadInstance.getResult();

you made an asynchronous call, synchronous

As pointed by 323go, you can use AsyncTask (much better IMHO). Create an internal class like this:

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

Integer is used to update a progress dialog (if you don't need one, just put Void instead); Long is the result of DoInBackground method. Launch your AsyncTask like this:

new MyAsyncTask().execute(passing);

Now i don't know what you are aiming, but if you follow the link suggested by 323go or this tutorial , you can improve your code.

EDIT

After 323go comments, it is better to pass your ArrayList of object in AsyncTask constructor:

new MyAsyncTask(passing).execute();

Of course in your AsyncTask class you have to create an internal variable:

...
private ArrayList<Object> myArrayList;

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

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