private static List<DataVoucher> processResponse(String response) {
List<DataVoucher> list = new ArrayList<DataVoucher>();
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray jsonArray = jsonObj.getJSONArray("produk");
Log.d(TAG, "data lengt: " + jsonArray.length());
DataVoucher dataVoucher = null;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
dataVoucher = new DataVoucher();
dataVoucher.setKode(obj.getString("kode"));
dataVoucher.setHrg(obj.getString("hrg"));
dataVoucher.setNom(obj.getString("nom"));
dataVoucher.setKet(obj.getString("ket"));
list.add(dataVoucher);
listvoucher.add(obj.getString("nom"));
}
} catch (JSONException e) {
Log.d(TAG, e.getMessage());
}
return list;
}
public static String requestDataVoucher(final String operator) {
final String TAG = "SEND JSON";
Thread thread = new Thread() {
public void run() {
Looper.prepare();
JSONObject jsonObjSend = new JSONObject();
try {
jsonObjSend.put("type", "svoc");
jsonObjSend.put("hp", "089631633614");
jsonObjSend.put("opr", operator);
Log.i(TAG, jsonObjSend.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
SendHttpPost(jsonObjSend);
Looper.loop();
}
};
thread.start();
return TAG;
}
private class MainActivityAsync extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("retrieving...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected String doInBackground(String... params) {
String response = requestDataVoucher(pilihOperator
.getSelectedItem().toString());
list = processResponse(response);
return null;
}
@Override
protected void onPostExecute(String result) {
adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_item, listvoucher);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
pilihVoucher.setAdapter(adapter);
adapter.notifyDataSetChanged();
if (!adapter.isEmpty()) {
progressDialog.dismiss();
} // this is annoying
}
}
答案 0 :(得分:0)
adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_item,listvoucher);
我想你的意思 adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_item,list);
顺便说一句,只是在onPostExecute()中解除你的progressDialog没有检查任何内容,如果列表为空则可能会警告用户,这样你就可以避免这些问题。
答案 1 :(得分:0)
这里有很多问题
doInBackground
正在一个线程中运行,与ui线程不同。你正在调用requestDataVoucher
,它也在创建一个新线程,在这种情况下没用。
您正在使用字符processResponse
来调用response
,这是requestDataVoucher
的结果。根据您的代码,response
等于"SEND JSON"
。因此JSONObject jsonObj = new JSONObject(response);
将触发异常,listvoucher将保持为空,适配器也将如此。结论,适配器为空,progressDialog
不会消失。
我无法提出修复方法,因为SendHttpPost
未知。但就我的理解而言,您应该从requestDataVoucher
中删除线程创建并返回SendHttpPost
生成的JSON字符串。