图像显示为gridview

时间:2012-06-04 05:09:38

标签: android image url gridview

我想使用imageurl显示来自mysql服务器的图像(在localhost中测试),我在我的服务器上的filder中有图像,在android客户端应用程序中作为gridview以及text.how我在我的代码中使用imageurl吗? mymainmenu.java

public class MainMenu extends Activity {



    GridView gridView;

    static final String[] MOBILE_OS = new String[] { 
        "Android", "iOS","Windows", "Blackberry" };

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainmenu_list);


        gridView = (GridView) findViewById(R.id.gridView1);

        gridView.setAdapter(new ImageAdapter(this, MOBILE_OS));

        gridView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {
                Toast.makeText(
                   getApplicationContext(),
                   ((TextView) v.findViewById(R.id.grid_item_label))
                   .getText(), Toast.LENGTH_SHORT).show();

            }
        });

    }

}

我的imageadapter.java:

public class ImageAdapter extends BaseAdapter {
private Context context;
private final String[] mobileValues;
    public ImageAdapter(Context context, String[] mobileValues) {
    this.context = context;
    this.mobileValues = mobileValues;
}

public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View gridView;

    if (convertView == null) {

        gridView = new View(context);

        // get layout from list.xml
        gridView = inflater.inflate(R.layout.list, null);

        // set value into textview
        TextView textView = (TextView) gridView
                .findViewById(R.id.grid_item_label);
        textView.setText(mobileValues[position]);

        // set image based on selected text
        ImageView imageView = (ImageView) gridView
                .findViewById(R.id.grid_item_image);

        String mobile = mobileValues[position];

        if (mobile.equals("Windows")) {
            imageView.setImageResource(R.drawable.imggrid);
        } else if (mobile.equals("iOS")) {
            imageView.setImageResource(R.drawable.imggrid);
        } else if (mobile.equals("Blackberry")) {
            imageView.setImageResource(R.drawable.imggrid);
        } else {
            imageView.setImageResource(R.drawable.imggrid);
        }

    } else {
        gridView = (View) convertView;
    }

    return gridView;
}

@Override
public int getCount() {
    return mobileValues.length;
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

}

我不知道如何在我的代码中使用以下内容:

try {
            URL url = new URL(imageFileURL);
            URLConnection conn = url.openConnection();                   
            HttpURLConnection httpConn = (HttpURLConnection)conn;
            httpConn.setRequestMethod("GET");
            httpConn.connect();               
            if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
             InputStream inputStream = httpConn.getInputStream();                     
             Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
             inputStream.close();
             img.setImageBitmap(bitmap);
            }
           } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
           } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
           }

3 个答案:

答案 0 :(得分:1)

将图像下载代码放在AsyncTask中。 Here is the explanation。 在你的getView方法中执行一个asynctask实例,即每次都获取一个图像。

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
 ImageView mImageView;
 public void setImageView(ImageView img) {
      mImageView = img;
 }

 protected Bitmap doInBackground(String... urls) {
     return loadImageFromNetwork(urls[0]);
 }

 protected void onPostExecute(Bitmap result) {
     mImageView.setImageBitmap(result);
 }

}

在执行task.setImageView(yourImageViewinGrid)之前致电AsyncTask,让其知道下载后设置图片的位置。

答案 1 :(得分:0)

  

我不知道如何在我的代码中使用以下内容:

该代码将为您下载图像,您可以将AsyncTaskThread放在单独的线程中,并将下载的图像设置在图像视图中......简单。网上有很多例子你可以谷歌出来

<强> EIDTED

下载图片的代码

public class AsyncFetchImage extends AsyncTask<String, Void, Bitmap>{

    private WeakReference<ImageView> imageReference;
//  private WeakReference<Dialog> dialogReferance;

    public AsyncFetchImage(ImageView imageview) {
        imageReference = new WeakReference<ImageView>(imageview);
//      dialogReferance = new WeakReference<Dialog>(dialog);
    }

    @Override
    protected Bitmap doInBackground(String... s) {

        return downloadImage(s[0]);
    }

    private Bitmap downloadImage(String url) {

        final AndroidHttpClient client = AndroidHttpClient.newInstance("Nixit");
        final HttpGet getRequest = new HttpGet(url);
        try {

            HttpResponse response = client.execute(getRequest);
            final int statusCode = response.getStatusLine().getStatusCode();

            if(statusCode != HttpStatus.SC_OK){
                Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url); 
                return null;
            }
            final HttpEntity entity = response.getEntity();
            if(entity != null){
                InputStream is = null;
                try{
                    is = entity.getContent();
                    final Bitmap bit = BitmapFactory.decodeStream(is);
                    return bit;
                }finally{
                    if(is != null)
                        is.close();
                    entity.consumeContent();
                }
            }


        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally{
            if(client != null){
                client.close();
            }
        }
        Log.i("Image Fetch","Image Fetch Complete");
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        if(isCancelled()){
            result = null;
        }
        if(imageReference != null){
            ImageView imageView = imageReference.get();
//          Dialog di = dialogReferance.get();
            if (imageView != null) {
                imageView.setImageBitmap(result);
//                di.show();
            }

        }
    }


}

使用方法: -

imageView = (ImageView)dialog.findViewById(R.id.imageView1);

AsyncFetchImage fetchImage = new AsyncFetchImage(imageView);
fetchImage.execute(url);

您可以在适配器的getview方法中使用它

希望有帮助

答案 2 :(得分:0)

要获取图像,您必须执行以下操作:

URL new_url = new URL("your url"); 
Bitmap image_bitmap = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream()); ImageView image_view = new ImageView(this);
image_view.setImageBitmap(image_bitmap);

无论如何,最好将图像下载为后台任务。我实际上做的是创建一个自定义视图,其中包含一个私有内部类,它扩展了AsyncTask以便为您下载图像。