如何从url获取图像并使用hashmap在listview上设置它?

时间:2014-10-30 09:00:59

标签: android json web-services

我有Listview用于显示JSON数据。我获得了pdf标题但我无法使用JSON webservices获得pdf标题图像。在日志中,整个数据显示在arraylist中。我使用hashmap概念在Listview上设置JSON数据。以下是我的源代码。

  //    Default url
        private static String url = "http://.....";

    //  JSON Node names
        public static final String TAG_DOCUMENT = "docs";
        public static final String TAG_TITLE = "name";
        public static final String TAG_IMAGEPATH = "imagepath";
        ArrayList<HashMap<String, String>> documentList = new ArrayList<HashMap<String,String>>();

        Button mPdf_list_btn_more;
        ListView lv;
        JSONArray document = null;
        ProgressDialog pDialog;
        // flag for Internet connection status
        Boolean isInternetPresent = false;
        ConnectionDetector cd;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // Remove Titlebar
            this.requestWindowFeature(Window.FEATURE_NO_TITLE);

            // Remove Notificationbar
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
            setContentView(R.layout.pdf_list);

            if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }

            mPdf_list_btn_more = (Button)findViewById(R.id.mPdf_list_btn_more);
            mPdf_list_btn_more.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent i = new Intent(PDF_List.this,Info_Screen.class);
                    startActivity(i);
                }
            });


            lv = (ListView)findViewById(R.id.listView1);
            ServiceHandler sh = new ServiceHandler();
            cd = new ConnectionDetector(getApplicationContext());
    //      new GetPDF().execute();
            new GetPDFNew().execute();


        }

        public void ListViewData() {


        /*  ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    document = jsonObj.getJSONArray(TAG_DOCUMENT);
                 // looping through All Contacts
                    for (int i = 0; i < document.length(); i++) {
                        JSONObject c = document.getJSONObject(i);
                        String name = c.getString(TAG_TITLE);
                        String image_path = c.getString(TAG_IMAGEPATH);

                        Log.i("Name:--->", name);
                        Log.i("Image_Path--->",image_path);

                        // tmp hashmap for single contact
                        HashMap<String, String> doc = new HashMap<String, String>();
                        doc.put(TAG_TITLE,name);
                        doc.put(TAG_IMAGEPATH, image_path);
                        documentList.add(doc);
                        Log.i("ArrayList for documentList ","-->"+ documentList);


                        Log.i("TAG IMAGEPATH IN ListviewData", TAG_IMAGEPATH);
                        Log.i("TAG TITLE IN ListviewData", TAG_TITLE);
                        String[] from = {TAG_IMAGEPATH,TAG_TITLE};
                        final int[] to = {R.id.mImageview_pdf,R.id.mtextview_title};
                        SimpleAdapter adapter = new SimpleAdapter(PDF_List.this, documentList, R.layout.list_item, from, to);
                        lv.setAdapter(adapter);
                    }

                }
                catch(JSONException e){

                }
            }

            else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }*/


            Log.i("TAG IMAGEPATH IN ListviewData", TAG_IMAGEPATH);
            Log.i("TAG TITLE IN ListviewData", TAG_TITLE);
            String[] from = {TAG_IMAGEPATH,TAG_TITLE};
            final int[] to = {R.id.mImageview_pdf,R.id.mtextview_title};
            SimpleAdapter adapter = new SimpleAdapter(PDF_List.this, documentList, R.layout.list_item, from, to);
            lv.setAdapter(adapter);

            lv.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int position, long arg3) {
                    // TODO Auto-generated method stub

                    Object position1 = lv.getItemAtPosition(position);
                    System.out.println(position1+"-->:item postion");


                    for (HashMap<String, String> map : documentList)
                             for (Entry<String, String> mapEntry : map.entrySet())
                                {
                                String key = mapEntry.getKey();
                                String value = mapEntry.getValue();
    //                          Log.i("arraylist key-->",key);
    //                          Log.i("arraylist value-->",value);
    //                          Log.i("cccc","->>"+documentList.get(position).get(key).valueOf(pathforurl+file_path));       
                                }


                }
            });

        }

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

             @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    // Showing progress dialog
                    pDialog = new ProgressDialog(PDF_List.this);
                    pDialog.setMessage("Please wait...");
                    pDialog.setCancelable(false);
                    pDialog.show();

                    // get Internet status
                   isInternetPresent = cd.isConnectingToInternet();

                   // check for Internet status
                   if (isInternetPresent) {
                       // Internet Connection is Present
                       // make HTTP requests
    //                   showAlertDialog(MainActivity.this, "Internet Connection",
    //                           "You have internet connection", true);
                   } else {
                       // Internet connection is not present
                       // Ask user to connect to Internet
                       showAlertDialog(PDF_List.this, "No Internet Connection",
                               "You don't have internet connection.", false);

                       pDialog.dismiss();
                   }

                }

            @Override
            protected Void doInBackground(Void... arg0) {
                // TODO Auto-generated method stub
                ServiceHandler sh = new ServiceHandler();

               // Making a request to url and getting response
               String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

               Log.d("Response: ", "> " + jsonStr);

               if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                       document = jsonObj.getJSONArray(TAG_DOCUMENT);
                    // looping through All Contacts
                       for (int i = 0; i < document.length(); i++) {
                           JSONObject c = document.getJSONObject(i);
                           String name = c.getString(TAG_TITLE);
                           String image_path = c.getString(TAG_IMAGEPATH);

                           Log.i("Name:--->", name);
                           Log.i("Image_Path--->",image_path);

                           // tmp hashmap for single contact
                           HashMap<String, String> doc = new HashMap<String, String>();
                           doc.put(TAG_TITLE,name);
                           doc.put(TAG_IMAGEPATH, image_path);
                           documentList.add(doc);
                           Log.i("ArrayList for documentList ","-->"+ documentList);
                       }

                }
                catch(JSONException e){

                }
               }

               else {
                   Log.e("ServiceHandler", "Couldn't get any data from the url");
               }
                return null;
            }

              @Override
                protected void onPostExecute(Void result) {
                    super.onPostExecute(result);
                    // Dismiss the progress dialog
                    if (pDialog.isShowing())
                        pDialog.dismiss();
                    /**
                     * Updating parsed JSON data into ListView
                     * */


                  ListViewData();
                }

            }

        private class GetPDFNew extends AsyncTask<String, Void, Bitmap> {

             @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    // Showing progress dialog
                    pDialog = new ProgressDialog(PDF_List.this);
                    pDialog.setMessage("Please wait...");
                    pDialog.setCancelable(false);
                    pDialog.show();

                    // get Internet status
                  isInternetPresent = cd.isConnectingToInternet();

                  // check for Internet status
                  if (isInternetPresent) {
                      // Internet Connection is Present
                      // make HTTP requests
    //                  showAlertDialog(MainActivity.this, "Internet Connection",
    //                          "You have internet connection", true);
                  } else {
                      // Internet connection is not present
                      // Ask user to connect to Internet
                      showAlertDialog(PDF_List.this, "No Internet Connection",
                              "You don't have internet connection.", false);

                      pDialog.dismiss();
                  }

                }



              @Override
                protected void onPostExecute(Bitmap result) {
                    super.onPostExecute(result);
                    // Dismiss the progress dialog
                    if (pDialog.isShowing())
                        pDialog.dismiss();
                    /**
                     * Updating parsed JSON data into ListView
                     * */


                  ListViewData();
                }

            @Override
            protected Bitmap doInBackground(String... params) {
                // TODO Auto-generated method stub
                ServiceHandler sh = new ServiceHandler();

                // Making a request to url and getting response
                String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

                Log.d("Response: ", "> " + jsonStr);
                if (jsonStr != null) {
                    try {
                        JSONObject jsonObj = new JSONObject(jsonStr);

                        // Getting JSON Array node
                           document = jsonObj.getJSONArray(TAG_DOCUMENT);
                        // looping through All Contacts
                           for (int i = 0; i < document.length(); i++) {
                               JSONObject c = document.getJSONObject(i);
                               String name = c.getString(TAG_TITLE);
                               String image_path = c.getString(TAG_IMAGEPATH);

                               Log.i("Name:--->", name);
                               Log.i("Image_Path--->",image_path);

                               // tmp hashmap for single contact
                               HashMap<String, String> doc = new HashMap<String, String>();
                               doc.put(TAG_TITLE,name);
                               doc.put(TAG_IMAGEPATH, image_path);
                               documentList.add(doc);
                               Log.i("ArrayList for documentList ","-->"+ documentList);
                           }


                    }
                    catch(JSONException e){

                    }
                   }
                return null;
            }

            }


        @SuppressWarnings("deprecation")
        public void showAlertDialog(Context context, String title, String message, Boolean status) {
            AlertDialog alertDialog = new AlertDialog.Builder(context).create();

            // Setting Dialog Title
            alertDialog.setTitle(title);

            // Setting Dialog Message
            alertDialog.setMessage(message);

            // Setting alert dialog icon
            alertDialog.setIcon((status) ? R.drawable.ic_launcher : R.drawable.ic_launcher);

            // Setting OK Button
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            });
        }

1 个答案:

答案 0 :(得分:0)

您可以使用名为Picasso

的简单库来实现此目的

最准确的方式,它可以处理所有内容,例如缓存维护,离线渲染以及从网络和磁盘加载图像

<强> 1。大多数情况下,如果在批量图像的情况下无法正确处理,则可能会出现名为bitmap size exceeds vm budget的异常

所以我建议你选择通用图片加载库或Picasso

public static void loadNetworkThumNail(final Context context, final ImageView imageview, final String Url) {
        Picasso.with(context).load(Url.trim()).resize(98, 98).placeholder(R.drawable.default_image).into(imageview);
    }