Android图片下载

时间:2016-03-21 17:54:37

标签: java android image url download

您好,我需要从网址下载图像,然后将该图像保存到我的Android设备,但我遇到从网址获取图像的问题。这是我的代码。请帮助。我附加了我的数据类以及我的主要活动类。

package muneeb.muneeba;

import android.graphics.*;
import java.net.*;
import java.io.*;

public class Picture 
{
   public String url;
   public String description;
   public String category;

   public Picture(String url,String desc,String category){
  this.url = url;
  this.description = desc;
  this.category = category;
   }

   public Bitmap getImage(){

  Bitmap image = null;

  try {
     InputStream in = new URL(url).openStream();
     image = BitmapFactory.decodeStream(in);
  } catch (Exception e) {
     e.printStackTrace();
  }

  return image;
   }
}

package muneeb.muneeba;

import android.app.Activity;
import android.os.Bundle;
import java.net.*;
import java.util.*;
import java.io.*;
import android.widget.*;
import android.view.*;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Xml;

public class WebPics extends Activity
{
ArrayList<Picture> pictures;
int position = 0;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    load();
    show();
}

private void load(){

   String line = "";
   TextView view = (TextView) findViewById(R.id.text);

   try{

      URL url = new URL("https://dl.dropboxusercontent.com/u/47451150/pictures.xml");
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setReadTimeout(10000);
      connection.setConnectTimeout(15000);
      connection.setRequestMethod("GET");
      connection.setDoInput(true);

      connection.connect();

      StringBuilder content = new StringBuilder();
      BufferedReader reader = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );


      while( (line = reader.readLine()) != null ){
         content.append(line);
      }

      line = content.toString();
      parse(line);
   } catch(Exception ex) {
      line = ex.getMessage();
      ex.printStackTrace();
   }

}

private void parse(String xml){

   String category = "";
   pictures = new ArrayList<Picture>();

   try{
      XmlPullParser parser = Xml.newPullParser();
      parser.setInput(new StringReader(xml));

      int event = parser.getEventType();
      while(event != XmlPullParser.END_DOCUMENT){

         if(event == XmlPullParser.START_TAG &&
             parser.getName().equals("category") ) {

            category = parser.getAttributeValue(null,"name");
         }

         if(event == XmlPullParser.START_TAG &&
             parser.getName().equals("im") ){

             String url = parser.getAttributeValue(null,"url");
             String description = parser.getAttributeValue(null,"description");
             pictures.add(new Picture(url,description,category));
         }

         event = parser.next();
      }
   } catch(Exception ex){ }
}

private void show(){
   if(pictures != null){
      Picture picture = pictures.get(position);
      if (picture == null) return;

      ImageView image = (ImageView) findViewById(R.id.image);
      image.setImageBitmap(picture.getImage());

      TextView text = (TextView) findViewById(R.id.text);
      text.setText("Category:" + picture.category + "\n" + picture.description);
   }
}

public void buttonClick(View view){
   if(view.getId() == R.id.previous ){
      position--;
      if (position < 0) position = pictures.size() - 1;
   }

   if(view.getId() == R.id.next )
{
      position = (position + 1) % pictures.size();
   }

   show();
}

}

3 个答案:

答案 0 :(得分:0)

您无法下载图片的原因是因为您在UI线程中进行网络请求无法正常工作。 使用Asynctask或任何其他机制将所有网络请求放在非UI线程中,并在UI线程中更新ImageView。这样您就可以正确下载图片了。 这link可能会对您有所帮助。

  

解决方案 -

private class DownloadWebPageTask extends AsyncTask<Void, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(Void... urls) {
           load();
            if(pictures == null) {
               return null;
            } else{
                Picture picture = pictures.get(position);
                if (picture == null)
                    return null;
                else
                    return picture.getImage();
            }
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if(bitmap == null){
                //Show error
            } else{
                ImageView image = (ImageView) findViewById(R.id.image);
                image.setImageBitmap(bitmap);
            }
        }
    }

添加

new DownloadWebPageTask().execute();

无论你想在哪里下载图片

答案 1 :(得分:0)

package muneeb.muneeba;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import java.net.*;
import java.util.*;
import java.io.*;
import android.widget.*;
import android.view.*;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Xml;

public class WebPics extends Activity {
    ArrayList<Picture> pictures;
    int position = 0;
    Context c;

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

        c = this;
        new DownloadWebPageTask().execute();
    }

    private class DownloadWebPageTask extends AsyncTask<Void, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(Void... urls) {
            load();
            if(pictures == null) {
                return null;
            } else{
                Picture picture = pictures.get(position);
                if (picture == null)
                    return null;
                else
                    return picture.getImage();
            }
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if(bitmap == null){
                //Show error
            } else{
                ImageView image = (ImageView) findViewById(R.id.image);
                image.setImageBitmap(bitmap);
            }
        }
    }
        private void load() {

            String line = "";
            TextView view = (TextView) findViewById(R.id.text);

            try {
                Toast.makeText(c, "hello", Toast.LENGTH_LONG).show();
                URL url = new URL("https://dl.dropboxusercontent.com/u/47451150/pictures.xml");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setReadTimeout(10000);
                connection.setConnectTimeout(15000);
                connection.setRequestMethod("GET");
                connection.setDoInput(true);

                connection.connect();

                StringBuilder content = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));


                while ((line = reader.readLine()) != null) {
                    content.append(line);
                }

                line = content.toString();
                parse(line);
            } catch (Exception ex) {
                line = ex.getMessage();
                ex.printStackTrace();
            }

        }

        private void parse(String xml) {

            String category = "";
            pictures = new ArrayList<Picture>();

            try {
                XmlPullParser parser = Xml.newPullParser();
                parser.setInput(new StringReader(xml));

                int event = parser.getEventType();
                while (event != XmlPullParser.END_DOCUMENT) {

                    if (event == XmlPullParser.START_TAG &&
                            parser.getName().equals("category")) {

                        category = parser.getAttributeValue(null, "name");
                    }

                    if (event == XmlPullParser.START_TAG &&
                            parser.getName().equals("im")) {

                        String url = parser.getAttributeValue(null, "url");
                        Toast.makeText(c, "hello", Toast.LENGTH_LONG).show();
                        String description = parser.getAttributeValue(null, "description");
                        pictures.add(new Picture(url, description, category));
                    }

                    event = parser.next();
                }
            } catch (Exception ex) {
            }
        }

        public void buttonClick(View view) {
            if (view.getId() == R.id.previous) {
                position--;
                if (position < 0) position = pictures.size() - 1;
            }

            if (view.getId() == R.id.next) {
                position = (position + 1) % pictures.size();
            }
            show();
        }
    public void show() {
        if (pictures != null) {
            Picture picture = pictures.get(position);
            if (picture == null) return;

            ImageView image = (ImageView) findViewById(R.id.image);
            image.setImageBitmap(picture.getImage());

            TextView text = (TextView) findViewById(R.id.text);
            text.setText("Category:" + picture.category + "\n" + picture.description);
        }
    }
    }

答案 2 :(得分:0)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="muneeb.muneeba" >

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <uses-permission android:name="android.permission.INTERNET" />
    <activity android:name=".WebPics"
        android:icon="@drawable/ic_launcher"
        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>

</manifest>