不知何故,我似乎並沒有得到它。 8-} 我有一個活動,我從數據庫請求JSON數據,返回結果包含一個圖片URL。我的應用在Android v2.x上運行良好,但由於偶然發現,在Android 4上出現了奇怪的行爲 - 包括未加載的圖像(這不是我稱之爲兼容性?!)現在我必須修復這個問題,希望修復不會再次破壞Android 2.x系統的功能!NetworkOnMainThreadException加載圖片如何
基本上,活動作品在網絡上的所有無數的例子說明(我刪除了最錯誤檢查等,以修剪下來的代碼主要部分):
new GetProductDetails().execute();
(..)
class GetProductDetails extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
(..)
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
getString(R.string.urlProductDetails), "GET",
params);
try {
JSONArray prodObj = json.getJSONArray(Consts.PRODS);
pinfo = prodObj.getJSONObject(0);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Storing each json item in variable
try {
String s = "";
txtvname = (TextView) findViewById(R.id.txtpname);
txtshortinfo = (TextView) findViewById(R.id.txtshortinfo);
(… populating activity window with json data …)
}
});
// update image:
String imgURL;
try {
imgURL = pinfo.getString("pic_url");
if (imgURL.length() > 1) {
imgURL = getString(R.string.urlPicsFull) + imgURL;
ImageView imgProd = (ImageView) findViewById(R.id.imgProduct);
Drawable drawable = LoadImageFromWebOperations(imgURL);
imgProd.setImageDrawable(drawable);
}
} catch (JSONException e) {
e.printStackTrace();
}
pDialog.dismiss();
}
private Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
System.out.println("Could not load " + url + ", Exc=" + e);
return null;
}
}
現在,有一個加載圖像時出現android.os.NetworkOnMainThreadException。