从谷歌下载图像

时间:2014-08-05 18:13:28

标签: java android eclipse

我要做的就是从URL下载图像并显示它,但它总是显示Toast消息。如有任何帮助,请提前感谢。

以下是我目前的代码:

public class CopyOfMainGoogle extends Activity {

    @Override
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.copygoogleactivity);
         new DownloadImageTask((ImageView)       findViewById(R.id.imageView1)).execute("https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRyIxW1ckzzIsvhUX3SCQTlPWVX2MlIBE8rvTIzgMaPeHkjT778hSM9hfn2");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_google, menu);
        return true;
    }

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
            Log.i("debug","reached here");
        }

        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();
                runOnUiThread(new Runnable() {
                        public void run() {
                                Toast.makeText(CopyOfMainGoogle.this, R.string.Toast, Toast.LENGTH_SHORT).show();
                            }
                         });

            }
            return mIcon11;
         }

        protected void onPostExecute(Bitmap result) {
             bmImage.setImageBitmap(result);
            findViewById(R.id.progressBar1).setVisibility(View.GONE);
        }
      }
}

1 个答案:

答案 0 :(得分:0)

如果您还没有添加

<uses-permission android:name="android.permission.INTERNET" />

AndroidManifest.xml,请添加它,看看它是否已解决。

此外,这并不重要,但如果您想尝试使用

 new java.net.URL(urldisplay).openConnection().getInputStream();

而不是仅仅使用new java.net.URL(urldisplay).openStream();