我正在尝试使用php和json在远程服务器上使用数据库创建android应用程序。我正在运行的查询假设返回一行作为答案,并且似乎存在问题,因为json数组始终返回空。这是我的JSON类代码:
public class JSONClass extends AsyncTask<String,Void,String>{
public JSONArray res = null;
private String link;
private Context context;
public JSONClass(Context context, int queryNo, String params) {
this.context = context;
link = "http://pickupfriend.fulba.com/android_project/query" + queryNo + ".php" + params;
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
protected String doInBackground(String... arg0) {
try{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(link);
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
res = new JSONArray(result);
}catch(Exception e){
}
return "";
}
}
这就是我使用此类的方式:EditText userNam =(EditText)findViewById(R.id.userNamTxt); EditText pass =(EditText)findViewById(R.id.pssTxt);
String uName,Pss;
uName = userNam.getText().toString();
Pss = pass.getText().toString();
String str = "?uname=" + uName + "&password=" + Pss;
JSONClass jClass = (JSONClass) new JSONClass(this, 1, str).execute();
res = jClass.res;
php链接为:“ http://pickupfriend.fulba.com/android_project/query1.php?uname=itzick&password=maccabi ”,它返回以下结果:“ [{“ UserID”:“ 1”}]“。当我将结果作为jsonArray(我的res)进行检查时,其长度始终为0。有人可以告诉我我在哪里出错吗?先感谢您!
您使用AsyncTask似乎有问题。您不应该res = jClass.res
在execute()之后获得结果,因为您可能还没有HTTP响应。当您说长度为0,而对象实际上为null时,可能就是您得到的错误。
在使用onPostExecute()
AsyncTask的方法接收数据后,应该相应地更新UI 。像这样的东西:
public class JSONClass extends AsyncTask<String,Void,JSONArray>{
...
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
protected JSONArray doInBackground(String... arg0) {
...
String result = EntityUtils.toString(entity, "utf-8");
return new JSONArray(result);
}
protected void onPostExecute(JSONArray result) {
// DO WHATEVER YOU WANT IN YOUR UI
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句