【问题标题】:Loading IMAGE from JSON URL into listview将图像从 JSON URL 加载到列表视图中
【发布时间】:2012-12-04 07:38:06
【问题描述】:

我正在尝试从 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 中,但想提取到列表视图中。

【问题讨论】:

  • 您是否收到错误消息?我认为该实现仅适用于将文本应用于文本视图。您的适配器可能认为您的图像是文本。您可能需要制作一个自定义适配器。
  • @mango 我不会得到任何错误。我可以在 Imageview 中获取图像,但不能在 listview 中获取。是吗?

标签: android json bitmap android-listview


【解决方案1】:

尝试以下方法:

         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;
    }

    };
        }

【讨论】:

  • 如果我们有一组图像 url,我们如何在 listview 上显示它们?
【解决方案2】:

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

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

【讨论】:

  • 非常感谢您提供的链接。它帮助我理解了这个概念
【解决方案3】:

Hello Guys

我一直在搜索,但在使用 simpleadapter 实现 ListView 时遇到了一些问题。然后@AYorhan 说要使用 baseadapter 并提供了帮助我解决问题的链接。然后@Ramesh 为我提供了一个对我也很有帮助的例子。

我想使用 simpleadapter 创建我自己的列表适配器以显示在列表视图中,但在使用 BaseAdapter 之后没有成功,使用 JSON URL 从服务器获取多个项目。我成功了。

我正在为一些 android 初学者分享这个工作代码链接,他们可能会得到帮助,从服务器检索图像并使用 baseadpater 提取到列表视图中。

问候 :::: TechEnd

【讨论】:

    【解决方案4】:

    从 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);
        }
    
    }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-05
      • 2016-01-11
      • 1970-01-01
      • 2011-04-07
      • 2018-01-10
      • 1970-01-01
      • 2012-07-19
      • 1970-01-01
      相关资源
      最近更新 更多