如何在HashMap中将url转换为图像?

时间:2014-11-27 11:40:02

标签: php android json hashmap imageview

这是我的Json编码代码我想要的是我想在Android中显示图像和标题但我无法显示图像 < / strong>

    {"lists":
    [{"post_title":"kigs",
    "post_img":"post_img":"http://truzzinfotech.com/wp-content/uploads/2014/04/19-150x150.jpg"},  

    {"post_title":"Lacolline",
    "post_img":"http://truzzinfotech.com/wp-content/uploads/2014/04/19-150x150.jpg"},

    {"post_title":"Cricket",
    "post_img":"http://truzzinfotech.com/wp-content/uploads/2014/047-150x150.jpg"},      
    ],
    "success":1}  

这是我获取图像和标题的安卓代码

public class Portfolio扩展了ListActivity {

// Progress Dialog


private ProgressDialog pDialog;


ImageView image;  




// Creating JSON Parser object
        JSONParser jParser = new JSONParser();  

        ArrayList<HashMap<String, String>> portfoliosList;

        // url to get all products list
        private static String url_all_portfolios = "http://truzzinfotech.com/wp-content/themes/truzz/getPortfolio.php";

        // JSON Node names
        private static final String TAG_SUCCESS = "success";
        private static final String TAG_PORTFOLIOS = "lists";
        static final String TAG_TITLE = "post_title";   
        static final String TAG_IMAGE = "post_img";

        // products JSONArray
        JSONArray lists = null;

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.portfolio);

              //ListView lv = getListView(); 

            // Hashmap for ListView
            portfoliosList = new ArrayList<HashMap<String, String>>();

            // Loading products in Background Thread
            new LoadAllPortfolios().execute();


            image = (ImageView)findViewById(R.id.portImg);
        }


        /**
         * Background Sync Task to Load all product by making HTTP Request
         * */
        class LoadAllPortfolios extends AsyncTask<String, String, String> {

            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override  
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(Portfolio.this);
                pDialog.setMessage("Loading portfolio. Please wait...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(false);
                pDialog.show();
                //Toast.makeText(getBaseContext(), "Enter in loading" ,Toast.LENGTH_LONG).show();
            }

            /**
             * getting All products from url
             * */
            protected String doInBackground(String... args) {  
                // Building Parameters
                //Toast.makeText(getBaseContext(), "Enter in doInBackground" ,Toast.LENGTH_LONG).show();
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                // getting JSON string from URL

                 JSONObject json = jParser.makeHttpRequest(url_all_portfolios,"GET", params);


                 Log.d("All Products: ", json.toString());

                try {

                    //lists = new JSONArray(TAG_PORTFOLIOS);
                        int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {

                        // portfolios found
                        // Getting Array of portfolios

                        lists = json.getJSONArray(TAG_PORTFOLIOS);
                        // c = null;

                        // looping through All Products
                        for (int i = 0; i < lists.length(); i++) {
                            JSONObject c = lists.getJSONObject(i);


                            String title = c.getString(TAG_TITLE);
                            String image = c.getString(TAG_IMAGE);

                            Log.d("Item name: ",title);
                            HashMap<String, String> map = new HashMap<String, String>();

                            URL url = new URL(image);
                            HttpURLConnection con = (HttpURLConnection) url.openConnection();
                            con.setDoInput(true);  
                            con.connect();
                            InputStream input = con.getInputStream();
                            Bitmap bitmap = BitmapFactory.decodeStream(input);

                            //InputStream in = new URL(TAG_IMAGE).openStream();
                            //bmp = BitmapFactory.decodeStream(in);
                            map.put(TAG_TITLE, title);
                            map.put(TAG_IMAGE, image);
                            //map.put("image", jsonobject.getString("image"));


                            portfoliosList.add(map);
                        }
                    } else {
                        // no products found  
                        // Launch Add New product Activity
                        Toast.makeText(getBaseContext(), "No Portfolio Found" ,Toast.LENGTH_LONG).show();
                    }

                } catch (JSONException e) {  
                    // TODO Auto-generated catch block
                    Toast.makeText(getBaseContext(), "No Data Found" ,Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block  
                    e.printStackTrace();
                }

                return null;
            }

            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog after getting all products
                pDialog.dismiss();
                // updating UI from Background Thread
                runOnUiThread(new Runnable() {
                    public void run() {  
                        /**
                         * Updating parsed JSON data into ListView
                         * */
                        ListAdapter adapter = new SimpleAdapter(
                                Portfolio.this, portfoliosList,
                                R.layout.list_item, new String[] { TAG_TITLE,TAG_IMAGE },
                                new int[] {R.id.name, R.id.portImg});
                        // updating listview  
                        setListAdapter(adapter);
                    }
                });

            }

        }
}

2 个答案:

答案 0 :(得分:1)

你可以通过谷歌使用排球库来完成网络中必须处理的大部分脏东西

com.android.volley.toolbox.NetworkImageView
        android:id="@+id/networkImageView"
        android:layout_width="150dp"
        android:layout_height="170dp"
        android:layout_centerHorizontal="true" />

NetworkImageView如果您的图像视图是列表视图的一部分,它可以很好地管理它

ImageLoader mImageLoader;
NetworkImageView mNetworkImageView;
private static final String IMAGE_URL =
    "http://developer.android.com/images/training/system-ui.png";
...

// Get the NetworkImageView that will display the image.
mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView);

// Get the ImageLoader through your singleton class.
// mImagaLoader is actually the request Queue of the manages all the caching 
// and requesting image from the network in not present in cache
mImageLoader = MySingleton.getInstance(this).getImageLoader();

// Set the URL of the image that should be loaded into this view, and
// specify the ImageLoader that will be used to make the request.
mNetworkImageView.setImageUrl(IMAGE_URL, mImageLoader);

参考: https://developer.android.com/training/volley/request.html

mImageLoader参考:https://developer.android.com/training/volley/requestqueue.html#singleton 如何设置单例类以及为什么

答案 1 :(得分:0)

尝试这样,

JSONArray data = yourjson.getJSONArray("lists");

ArrayList<String> imgurls = new ArrayList<String>();

for(int i = 0; i < data.length(); i++){
   imgUrls.add(data.getJSONObject(i).getString("post_img"))
}

用于在imageview visit here

中显示图片