如何从URL下载图像并在imageview中设置

时间:2014-11-14 12:36:48

标签: android

for (int i = 0; i < productsofitems.length(); i++) 
                    {
                        count=productsofitems.length();
                        System.out.println("count is"+productsofitems.length());
                        JSONObject c = productsofitems.getJSONObject(i);

                        // Storing each json item in variable
                        //String id = c.getString(TAG_CATEGORYID);
                        String procid = c.getString(TAG_PRODUCTID);
                        System.out.println(procid);
                        String id = c.getString(TAG_CATEGORYID);
                        System.out.println(id);
                        String productname = c.getString(TAG_PRODUCTNAME);
                        System.out.println(productname);
                        //String title = c.getString(TAG_TITLE);
                        //System.out.println(title);
                        //String smalldesc = c.getString(TAG_SMALLDESCRIPTION);
                       //System.out.println(smalldesc);
                        //String originalprice = c.getString(TAG_ORIGINALPRICE);
                        //System.out.println(originalprice);
                        String salesprice = c.getString(TAG_SALEPRICE);
                        System.out.println(salesprice);
                        String smallimage = c.getString(TAG_SMALLIMAGE);
                        System.out.println(smallimage);

                        String stocks = c.getString(TAG_STOCK);
                        System.out.println(stocks);


                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_PRODUCTID, procid);
                        map.put(TAG_CATEGORYID, id);
                        map.put(TAG_PRODUCTNAME, productname);
                        //map.put(TAG_TITLE, title);
                        //map.put(TAG_SMALLDESCRIPTION, smalldesc);
                        //map.put(TAG_ORIGINALPRICE, originalprice);
                        map.put(TAG_SALEPRICE, salesprice);
                        map.put(TAG_SMALLIMAGE, smallimage);
                        map.put(TAG_STOCK, stocks);

                        // adding HashList to ArrayList
                        productListofitems.add(map);

                        System.out.println("inside"+count);

                    }

                }
                else {
                     Log.d("ProductListofitems: ", "null");
                    // no products found
                    // Launch Add New product Activity
                    //Intent i = new Intent(getApplicationContext(),
                            //NewProductActivity.class);
                    // Closing all previous activities
                    //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                   // startActivity(i);
                }
            } 
            catch (JSONException e) {
                e.printStackTrace();
            } 

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all category
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    int[] images = {
                            R.drawable.a, R.drawable.banner2,
                            R.drawable.banner4, R.drawable.banner1

                    };
                    ListAdapter adapter = new SimpleAdapter(
                            ProductListofitems.this, productListofitems,
                            R.layout.productlistofitems, new String[] { 
                                    TAG_PRODUCTID,TAG_CATEGORYID,TAG_PRODUCTNAME,TAG_SALEPRICE,TAG_STOCK},
                            new int[] {R.id.product_id,R.id.catgory_id,R.id.title,R.id.saleprice,R.id.stock});
                    // updating listview
                    setListAdapter(adapter);
                    System.out.println("post execute");
                    textview.setText(+count+" results for "+"'"+cat_title+"'");
                }
            });

        }

如何从URL下载图像。我正在获取URL作为响应以及如何在listview的imageview中下载和设置。如何从URL下载图像并在imageview中设置?我附上了这个代码。

5 个答案:

答案 0 :(得分:1)

试试这个:

private class LoadImage extends AsyncTask<String, String, Bitmap> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    protected Bitmap doInBackground(String... args) {
        //1 url
        if(args.length == 1){
            Log.i("doInBack 1","length = 1 ");
            try {
                Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }
    protected void onPostExecute(Bitmap image) {
        if(image != null){
            yourImageView.setBitmap(image);

        }
        }
    }

如何调用此类?

new LoadImage().execute("https://www.yourUrl.com/image.jpg");

答案 1 :(得分:0)

您可以使用this库来下载图片。

要使用,您必须将JAR放在Android项目的libs子文件夹中。

jar in lib Folder

然后只有你必须使用它

MainActivity.java

    public class MainActivity extends Activity {
    ImageLoader imageLoader;  
    ImageView image;
    String imageUrl = "http://developer.android.com/design/media/design_elements_landing.png";

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

        // Create global configuration and initialize ImageLoader with this config
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(MainActivity.this));

        image = (ImageView) findViewById(R.id.image);
        ImageLoader imageLoader = ImageLoader.getInstance();
        imageLoader.displayImage(imageUrl, image);

    }
}

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

最后在Manifest.xml中包含这些行

<uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <!-- Include following permission if you load images from Internet -->
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

答案 2 :(得分:0)

public class ImageViewFromURLActivity extends Activity {

    public static final String URL = 
        "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQm1U-h4oGaUpGTb9K7REF0ogGYprXYA2z7g8LGjS-7HUFooIwSV2qzHH-W";
    ImageView imageView;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        imageView = (ImageView) findViewById(R.id.imageView);

        // Create an object for subclass of AsyncTask
        GetXMLTask task = new GetXMLTask();
        // Execute the task
        task.execute(new String[] { URL });
    }

    private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... urls) {
            Bitmap map = null;
            for (String url : urls) {
                map = downloadImage(url);
            }
            return map;
        }

        // Sets the Bitmap returned by doInBackground
        @Override
        protected void onPostExecute(Bitmap result) {
            imageView.setImageBitmap(result);
        }

        // Creates Bitmap from InputStream and returns it
        private Bitmap downloadImage(String url) {
            Bitmap bitmap = null;
            InputStream stream = null;
            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            bmOptions.inSampleSize = 1;

            try {
                stream = getHttpConnection(url);
                bitmap = BitmapFactory.
                        decodeStream(stream, null, bmOptions);
                stream.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return bitmap;
        }

        // Makes HttpURLConnection and returns InputStream
        private InputStream getHttpConnection(String urlString) throws IOException {
            InputStream stream = null;
            URL url = new URL(urlString);
            URLConnection connection = url.openConnection();

            try {
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                httpConnection.setRequestMethod("GET");
                httpConnection.connect();

                if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    stream = httpConnection.getInputStream();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return stream;
        }
    }
}

答案 3 :(得分:0)

// show The Image

new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
        .execute("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
}

public void onClick(View v) {
startActivity(new Intent(this, IndexActivity.class));
finish();

}

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

答案 4 :(得分:0)

添加picasso jar然后调用它 Picasso.with(this.getContext())                 .load(IMAGEURL)                 .into(ImageView的);