0
我正在使用AsuncTask從Web服務獲取JSON。從JSON我得到「標題」和「全文」。 「標題」是簡單的文本,但「全文」是HTML文本。在這個HTML中,我有一些文字和網址與圖像。我想在TextView中顯示整個HTML。顯示從HTML到TextView的圖像 - Android
我的代碼:
TextView tvArticleTitle = (TextView) findViewById(R.id.tvArticleTitle);
TextView tvArticleText = (TextView) findViewById(R.id.tvArticleText);
public class GetArticleTask extends AsyncTask<String, Void, Boolean> {
private String title;
private String text;
private ProgressDialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setMessage("Please wait!");
dialog.setCancelable(false);
dialog.show();
}
@Override
protected Boolean doInBackground(String... params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Variables.URL_ARTICLE);
httpPost.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String data = EntityUtils.toString(httpEntity);
int status = httpResponse.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK) {
JSONObject jRealObject = new JSONObject(data);
title = jRealObject.getString("title").toString();
text = jRealObject.getString("fulltext").toString();
return true;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result == false) {
Toast.makeText(context, Variables.ERROR_MESSAGE, Toast.LENGTH_SHORT).show();
} else {
tvArticleTitle.setText(title);
tvArticleText.setText(Html.fromHtml(text, new ImageGetter() {
@Override
public Drawable getDrawable(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;
}
}, null));
if(dialog.isShowing()) {
dialog.dismiss();
}
}
}
}
}
它給我的錯誤:android.os.NetworkOnMainThreadException。我知道我需要再次在AsyncTask上做這件事,但我不知道如何分割代碼。
你應該使用圖像跨度來顯示圖像(在這之前,你需要下載圖像太) – MHP 2014-09-30 13:10:39
我認爲使用picasa圖像庫更容易加載該映像,因爲它幾乎可以處理您製作的所有內容盟友需要擔心abou ..我建議你去picasa圖像加載器庫 – 2014-09-30 13:12:03
@GeorgeThomas是啊。在文本是整個HTML,從那裏我想顯示所有圖像,也是文字。 – KiKo 2014-09-30 13:15:31