【发布时间】:2014-11-25 03:07:39
【问题描述】:
我正在使用 AsuncTask 从 Web 服务获取 JSON。从 JSON 我得到“标题”和“全文”。 “title”是简单文本,而“fulltext”是 HTML 文本。在这个 HTML 中,我有一些带有图像的文本和 URL。我想在 TextView 中显示整个 HTML。
我的代码:
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 上进行此操作,但我不知道如何拆分代码。
【问题讨论】:
-
你应该使用图像跨度来显示图像(在此之前你还需要下载图像)
-
我认为使用 picasa 图像库加载该图像更容易,因为它几乎可以处理您手动需要担心的所有事情......我建议您使用 picasa 图像加载器库
-
@GeorgeThomas 是的。在文本中是整个 html,从那里我想显示所有图像以及文本。
标签: android html json textview