Android:慢画廊视图

时间:2013-10-01 13:15:56

标签: android caching android-gallery

我的画廊出了问题,它会慢下来而且会滞后。我正在使用Image Adapter从服务器加载图像:

package com.example.ocenitaksi;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.apache.http.client.utils.URLEncodedUtils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;



public class ImageAdapter extends BaseAdapter {
    private Context context;
    private final String[] mobileValues;

    public ImageAdapter(Context context, String[] mobileValues) {
        this.context = context;
        this.mobileValues = mobileValues;
    }

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

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View gridView;

        if (convertView == null) {

            gridView = new View(context);

            // get layout from mobile.xml
            gridView = inflater.inflate(R.layout.mobile, null);


            // set image based on selected text
            ImageView imageView = (ImageView) gridView
                    .findViewById(R.id.grid_item_image);



            // ubacivanje slika za string


                String mobile = mobileValues[position];
                if (mobile.equals(MainActivity.imena[position])) {
                //imageView.setImageURI("http://24.media.tumblr.com/avatar_a400b4dbb80e_64.png");
                Bitmap bitmap=null;;

                mobile = mobile.replace(" ", "_");

                        bitmap = DownloadImage("http://android.yunews.net/images/"+mobile+".png");


                    imageView.setImageBitmap(bitmap);

                }


        } 
        else {
            gridView = (View) convertView;
        }

        return gridView;
    }

    @Override
    public int getCount() {
        return mobileValues.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }
    private InputStream OpenHttpConnection(String urlString) throws IOException {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");

        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        } catch (Exception ex) {
            throw new IOException("Error connecting");
        }
        return in;
    }

    private Bitmap DownloadImage(String URL) {
        Bitmap bitmap = null;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return bitmap;
    }
}

这是我主要活动的一部分。

private class LongOperation extends AsyncTask<String, Void, String> 
    {
        protected void onPreExecute() 
        { 
            progressDialog = new ProgressDialog(MainActivity.this); 
            progressDialog.setTitle("Molimo sacekajte...");
            progressDialog.setMessage("Ucitavam taksi sluzbe...");
            progressDialog.setCancelable(true);
            progressDialog.show();
        }

        protected String doInBackground(String... params) 
        {

                niz = new JSONFunkcije().ListaSluzbi();

                imena= new String[niz.size()];
                Iterator<String> it= niz.iterator();
                for (int i=0;i<niz.size();i++)
                    imena[i]=it.next();
                slicice = new ImageAdapter(MainActivity.this, imena);


            return null;
        }
        protected void onPostExecute(String result) 
        {

            progressDialog.dismiss();

            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    //Button dugme1 = (Button) findViewById(R.id.dugme1);

                    ///params.height = "50dpi";
                    //dugme1.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 100));

                    Gallery gridView = (Gallery) findViewById(R.id.gallery1);

                    gridView.setAdapter(slicice);
                    //kraj ucitvanja

                    //gridView.setAdapter(adapter);
                    gridView.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {

                            // Sending image id to FullScreenActivity
                            Intent i = new Intent(getApplicationContext(), TaksiDetalji.class);
                            // passing array index
                            i.putExtra("id", imena[position]);
                            startActivity(i);
                        }
                    });

                }
            });
        System.gc();
        }
      }

我从OnCrate调用LongOperation:

mytask = new LongOperation();
        mytask.execute(); 

ImageAdapter出了什么问题?电话,下载太多了?我试图缓存图像,但我失败了。

2 个答案:

答案 0 :(得分:0)

这是在gridview,listview和pager中显示图像的精彩示例。看看这个

https://github.com/nostra13/Android-Universal-Image-Loader

答案 1 :(得分:0)

从您的代码中,我会说有很多原因,因为以下所有原因导致其运行缓慢:

  1. 您没有关注ViewHolder pattern。阅读Making ListView Scrolling Smooth
  2. 的文档
  3. 您没有按照标准方式加载图片(即本地缓存图片,如果已缓存则从本地加载)
  4. 最好在网络上尝试任何可用的库(Universal Image loader或任何库)来加载ListView中的图像。