将IMAGE从JSON URL加载到listview中

时间:2012-12-04 07:38:06

标签: android json bitmap android-listview

我正在尝试从URL获取图像,然后将其添加到列表视图中。我可以成功获取图像,但我正在努力将其添加到列表视图中。

我试过这种方式:

    ListView lv = (ListView) findViewById(R.id.list);

    try {

        URL url = new URL("http://devcms.barcodo.com/Images/ProductImages/ThumbnailImages100/EG-BIRT-ST-JA_th.jpg");
        HttpGet httpRequest = null;
        httpRequest = new HttpGet(url.toURI());
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
        HttpEntity entity = response.getEntity();
        BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
        InputStream input = b_entity.getContent();
        Bitmap bitmap = BitmapFactory.decodeStream(input); 

        HashMap<String, Object> docList = new HashMap<String, Object>();
        docList.put("IMAGE", bitmap);

        ArrayList<HashMap<String, Object>> al = new ArrayList<HashMap<String, Object>>();
        al.add(docList);

        simpleAdapter = new SimpleAdapter(this, al, R.layout.list_item,new String[] { "IMAGE" }, new int[] { R.id.image});
        lv.setAdapter(simpleAdapter);

注意:我可以将它放入ImageView,但想要获取列表视图。

4 个答案:

答案 0 :(得分:3)

尝试以下方法:

         public class ImageURL extends ListActivity{
        @Override
     public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    try {

        URL url = new URL(
                "http://devcms.barcodo.com/Images/ProductImages/ThumbnailImages100/EG-BIRT-ST-JA_th.jpg");
        HttpGet httpRequest = null;

        httpRequest = new HttpGet(url.toURI());

        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = (HttpResponse) httpclient
                .execute(httpRequest);

        HttpEntity entity = response.getEntity();
        BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
        InputStream input = b_entity.getContent();

        bitmap = BitmapFactory.decodeStream(input);

    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    } catch (MalformedURLException e) {
        Log.e("log", "bad url");
    } catch (IOException e) {
        Log.e("log", "io error");
    }
    setListAdapter(new StudentListAdapter(this));
}

private class StudentListAdapter extends BaseAdapter {
    private Context mContext;
    private String[] mStudents = { "DurgaPrasad", "Raghu", "Vivek",
            "Satish", "Naga Jyothi", "Vardhika", "Nikhil" };
    private String[] mDetailsStudent = { "Details of DurgaPrasad",
            "Details of  Raghu This row is not created using java",
            "Details of Vivek", "Details of Satish",
            "Details of Naga Jyothi", "Details of Vardhika",
            "Details of Nikhil" };

    public StudentListAdapter(Context context) {
        mContext = context;
    }

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

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

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

    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            System.out.println("111111111111 : " + position);
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            /*
             * if (position == 0) {
             * System.out.println("111111111111 : "+position); v =
             * vi.inflate(R.layout.studentdetailsrow, null);
             * System.out.println("111111111111 : "+position); } else
             */
            v = vi.inflate(R.layout.list_item, null);
        }

        ImageView iv = (ImageView) v.findViewById(R.id.icon);
        ImageView iv2 = (ImageView) v.findViewById(R.id.icon2);
        if (position == 0) {
            iv.setImageBitmap(bitmap);
            // iv2.setImageResource(R.drawable.icon);
        } else {
            iv.setImageBitmap(bitmap);
            // iv2.setImageResource(R.drawable.icon);
        }

        TextView tvname = (TextView) v.findViewById(R.id.stuname);
        TextView tvdetail = (TextView) v.findViewById(R.id.studetail);
        tvname.setText(mStudents[position]);
        tvdetail.setText(mDetailsStudent[position]);
        return v;
    }

    };
        }

答案 1 :(得分:1)

试试这个库,完全符合您的需求。 https://github.com/thest1/LazyList

要在列表视图中显示图像,您需要创建一个从BaseAdapter扩展的列表适配器类,并在那里创建每个视图。

答案 2 :(得分:1)

Hello Guys

我一直在寻找粗细,我在使用simpleadapter实现ListView时遇到了一些问题。然后@AYorhan说使用baseadapter并提供了帮助我解决问题的链接。然后@Ramesh给我提供了一个例子,它对我帮助很大。

