西牛贺州的耍猴老道 2016-04-12 02:21 采纳率: 25%
浏览 2471
已采纳

android imageview加载网络图片无图片

MainActivity.java

 package study_imageput.com.study_apktointent;

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

        import java.io.InputStream;
        import java.net.HttpURLConnection;
        import java.net.URL;

public class MainActivity extends Activity {
    //定义一个图片显示控件
    private ImageView imageView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) this.findViewById(R.id.ivPic);
                String url = "http://images.cnitblog.com/blog/430074/201302/01220037-4e6a57c1199748fea9f8391e7e0548d7.jpg";
                setPicBitmap(imageView, url);

    }

    public static void setPicBitmap(final ImageView ivPic,final String pic_url){

        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    HttpURLConnection conn = (HttpURLConnection) new URL(pic_url).openConnection();
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    Bitmap bitmap =BitmapFactory.decodeStream(is);
                    ivPic.setImageBitmap(bitmap);
                    is.close();
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }
}

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button1"
        android:text="加载图片"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/ivPic"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="#dc0000"/>
</LinearLayout>

AndroidMainfest.xml

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="study_imageput.com.study_apktointent">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

最后显示结果就是白屏,如果之前设置了imageview的默认图片,加载之后就会变成白色

  • 写回答

4条回答 默认 最新

  • 斩月sama 博客专家认证 2016-04-12 02:28
    关注

    你这个得用异步来做吧,我最近写了一个异步获取图片的Demo,主要部分是这么写的:

     public class MainActivity extends Activity implements OnClickListener {
    
        private ImageView iv;
        private Button downloadButton;
        private TextView tv_show;
        private RotatingDoughnut rotatingDoughnut;
        private static final String IMG_PATH = "http://img.my.csdn.net/uploads/201604/06/1459922240_8285.jpg";
        private static final int MSG_SUCCESS = 0;
        private static final int MSG_FAILURE = 1;
        private static final int MSG_START_LOADING = 3;
        private static final int MSG_FINISH_LOADING = 4;
        private DownloadThread downloadThread;
        private Bitmap bitmap = null;
    
        @Override 
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            iv = (ImageView) findViewById(R.id.iv);
            tv_show = (TextView) findViewById(R.id.tv_show);
            rotatingDoughnut = (RotatingDoughnut) findViewById(R.id.progressBar);
            downloadButton = (Button) findViewById(R.id.btn_download);
            downloadButton.setOnClickListener(this);
        } 
    
        private Handler mHandler = new Handler() {
            public void handleMessage(Message msg) { 
    
                switch (msg.what) { 
                    case MSG_SUCCESS: 
                        rotatingDoughnut.setVisibility(View.INVISIBLE); 
                        iv.setImageBitmap(bitmap); 
                        downloadButton.setText("Success"); 
                        downloadButton.setEnabled(false); 
                        break; 
                    case MSG_FAILURE: 
                        Toast.makeText(getApplicationContext(), "获取图片失败", Toast.LENGTH_SHORT).show(); 
                        downloadButton.setText("Failure"); 
                        downloadButton.setEnabled(false); 
                        break; 
                    case MSG_START_LOADING: 
                        rotatingDoughnut.doughnutRotating(); 
                    default: 
                        break; 
                } 
            } 
    
            ; 
    
        }; 
    
    
        private class DownloadThread extends Thread {
            HttpURLConnection coon;
            InputStream inputStream;
    
            @Override 
            public void run() { 
                try { 
                    URL url = new URL(IMG_PATH);
                    if (url != null) {
                        coon = (HttpURLConnection) url.openConnection();
                        coon.setConnectTimeout(2000);
                        coon.setDoInput(true);
                        coon.setRequestMethod("GET");
                        coon.connect();
                        if (coon.getResponseCode() == 200) {
                            inputStream = coon.getInputStream();
                            bitmap = BitmapFactory.decodeStream(inputStream);
                            mHandler.obtainMessage(MSG_SUCCESS).sendToTarget();
                        } else { 
                            mHandler.obtainMessage(MSG_FAILURE).sendToTarget();
                        } 
                    } 
    
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block 
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block 
                    e.printStackTrace();
                } 
                super.run(); 
            } 
    
    
        } 
    
        @Override 
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_download:
                    iv.setImageBitmap(null);
                    downloadThread = new DownloadThread();
                    if (!isConnectingToInternet()) { 
                        Toast.makeText(getApplicationContext(), "未检测到网络", Toast.LENGTH_SHORT).show();
                    } else { 
                        tv_show.setVisibility(View.GONE);
                        rotatingDoughnut.setVisibility(View.VISIBLE);
                        mHandler.obtainMessage(MSG_START_LOADING).sendToTarget();
                        mHandler.postDelayed(new Runnable() {
                            @Override 
                            public void run() { 
                                downloadThread.start();
                            } 
                        }, 2500); 
                    } 
                    break; 
                default: 
                    break; 
            } 
    
        } 
    
        /** 
         * 检测网络状态 
         * 
         * @return 
         */ 
        public boolean isConnectingToInternet() { 
            ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo[] info = connectivity.getAllNetworkInfo();
                if (info != null)
                    for (int i = 0; i < info.length; i++)
                        if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                            return true; 
                        } 
    
            } 
            return false; 
        } 
    
    } 
    

    你参考参考

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 MATLAB APP 制作出现问题
  • ¥15 wannier复现图像时berry曲率极值点与高对称点严重偏移
  • ¥15 利用决策森林为什么会出现这样·的问题(关键词-情感分析)
  • ¥15 DispatcherServlet.noHandlerFound No mapping found for HTTP request with URI[/untitled30_war_e
  • ¥15 使用deepspeed训练,发现想要训练的参数没有梯度
  • ¥15 寻找一块做为智能割草机的驱动板(标签-stm32|关键词-m3)
  • ¥15 信息管理系统的查找和排序
  • ¥15 基于STM32,电机驱动模块为L298N,四路运放电磁传感器,三轮智能小车电磁组电磁循迹(两个电机,一个万向轮),怎么用读取的电磁传感器信号表示小车所在的位置
  • ¥15 如何解决y_true和y_predict数据类型不匹配的问题(相关搜索:机器学习)
  • ¥15 PB中矩阵文本型数据的总计问题。