我正在尝试从GSON中的URL获取数据并将这些值放入TextView中。我正在使用ArrayList
从GSON添加值。以下是处理该问题的AsyncTask<>
代码:
private class getData extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CardViewExpandCollapse.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... voids) {
HttpHandler httpHandler = new HttpHandler();
String s = httpHandler.makeServiceCall(mUrl);
Gson gson = new Gson();
AccountDetail[] accountDetails = gson.fromJson(s, AccountDetail[].class);
ArrayList<AccountDetail> details = new ArrayList<>(Arrays.asList(accountDetails));
HashMap<String, String> accDetails = new HashMap<>();
String address = details.get(0).getRow().getBillToAddress();
Double balance = details.get(0).getRow().getTotalAccountBalance();
Double invoices = details.get(0).getRow().getTotalOpenInvoicesValue();
Log.e(Tag, "Response from URL " + s);
Log.e(Tag, "Address is " + address);
Log.e(Tag, "Balance is " + balance);
Log.e(Tag, "Invoice is " + invoices);
accDetails.put("billToAddress", address);
accDetails.put("totalAccountBalance", balance + "\tUSD");
accDetails.put("totalOpenInvoicesValue", invoices + "\tUSD");
hashMap.add(accDetails); // size = 3
return null;
}
@Override
protected void onPostExecute(Void values) {
super.onPostExecute(values);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
/*How can I add values from hash map to TextView here?*/
}
}
在doInBackground()
方法中,我从Gson获取数据并将其添加到哈希映射中。
在onPostExecute()
方法中,我想将GSON
的值添加到TextView
。如何将hashMap
中的值添加到TextView
?
答案 0 :(得分:2)
你的AsyncTask的doInBackground()方法应该返回一个HashMap。
然后你的onPostExecute()方法会收到它,并且应该更新你的TextView。
以下是代码示例:
<!DOCTYPE html>
<HTML lang="en">
<HEAD>
<title>My webpage</title>
</HEAD>
<BODY>
<IMG src="sunset.png" width="500" height="400" alt="missing">
</BODY>
</HTML>
答案 1 :(得分:1)
您的doInBackground
函数需要返回hashMap
变量才能在onPostExecute
中访问它。
更改protected Void doInBackground(Void... voids)
到protected HashMap<String, String> doInBackground(Void... voids)
然后让您在该函数中返回return hashMap;
接下来更改您的protected void onPostExecute(Void values)
至protected void onPostExecute(HashMap<String, String> hashMap)
最后,将您的班级声明更改为private class getData extends AsyncTask<Void, Void, HashMap<String, String>>