我遇到了如何处理来自FetchDataTask的否定响应的问题。我有两个微调器,当我选择值时,我开始搜索MySQL数据库。当数据库中没有这样的值时,我应该在该布局上获得一些toast,列表为空并选择其他微调器选项。我的问题是我不知道在哪里实现它。这是代码:
private void initView() {
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://192.168.1.24/test/spinner.php";
Bundle extras = getIntent().getExtras();
if (extras != null) {
url = extras.getString("URL");
}
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
这是FetchDataTask的一部分
@Override
protected void onPostExecute(String sJson) {
if(sJson == null) {
if(listener != null) listener.onFetchFailure(msg);
return;
}
try {
// convert json string to json array
JSONArray aJson = new JSONArray(sJson);
// create apps list
List<Application> apps = new ArrayList<Application>();
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
Application app = new Application();
app.setIme(json.getString("Ime"));
app.setGrad(json.getString("Grad"));
app.setBroj(json.getString("Broj"));
app.setCena(json.getString("Cena"));
app.setPredmet(json.getString("Predmet"));
apps.add(app);
}
//notify the activity that fetch data has been complete
if(listener != null) listener.onFetchComplete(apps);
} catch (JSONException e) {
msg = "Invalid response";
if(listener != null) listener.onFetchFailure(msg);
return;
}
}
public String streamToString(final InputStream is) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
throw e;
}
finally {
try {
is.close();
}
catch (IOException e) {
throw e;
}
}
return sb.toString();
}
}
答案 0 :(得分:0)
您可以使用droidQuery来处理此问题:
$.ajax(new AjaxOptions().url("http://192.168.1.24/test/spinner.php")
.type("GET")
.dataType("json")
.context(this)
.success(new Function() {
@Override
public void invoke($ droidQuery, Object... params) {
JSONObject obj = (JSONObject) params[0];
//TODO parse JSONObject.
}
})
.error(new Function() {
@Override
public void invoke($ droidQuery, Object... params) {
AjaxError error = (AjaxError) params[0];
droidQuery.toast("Fetch Failed: " + error.error, Toast.LENGTH_SHORT);
}
}));
您还可以找到用于解析JSON
的方法$.map(JSONObject)和$.makeArray(JSONArray)。另外,请查看droidProgress以使用droidQuery
扩展程序轻松显示和隐藏ajax请求的进度指示器。