【问题标题】:Android Java creating new thread in BaseAdapter not workingAndroid Java在BaseAdapter中创建新线程不起作用
【发布时间】:2014-08-27 23:48:20
【问题描述】:

我正在开发一个 android 应用程序,对于该应用程序,我有一个从数据库加载数据的活动,其中包括文本和图像。目标是这些图像以圆形显示,直到现在一切正常。

问题是,当我启动 Activity 时,它使用 AsyncTask 类接收数据并显示“正在加载”对话框,但是当它传递给我的 BaseAdapter 时,它会阻塞,直到所有图像都被加载,这使得应用程序成为懒惰的。我该怎么做才能解决这个问题?

下面你有我所有的代码过程。

NotificationsActivity (LoadNotifications AsyncTask)

class LoadNotifications extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Notifications.this);
        pDialog.setMessage("Loading..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    protected String doInBackground(String... args) {

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("token", token));

        Log.d("TOKEN", token);

        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(getMyNotificationsURL,
                "POST", params);

        try { // Trying to get notifications

            // Getting Array of notifications
            notifications = json.getJSONArray("notifications");

            userImage = new String[notifications.length()];
            message = new String[notifications.length()];
            param = new String[notifications.length()];
            type = new String[notifications.length()];
            timestamp = new String[notifications.length()];

            // Looping through all notifications
            for (int i = 0; i < notifications.length(); i++) {

                JSONObject c = notifications.getJSONObject(i);

                    try{
                        userImage[i] = c.getString("userImage");
                    } catch(Exception e){
                        userImage[i] = "system";
                    }


                message[i] = c.getString("message");
                param[i] = c.getString("param");
                type[i] = c.getString("type");
                timestamp[i] = c.getString("timestamp");

                Log.d("message", message[i]);

            } // End for

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(String file_url) {

        if (notifications.length() > 0) {

            // updating UI from Background Thread
            runOnUiThread(new Runnable() {

                public void run() {
                    // dismiss the dialog after getting all videos
                    pDialog.dismiss();

                    list = (ListView) findViewById(R.id.notifications_list);
                    NotificationsAdapter adapter = new NotificationsAdapter(
                            mActivity, userImage, message, param, type,
                            timestamp);
                    list.setAdapter(adapter);
                }
            });

        } else {

            pDialog.dismiss();

            Toast.makeText(getApplicationContext(),
                    getString(R.string.noNotifications), Toast.LENGTH_LONG)
                    .show();
            finish();

        }
    } // Close PostExecute
} // Close LoadNotifications

NotificationsAdapter(构造函数中的 for 循环用于加载图像)

public class NotificationsAdapter extends BaseAdapter{

private Activity activity;
private String[] usersImage, messages, params, types, timestamps;
private Bitmap[] loadedImages;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;

public boolean isOnline() {

    ConnectivityManager connectivity = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) 
    {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) 
            for (int i = 0; i < info.length; i++) 
                if (info[i].getState() == NetworkInfo.State.CONNECTED)
                {
                    return true;
                }

    }
    return false;
}

public NotificationsAdapter(final Activity activity, String[] userImage, String[] messages, String[] params, String[] types, String[] timestamps) {
    this.activity       = activity;
    this.usersImage     = userImage;
    this.messages       = messages;
    this.params         = params;
    this.types          = types;
    this.timestamps     = timestamps;

    final ImageHelper imageHelper = new ImageHelper();
    loadedImages = new Bitmap[getCount()];

   /*(new Thread(new Runnable() {

        @Override
        public void run() {
            activity.runOnUiThread(new Runnable() {
                public void run() {*/
                    for (int i=0; i<getCount(); i++){
                        loadedImages[i] = imageHelper.downloadImageTaskOnly(usersImage[i]);
                    }
                    /*areImagesLoaded=true;
                }
            });
        }
    })).start();*/


    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoader=new ImageLoader(activity.getApplicationContext());
}