我想创建自己的列表适配器,使用simpleadapter在listView中显示但是在我使用 BaseAdapter 之后不会获得成功,并且使用JSON URL从服务器获取多个项目。我获得了成功。

我正在为Android中的一些初学者分享这个工作代码链接,他们可以帮助从服务器检索图像并使用baseadpater获取到listview。

问候:::: TechEnd

答案 3 :(得分:0)

将json数据中的图像提取到列表视图列表中选中所有数据移动到第二个活动名称SingleContactActivity

ListView list;

ArrayList<FeeStacture> newsFeedList;
DeliveryListAdapter adapter;

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


    initializeAdress();


    list = (ListView) findViewById(R.id.list);
    adapter = new DeliveryListAdapter();
    list.setAdapter(adapter);
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.rank))
                    .getText().toString();
            String cost = ((TextView) view.findViewById(R.id.country))
                    .getText().toString();
            String description = ((TextView) view.findViewById(R.id.population)).getText().toString();

            ImageView employee_id = ((ImageView) view.findViewById(R.id.imagestar));
           employee_id.buildDrawingCache();
            Bitmap bitmap=employee_id.getDrawingCache();





          Intent in = new Intent(getApplicationContext(),
                    SingleContactActivity.class);
            in.putExtra("name", name);
            in.putExtra("email", cost);
            in.putExtra("phone", description);

            in.putExtra("BitmapImage", bitmap);


            startActivity(in);
        }
    });

}


private void initializeAdress() {
    getNewsFeedListFromServer();

    newsFeedList = new ArrayList<FeeStacture>();
}


private void getNewsFeedListFromServer() {

    Fee_Stacture_WebService servics = new Fee_Stacture_WebService(this);
    servics.startTask();
}

public class DeliveryListAdapter extends BaseAdapter

{

    LayoutInflater minflat;

    public DeliveryListAdapter() {
        minflat = LayoutInflater.from(getApplicationContext());
    }

    @Override
    public int getCount() {
        return newsFeedList.size();
        //return MainActivity.size();
    }

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

    @Override
    public long getItemId(int arg0) {
        return 0;
    }


    @Override
    public View getView(int position, View contentView, ViewGroup arg2) {

        ViewHolder holder;

        if (contentView == null) {
            holder = new ViewHolder();

            contentView = minflat.inflate(R.layout.home_custom_listitem, null);


            holder.rank = (TextView) contentView.findViewById(R.id.rank);
            holder.pop = (TextView) contentView.findViewById(R.id.population);
            holder.country = (TextView) contentView.findViewById(R.id.country);
            holder.image = (ImageView) contentView.findViewById(R.id.imagestar);

            contentView.setTag(holder);

        } else
        {
            holder = (ViewHolder) contentView.getTag();

        }

        FeeStacture newsObj = newsFeedList.get(position);



        holder.rank.setText(newsObj.getRank());
        holder.pop.setText(newsObj.getPop());

       holder.country.setText(newsObj.getCountry());
        new DownloadImageTask(holder.image).execute(newsFeedList.get(position).getItemIconStr());

        return contentView;


    }


    public class ViewHolder {
        // ImageView use;
        TextView rank;
        TextView pop;
        ImageView image;
        TextView address;
        TextView country;
        TextView gender;
        TextView phone;
    }

}

@Override
public void onSuccessfullResponse(Object object) {
    newsFeedList = (ArrayList<FeeStacture>) object;

    adapter.notifyDataSetChanged();

}

@Override
public void onErrorResponse(String error) {
    Toast.makeText(getApplicationContext(), error, Toast.LENGTH_SHORT).show();

}

@Override
public void onNetworkError(String error) {
    Toast.makeText(getApplicationContext(), error, Toast.LENGTH_SHORT).show();

}


@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    //super.onBackPressed();
    new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_menu_zoom)
            .setTitle("Web Service Demo")
            .setMessage("Are you sure you want to quit Web Demo ?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();

                }

            })
            .setNegativeButton("No", null)
            .show();
}



private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        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;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }

}

}