拥有json对象,其值来自<img>
,<src>
,<p>
等标签的组合。
想要获取该值并使用Html.from()
方式放入文本视图。
public class MainActivity extends AppCompatActivity {
ProgressDialog pDialog;
public String html;
public String sag;
private final String url = "http://memaraneha.ir/%db%8c%da%a9%d9%be%d8%a7%d8%b1%da%86%da%af%db%8c-%d9%87%d9%85%d8%a7%d9%87%d9%86%da%af%db%8c-%d8%b7%d8%b1%d8%a7%d8%ad%db%8c-%d8%af%d8%a7%d8%ae%d9%84%db%8c";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView htmlTextView = (TextView)findViewById(R.id.html_text);
htmlTextView.setText(Html.fromHtml(sag, null, null));
new GetContacts().execute();
}
public class GetContacts extends AsyncTask<Void, Void, Void> {
private String TAG = "erfan";
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject c = jsonObj.getJSONObject("posts");
html = String.valueOf(c.getJSONObject("content"));
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
sag=html;
}
}
}
但从此行获取null异常:
htmlTextView.setText(Html.fromHtml(sag, null, null));
如果有人可以请求帮助
答案 0 :(得分:1)
由于设置到文本视图中的“sag”值,因此您获得了空指针 你可以简单地使你的textView全局
public TextView htmlTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView htmlTextView = (TextView)findViewById(R.id.html_text);
new GetContacts().execute();
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
htmlTextView.setText(Html.from(html,arg,arg));
}
答案 1 :(得分:0)
最后解决了我的问题,将backgorund html = String.valueOf(c.getJSONObject("content"));
中的这一行更改为html= c.getString("content");