public int getCount() {
    return messages.length;
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {

    ImageHelper imageHelper = new ImageHelper();

    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.notifications_item, null);

    ImageView   userImage   = (ImageView)   vi.findViewById(R.id.userImage);
    TextView    message     = (TextView)    vi.findViewById(R.id.notification_message);
    TextView    param       = (TextView)    vi.findViewById(R.id.notification_param);
    TextView    type        = (TextView)    vi.findViewById(R.id.notification_type);
    TextView    timestamp   = (TextView)    vi.findViewById(R.id.notification_timestamp);

    if (!isOnline()) {
        Toast.makeText(activity,
                activity.getString(R.string.noInternetConnection),
                Toast.LENGTH_SHORT).show();
    } else {
        if(usersImage[position].equalsIgnoreCase("system")){
            Bitmap icon = BitmapFactory.decodeResource(activity.getResources(), R.drawable.vidytape_icon);
            userImage.setImageBitmap(imageHelper.BigRoundedShape(icon));
        } else {
            userImage.setImageBitmap(imageHelper.BigRoundedShape(loadedImages[position]));
        }

    }

    message.setText(messages[position]);
    param.setText(params[position]);
    type.setText(types[position]);
    timestamp.setText(timestamps[position]);
    return vi;
}

}

图像助手

downloadImageTaskOnly 方法

public Bitmap downloadImageTaskOnly(String url){
    Log.e("IMAGE HELPER", url);

    try {
        return new DownloadImageTaskOnly().execute(url).get();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

下载ImageTaskOnly AsyncTask

private class DownloadImageTaskOnly extends AsyncTask<String, Void, Bitmap> {

    protected Bitmap doInBackground(String... urls) {
        Log.e("IMAGE HELPER", "DOWNLOAD ONLY");
        String urldisplay = urls[0];
        Log.e("IMAGE HELPER", urldisplay);
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }
} // Close DownloadImageTaskOnly

BigRoundedShape

public Bitmap BigRoundedShape(Bitmap scaleBitmapImage) {
    // TODO Auto-generated method stub
    int targetWidth = 250;
    int targetHeight = 300;
    Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight,
            Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(targetBitmap);
    Path path = new Path();
    path.addCircle(((float) targetWidth - 1) / 2,
            ((float) targetHeight - 1) / 2,
            (Math.min(((float) targetWidth), ((float) targetHeight)) / 2),
            Path.Direction.CCW);

    canvas.clipPath(path);
    Bitmap sourceBitmap = scaleBitmapImage;
    canvas.drawBitmap(sourceBitmap, new Rect(0, 0, sourceBitmap.getWidth(),
            sourceBitmap.getHeight()), new Rect(0, 0, targetWidth,
            targetHeight), null);
    return targetBitmap;
}

我的目标是让用户能够使用应用程序和尚未加载的图像,仍在后台加载

【问题讨论】:

    标签: java android multithreading android-asynctask


    【解决方案1】:

    之所以这么慢是因为

    return new DownloadImageTaskOnly().execute(url).get();
    

    .get() 总是在等待任务完成。 感觉这个教程可以帮到你http://developer.android.com/training/displaying-bitmaps/process-bitmap.html

    您可以尝试将使用过的imageview传递给asynctask,将结果传递给位图中的onPostExecute并在那里设置图像,因此您无需在主线程中等待,只需启动任务即可。 并发会导致一些问题,您可以使用适用于这种情况的教程的第二部分。

    【讨论】:

      【解决方案2】:

      如果您只是下载图像,我建议您使用 Picasso (http://square.github.io/picasso/) 甚至 Ion (https://github.com/koush/ion),这些库可以让您轻松下载甚至转换图像,同时允许您同时使用内存和磁盘缓存。

      希望对你有帮助

      【讨论】:

      • 如何在我的项目中加入毕加索?
      • 我已经在我的项目中包含了毕加索库。它的工作!非常感谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      • 2012-03-18
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多