在AsyncTask中,我得到了一些json的一些值作爲圖像。下面是我的JSON如何從AsyncTask中的html加載圖像
{
"text": "some text",
"html1": "Hi, check out my fb profile picture at <img src = 'http:\/\/abc.com/image1.png'\/> ",
"html2": "Hi, check out my whatsapp profile picture at <img src = 'http:\/\/abc.com\/image1.png'\/> ",
.
.
.
}
的樣本中異步任務postExecute方法我有
((TextView) findViewById(R.id.html1)).setText(Html.fromHtml((String) jsonObj.get("html1"), new ImageGetter()
{
@Override
public Drawable getDrawable(String source)
{
return loadImage(source);
}
}, null));
((TextView) findViewById(R.id.html2)).setText(Html.fromHtml((String) jsonObj.get("html2"), new ImageGetter()
{
@Override
public Drawable getDrawable(String source)
{
return loadImage(source);
}
}, null));
和我的LoadImage方法看起來像下面
private Drawable loadImage(String source)
{
Drawable drawable = null;
URL sourceURL;
try
{
sourceURL = new URL(source);
URLConnection urlConnection = sourceURL.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
Bitmap bm = BitmapFactory.decodeStream(bufferedInputStream);
// convert Bitmap to Drawable
drawable = new BitmapDrawable(getResources(), bm);
drawable.setBounds(0, 0, bm.getWidth(), bm.getHeight());
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return drawable;
}
我覺得代碼就足夠了,但我我越來越android.os.NetworkOnMainThreadException
我在manifest.xml中添加Internet權限
可以請你調試的具體行代碼時會崩潰嗎? – ymz 2014-11-24 00:31:37
@ urlConnection.connect(); – 2014-11-24 00:35:44
我不確定,但可能你不應該在onPostExecute方法中使用網絡。 AsyncTask中您可以執行此操作的唯一方法是doInBackground方法。這可能會導致android.os.NetworkOnMainThreadException。 – antonpp 2014-11-24 00:48:59