从服务器获取gridview中的图像

时间:2014-10-30 09:43:10

标签: android image http gridview

我有应用程序,通过地址获取图像" http://xn--e1aybc.xn--76-6kc1ag2ab9l.xn--p1ai/food.png"(例如)来自服务器

public class MenuActivity extends Activity {

private static ArrayList<Products> myProducts;
ParseJSON parseJSON;
private static ArrayList <Bitmap> bm;

final String GetMenuUrl = "http://xn--e1aybc.xn--76-6kc1ag2ab9l.xn--p1ai/get_menu.php";
String City = "Moscow";
String NameCinema = "Avrora";
private ProgressDialog dialog;
private String response;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.menu);
    init();
    new RequestTask().execute(GetMenuUrl);
}


private void init(){

    myProducts = new ArrayList<Products>();
    parseJSON = new ParseJSON();

}


private void setAdapter(ArrayList<Products> products){

    GridView grid;



    for(int i = 0; i < myProducts.size(); i++){

        try {
            bm.add(downloadBitmap("http://xn--e1aybc.xn--76-6kc1ag2ab9l.xn--p1ai/food.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    System.out.println("size == " + bm.size());


    final ImageView imageView = (ImageView) findViewById(R.id.imageView);
    SetImg("http://xn--e1aybc.xn--76-6kc1ag2ab9l.xn--p1ai/food.png",imageView);

    System.out.println("size == " + bm.size());

    CustomGrid adapter = new CustomGrid(MenuActivity.this, products, bm);
    grid=(GridView)findViewById(R.id.grid);
    grid.setAdapter(adapter);
    grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            Toast.makeText(MenuActivity.this, "Продукт " + myProducts.get(position).getProductName() + " добавлен в корзину", Toast.LENGTH_SHORT).show();
        }
    });


}


private void SetImg(final String url,final ImageView v){
    final ProgressDialog dialog = ProgressDialog.show(this, "Download",
            "downloading");
    dialog.show();
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                final Bitmap downloadBitma = downloadBitmap(url);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        v.setImageBitmap(downloadBitma);
                    }
                });

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                dialog.dismiss();
            }
        }
    }).start();
}

private Bitmap downloadBitmap(String url) throws IOException {
    HttpUriRequest request = new HttpGet(url.toString());
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(request);

    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        byte[] bytes = EntityUtils.toByteArray(entity);

        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
                bytes.length);
        return bitmap;
    } else {
        throw new IOException("Download failed, HTTP response code "
                + statusCode + " - " + statusLine.getReasonPhrase());
    }
}


class RequestTask extends AsyncTask<String, String, String> {
    @Override
    protected String doInBackground(String... params) {
        try {

            DefaultHttpClient hc = new DefaultHttpClient();
            ResponseHandler<String> res = new BasicResponseHandler();

            HttpPost postMethod = new HttpPost(params[0]);

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("city", City));

            nameValuePairs.add(new BasicNameValuePair("name_cinema",NameCinema));

            postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            response = hc.execute(postMethod, res);

            parseJSON.parse(response.toString());
            Log.d("response == ", response.toString());
            myProducts = parseJSON.getObjects();

            Log.d("firstProduc == ", myProducts.get(0).getProductName());



        } catch (Exception e) {
            System.out.println("Exp=" + e);
        }
        return null;
    }
    @Override
    protected void onPostExecute(String result) {

        if (dialog != null && dialog.isShowing())
            dialog.dismiss();

        ArrayList<String> products = new ArrayList<String>();
        for(int i = 0 ; i < myProducts.size(); i++){
            products.add(myProducts.get(i).getProductName());
        }
        if(products.size() != 0)
            setAdapter(myProducts);
        else Log.d("error", "can`t load");
        super.onPostExecute(result);
    }
    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(MenuActivity.this);
        dialog.setMessage("Загружаюсь...");
        dialog.setIndeterminate(true);
        dialog.setCancelable(true);
        dialog.show();
        super.onPreExecute();
    }
}
}

//将图像显示到gridview

public class CustomGrid extends BaseAdapter{
private Context mContext;
private final ArrayList<Products> web;

private final ArrayList<Bitmap> Imageid;
public CustomGrid(Context c,ArrayList<Products> web,ArrayList<Bitmap>Imageid  ) {
    mContext = c;
    this.Imageid = Imageid;
    this.web = web;

}
@Override
public int getCount() {
    // TODO Auto-generated method stub
    return web.size();
}
@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}
@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    View grid;
    LayoutInflater inflater = (LayoutInflater) mContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        grid = new View(mContext);
        grid = inflater.inflate(R.layout.rowlayout, null);
        TextView textView = (TextView) grid.findViewById(R.id.grid_text);
        TextView textDescr = (TextView) grid.findViewById(R.id.grid_description);
        final ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image);
        textView.setText(web.get(position).getProductName());
        textDescr.setText(String.valueOf(web.get(position).getProductPrice()) + "руб.");
      //  imageView.setImageResource(Imageid[position]);
        imageView.setImageBitmap(Imageid.get(position));
           } else {
        grid = (View) convertView;
    }
    return grid;
}
}

但我有错误:

10-30 09:27:23.081    2820-2820/com.example.kinofood E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
        at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
        at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
        at java.net.InetAddress.getAllByName(InetAddress.java:214)
        at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
        at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
        at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
        at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
        at com.example.kinofood.MenuActivity.downloadBitmap(MenuActivity.java:162)
        at com.example.kinofood.MenuActivity.setAdapter(MenuActivity.java:79)
        at com.example.kinofood.MenuActivity.access$400(MenuActivity.java:38)
        at com.example.kinofood.MenuActivity$RequestTask.onPostExecute(MenuActivity.java:232)
        at com.example.kinofood.MenuActivity$RequestTask.onPostExecute(MenuActivity.java:186)
        at android.os.AsyncTask.finish(AsyncTask.java:631)
        at android.os.AsyncTask.access$600(AsyncTask.java:177)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5041)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
        at dalvik.system.NativeStart.main(Native Method)

如何更改我的代码?谢谢

1 个答案:

答案 0 :(得分:1)

您无法在MainThread上下载。如果你想这样做,你将不得不异步加载它,即使用AsyncTask。

但是将在线图像加载到ImageViews的最佳方法是使用第三方库。

我知道的图书馆:

通用图片加载器 - https://github.com/nostra13/Android-Universal-Image-Loader

毕加索 - http://square.github.io/picasso/

除了简单地加载图像,它们还可以处理你的缓存,动画,事件处理等。