Android中的ListView内存泄漏

Android中的ListView内存泄漏,android,Android,我写了一个从JSON获取图像的类。它正在工作,但是内存有问题。当我向下滚动应用程序时,它正在内存中泄漏。这是我的代码 package com.nexum.senddata; public class MainActivity extends Activity { private ListView list; private MyAdapter adapter; private final String parsingUrl = "http://sametdede.com/expo/

我写了一个从JSON获取图像的类。它正在工作,但是内存有问题。当我向下滚动应用程序时,它正在内存中泄漏。这是我的代码

package com.nexum.senddata;

public class MainActivity extends Activity {

private ListView list;
private MyAdapter adapter;

    private final String parsingUrl = "http://sametdede.com/expo/data.json";
private String tag_coord = "Coord";
private String tag_lat = "Lat";
private String tag_lon = "Lon";// Double
private String tag_image = "Image";
private String tag_InIzmir = "InIzmir";
private String tag_name = "Name";

private ProgressDialog pDialog;

private static int clickedItemPosition = -1;
private final int REQUEST_CODE_DETAIL = 1;

ArrayList<CoordItem> items;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    items = new ArrayList<CoordItem>();
    adapter = new MyAdapter(this, R.layout.list_item, items);

    list = (ListView) findViewById(R.id.exampList);
    list.setAdapter(adapter);

    pDialog = new ProgressDialog(this);
    pDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    pDialog.setMessage("Veriler alınıyor...");

    new ListViewLoad().execute();

    list.setOnItemClickListener(new OnItemClickListener() {

        @SuppressLint("ShowToast")
        @Override
        public void onItemClick(AdapterView<?> a, View v, int position,
                long id) {
            /*
             * String bulunma = ""; if (items.get(position).inIzmir) {
             * bulunma+="İzmir de bulundu."; }else{
             * bulunma+="İzmir de bulunmadı."; } String
             * s="Name:"+items.get(position).name+"\nInIzmir:"+bulunma;
             * Toast.makeText(getApplicationContext(), s,
             * Toast.LENGTH_LONG).show();
             */

            clickedItemPosition = position;
            Intent myIntent = new Intent(MainActivity.this,
                    DetailActivity.class);
            Bundle bundle = new Bundle();
            bundle.putParcelable(
                    "parcelable_key",
                    new CoordItem(items.get(position).name, items
                            .get(position).img, items.get(position).lat,
                            items.get(position).lon,
                            items.get(position).inIzmir));
            myIntent.putExtras(bundle);
            // Güncelleme olayı burada başlıyor
            // startActivityForResult(myIntent, REQUEST_CODE_DETAIL);

            startActivityForResult(myIntent, REQUEST_CODE_DETAIL);

        }

    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_CODE_DETAIL && resultCode == RESULT_OK
            && data != null) {
        CoordItem coorditem = new CoordItem(data.getStringExtra("name"),
                items.get(clickedItemPosition).img, Double.parseDouble(data
                        .getStringExtra("lat")), Double.parseDouble(data
                        .getStringExtra("lon")),
                items.get(clickedItemPosition).inIzmir);

        items.set(clickedItemPosition, coorditem);
        adapter.notifyDataSetChanged();
        Toast.makeText(getApplicationContext(), "Guncelleme yapıldı.",
                Toast.LENGTH_SHORT).show();
    }
    /*
     * CoordItem coorditem = new CoordItem(data.getStringExtra("name"),
     * items.get(clickedItemPosition).img,
     * Double.parseDouble(data.getStringExtra("lat")),Double.parseDouble(
     * data.getStringExtra("lon")), items.get(clickedItemPosition).inIzmir);
     * 
     * items.set(clickedItemPosition, coorditem);
     * adapter.notifyDataSetChanged();
     * Toast.makeText(getApplicationContext(), "Guncelleme yapıldı.",
     * Toast.LENGTH_SHORT).show();
     */

}

private class ListViewLoad extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {

        String json = getStringFromURL(parsingUrl);
        try {
            final JSONArray jArray = new JSONArray(json);

            for (int i = 0; i < jArray.length(); i++) {
                JSONObject c = jArray.getJSONObject(i);
                JSONObject coord = c.getJSONObject(tag_coord);
                double lat = coord.getDouble(tag_lat);
                double lon = coord.getDouble(tag_lon);
                String image = c.getString(tag_image);
                boolean InIzmir = c.getBoolean(tag_InIzmir);
                String name = c.getString(tag_name);

                CoordItem item = new CoordItem(name, image, lat, lon,
                        InIzmir);
                items.add(item);
            }

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

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        adapter.notifyDataSetChanged();

        pDialog.dismiss();
    }

}

private class MyAdapter extends ArrayAdapter<CoordItem> {

    private LayoutInflater inflater;

    public MyAdapter(Context context, int textViewResourceId,
            ArrayList<CoordItem> objects) {
        super(context, textViewResourceId, objects);

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

    @Override
    public int getCount() {
        if (items != null)
            return items.size();
        else
            return 0;
    }

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

        ViewHolder viewholder = null;

        if (convertView == null) {
            viewholder = new ViewHolder();

            convertView = inflater.inflate(R.layout.list_item, parent,
                    false);
            viewholder.listItemImage = (ImageView) convertView
                    .findViewById(R.id.listItemImage);

            viewholder.listItemName = (TextView) convertView
                    .findViewById(R.id.listItemName);
            viewholder.listItemInIzmir = (TextView) convertView
                    .findViewById(R.id.listItemInIzmir);
            viewholder.listItemLatitude = (TextView) convertView
                    .findViewById(R.id.listItemLatitude);
            viewholder.listItemLongitude = (TextView) convertView
                    .findViewById(R.id.listItemLongitude);
            convertView.setTag(viewholder);
        } else {
            viewholder = (ViewHolder) convertView.getTag();
        }

        viewholder.listItemName.setText(items.get(position).name);
        if (items.get(position).inIzmir) {
            viewholder.listItemInIzmir.setText("Izmirde.");
        } else {
            viewholder.listItemInIzmir.setText("Izmirde degil.");
        }

        try {
            viewholder.listItemImage
                    .setImageDrawable(getDrawableFromUrl(new URL(items.get(
                            position).getImg())));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return convertView;
    }

    public Drawable getDrawableFromUrl(URL url) {
        try {
            InputStream is = (InputStream) url.getContent();
            Drawable d = Drawable.createFromStream(is, "src");
            return d;
        } catch (Exception e) {
            return null;
        }
    }

}

/**
 * Burada layoutinflater da kullandığımız layoutun componentlerini
 * yazıyoruz.Bu da bizim list_item.xml imizdir.
 */
static class ViewHolder {
    ImageView listItemImage;
    TextView listItemName, listItemInIzmir, listItemLatitude,
            listItemLongitude;
}

public String getStringFromURL(String url) {

    // Making HTTP request
    String json = "";
    InputStream is = null;
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }

    // return JSON String
    return json;

}
package com.nexum.senddata;
公共类MainActivity扩展了活动{
私有列表视图列表;
专用MyAdapter适配器;
私有最终字符串parsingUrl=”http://sametdede.com/expo/data.json";
私有字符串tag_coord=“coord”;
私有字符串标记_lat=“lat”;
私有字符串标记_lon=“lon”//Double
私有字符串tag_image=“image”;
私有字符串标记_inizimir=“inizimir”;
私有字符串标记_name=“name”;
私人对话;
私有静态int-clickedItemPosition=-1;
私人最终整数请求\代码\详细信息=1;
数组列表项;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
items=newarraylist();
适配器=新的MyAdapter(此,R.layout.list_项,项);
list=(ListView)findViewById(R.id.exampList);
list.setAdapter(适配器);
pDialog=新建进度对话框(此对话框);
pDialog.requestWindowFeature(Window.FEATURE\u NO\u TITLE);
pDialog.setMessage(“Veriler alınıyor…”);
新建ListViewLoad().execute();
list.setOnItemClickListener(新的OnItemClickListener(){
@SuppressLint(“ShowToast”)
@凌驾
公共视图单击(适配器视图a、视图v、内部位置、,
长id){
/*
*字符串bulumma=“”;if(items.get(position.mir){
*布隆玛+=“布隆杜之家”;}其他{
*Bulumba+=“İzmir de Bulumbadı.;}字符串
*s=“Name:”+items.get(position).Name+”\nizmir:“+bulumma;
*Toast.makeText(getApplicationContext(),s,
*Toast.LENGTH_LONG).show();
*/
单击编辑位置=位置;
Intent myIntent=新Intent(MainActivity.this,
活动类);
Bundle=新Bundle();
包裹(
“可随身携带的钥匙”,
新坐标(items.get(position).名称,items
.get(位置).img,items.get(位置).lat,
项目。获取(位置)。lon,
items.get(position.mir));
myIntent.putExtras(bundle);
/玉兰油
//startActivityForResult(我的意图、请求代码和详细信息);
startActivityForResult(我的意图、请求代码和详细信息);
}
});
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
//TODO自动生成的方法存根
super.onActivityResult(请求代码、结果代码、数据);
如果(requestCode==请求\代码\详细信息和结果代码==结果\确定
&&数据!=空){
CoordItem CoordItem=新的CoordItem(data.getStringExtra(“名称”),
items.get(单击编辑位置).img,Double.parseDouble(数据
.getStringExtra(“lat”)、Double.parseDouble(数据
.getStringExtra(“lon”),
获取(单击编辑位置).mir);
设置项目(单击编辑位置、坐标);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(),“Guncelleme yapıldı”,
吐司。长度(短)。show();
}
/*
*CoordItem CoordItem=新的CoordItem(data.getStringExtra(“名称”),
*items.get(单击编辑位置).img,
*Double.parseDouble(data.getStringExtra(“lat”)),Double.parseDouble(
*data.getStringExtra(“lon”)、items.get(单击编辑位置).mir);
* 
*设置项目(单击编辑位置、坐标);
*adapter.notifyDataSetChanged();
*Toast.makeText(getApplicationContext(),“Guncelleme yapıldı”,
*吐司。长度(短)。show();
*/
}
私有类ListViewLoad扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog.show();
}
@凌驾
受保护的Void doInBackground(Void…参数){
字符串json=getStringFromURL(parsingUrl);
试一试{
最终JSONArray jArray=新JSONArray(json);
for(int i=0;iimageLoader.DisplayImage(imageurl, imageview);
public void DisplayImage(String url, ImageView imageView) //url and imageview as parameters
{
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);   //get image from cache using url as key
if(bitmap!=null)         //if image exists
    imageView.setImageBitmap(bitmap);  //dispaly iamge
 else   //downlaod image and dispaly. add to cache.
 {
    queuePhoto(url, imageView);
    imageView.setImageResource(stub_id);
 }
 }
 File cacheDir = StorageUtils.getOwnCacheDirectory(activity context, "your folder");//for caching

// Get singletone instance of ImageLoader
imageLoader = ImageLoader.getInstance();
// Create configuration for ImageLoader (all options are optional)
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(a)
// You can pass your own memory cache implementation
.discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache implementation
.discCacheFileNameGenerator(new HashCodeFileNameGenerator())
.enableLogging()
.build();
// Initialize ImageLoader with created configuration. Do it once.
 imageLoader.init(config);
 options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_id)//display stub image untik image is loaded
.cacheInMemory()
.cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(20))
.build();
 ImageView image=(ImageView)vi.findViewById(R.id.imageview); 
 imageLoader.displayImage(imageurl, image,options);//provide imageurl, imageview and options.