[問題] ImageView顯示網路圖片的方法?
不好意思 原PO以前只有碰過網頁類型的程式語言
對於java跟android是個初學者
以下如有語意或誤解部分,請多包涵~順便告知哪邊誤解了~ORZ
-------進入正題----------
搭上順風車,最近也買了幾本Android書來自學
不過碰到了幾個問題,手邊的書都是以資源類別R方式教學
相關圖片等檔案或內容都是直接先行放置於專案中
少了Android對於存取網路資源的部分
最近想實作抓取HTML,之後抽出img與內容,處理後顯示於android上
在測試ImageView去顯示網路上的圖片時
收尋了網路上的教學,並實作出如下,用2.3.3跑也都正確顯示無誤
但用usb除錯模式丟給4.0.4(API15)手機
APK安裝後開啟就直接掛了,停止執行
Virtual用4.0執行也是相同結果
不知哪邊對於在4.0以上執行出現問題
拜託版上先進解惑~感恩
程式碼如下
--------------layout的介面佈局---------------
<ImageView
android:id="@+id/im01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
---------------------------------------------
--------------src的Actibity.java-----------
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends Activity {
String imageUrl01 = "http://ppt.cc/cut/ppt_logo.png";
//網路圖片路徑存入字串
// private ImageButton myfa;
Bitmap bmImg;
ImageView im01;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//介面R中取得
// myfa = (ImageButton)findViewById(R.id.myfa);
im01 = (ImageView)findViewById(R.id.im01);
im01.setImageBitmap(returnBitMap(imageUrl01));
}
public Bitmap returnBitMap(String url) {
URL myFileUrl = null;
Bitmap bitmap = null;
try {
myFileUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
------------AndroidManifest.xml add----------
<uses-permission android:name="android.permission.INTERNET"/>
---------------------------------------------
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.167.61.172
推
05/20 13:42, , 1F
05/20 13:42, 1F
→
05/20 13:42, , 2F
05/20 13:42, 2F
推
05/20 14:02, , 3F
05/20 14:02, 3F
推
05/20 22:06, , 4F
05/20 22:06, 4F
推
05/20 22:38, , 5F
05/20 22:38, 5F
→
05/20 22:57, , 6F
05/20 22:57, 6F
→
05/20 23:14, , 7F
05/20 23:14, 7F
→
05/20 23:18, , 8F
05/20 23:18, 8F
→
05/20 23:30, , 9F
05/20 23:30, 9F
→
05/20 23:32, , 10F
05/20 23:32, 10F
→
05/20 23:33, , 11F
05/20 23:33, 11F
推
05/21 01:53, , 12F
05/21 01:53, 12F
推
05/21 09:42, , 13F
05/21 09:42, 13F
推
05/21 22:21, , 14F
05/21 22:21, 14F
→
05/27 21:09, , 15F
05/27 21:09, 15F
→
05/28 22:43, , 16F
05/28 22:43, 16F