2014-10-08 134 views
0

我試圖從url獲取immage並將其設置爲imageview 圖像尺寸很小,我使用asynctask。 這裏是主要的活動代碼。 我已經嘗試了差異網站的多個代碼,但似乎沒有任何工作。 PLZ不建議volly圖書館。無法在imageview中顯示來自url的圖像

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

    } 



} 

回答

2

你是不是調用異步任務。在您的MainActivity嘗試:

new loadimage().execute(); 

您也可以使用此功能來從URL獲取的位圖,如果你不工作:

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

雅剛纔忘了執行的AsyncTask thansk – 2014-10-09 20:23:39