Android中URL的图像加载问题

时间:2013-05-01 07:22:44

标签: android image web-services

我正在尝试从网址加载图片,在Android 2.2中图像加载但不在Android 4.0 ICS中。它背后的问题是什么?还有其他方法可以做到这一点。

我的代码是

public class Photos extends Activity {

public static final String TAG_IMAGE_NAME = "image_name";
public static final String TAG_IMAGE_THUMB_NAME = "image_thumb_name";
public static String URL = "http://......./...../....../mainAPI.php";

ArrayList<HashMap<String, String>> photoList;
String responseData = null;
static GridView gridView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.photos);
    gridView = (GridView)findViewById(R.id.gridView);
    photoList = new ArrayList<HashMap<String,String>>();
    new AsyncData().execute();


}

class AsyncData extends AsyncTask<String, Void, Void> {
    ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(Photos.this);
        pDialog.setTitle("Loading....");
        pDialog.setMessage("Please wait...");
        pDialog.show();
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(String... args) {
        // TODO Auto-generated method stub
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(URL);
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("rquest","{\"method\":\"photogallery\",\"body\":[{}]}"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();
            responseData = EntityUtils.toString(resEntity);
            try {
                JSONArray data = new JSONArray(responseData);
                for (int i = 0; i < data.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    JSONObject c = data.getJSONObject(i);
                    String photoName = c.getString(TAG_IMAGE_NAME);
                    String imageThumbName = c.getString(TAG_IMAGE_THUMB_NAME);
                    map.put(TAG_IMAGE_NAME, photoName);
                    map.put(TAG_IMAGE_THUMB_NAME, imageThumbName);
                    photoList.add(map);
                }
            } catch (JSONException e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        ImageAdapter adapter = new ImageAdapter(Photos.this, R.layout.photo_row, photoList);
        gridView.setAdapter(adapter);
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }
    }
}

ImageAdapter Class。

public class ImageAdapter extends ArrayAdapter<HashMap<String, String>>{
Context context;
ArrayList<HashMap<String, String>> myList;
HashMap<String, String> myData;
int layout;
public ImageAdapter(Context context, int textViewResourceId, List<HashMap<String, String>> objects) {
    super(context, textViewResourceId, objects);
    // TODO Auto-generated constructor stub
    this.context = context;
    this.myList = (ArrayList<HashMap<String, String>>) objects;
    this.layout = textViewResourceId;
}

@Override
 public View getView(int position, View convertView, ViewGroup parent)  {
    // TODO Auto-generated method stub
    View row = null;
    ImageView image = null;
    Bitmap bimage;
    LayoutInflater inflater = ((Activity) context).getLayoutInflater();
    row = inflater.inflate(layout, parent, false);
    myData = myList.get(position);
    try{
        image = (ImageView)row.findViewById(R.id.imagePhoto);
        String uri = ("" + myData.get(Photos.TAG_IMAGE_THUMB_NAME)).replace(" ", "%20");
        System.out.println(uri);
        bimage =  getBitmapFromURL(uri);
        image.setImageBitmap(bimage);
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    return row;
}
public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
  }
}

请给我一些解决方案。

1 个答案:

答案 0 :(得分:0)

您无法从Android 3.x开始在UI线程中执行网络操作。在LogCat中,您应该看到错误NetworkOnMainThreadException。 http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

在你的情况下,它是getBitmapFromURL方法,它是从getView调用的。你应该使用AsyncTask或一些线程