无法在imageview中显示来自网址的图片

时间:2014-10-08 20:35:41

标签: android json url imageview

我正在尝试从url中获取immage并将其设置为imageview 图像尺寸小,我使用asynctask。 这是主要的活动代码。 我尝试过差异网站的多个代码,但似乎没有任何效果。 plz不建议volly库。

package com.example.jsonimage;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.widget.ImageView;

public class MainActivity extends Activity {

    Thread t;
    Bitmap bitmap;
    ImageView iv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        iv=(ImageView)findViewById(R.id.imageView1);

        //runthread();

    }

    @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, menu);
        return true;
    }



    public class loadimage extends AsyncTask<Void, Void, Void>{

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            URL url;
            try {
                url = new URL("http://wptrafficanalyzer.in//p//demo1//india.png");

                InputStream is=url.openStream();

                 bitmap= BitmapFactory.decodeStream(is);

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //HttpURLConnection huc =(HttpURLConnection)url.openConnection();
            //huc.connect();
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



            return null;
        }


        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            iv.setImageBitmap(bitmap);
        }

    }



}

1 个答案:

答案 0 :(得分:2)

您没有调用异步任务。在您的MainActivity上尝试:

new loadimage().execute();

如果您的网站无效,您还可以使用此功能从网址获取位图:

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;
    }
}