我試圖在使用php和json的遠程服務器上使用數據庫創建一個android應用程序。我正在運行的查詢假設返回一行作爲答案,似乎有問題,因爲json數組總是返回空。 這是我的JSON類代碼:使用JSON和Android應用程序獲取數組
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」,它返回這個結果: 「[{」 用戶ID 「:」 1 「}]」。 當我作爲jsonArray(我的資源)檢查結果時,其長度始終爲0.有人可以告訴我我犯了什麼錯誤嗎?先謝謝你!
我嘗試過,但我不能讓我的doInBackground函數返回JSONArray,只有字符串。每當我嘗試讓它返回JSONArray時,我收到一個錯誤,Android Studio只告訴我將它返回給String。我怎樣才能讓它返回JSONArray? –
檢查我發佈的代碼的第一行,您的AsyncTask類型也必須更改! –
它沒有工作,我改變了我的doInBackground,如你所說,並添加:@TargetApi(Build.VERSION_CODES。KITKAT) 保護無效onPostExecute(JSONArray結果){ 嘗試res = new JSONArray(result); (JSONException e){ e.printStackTrace(); } }。但是每次我嘗試在調用它的其他類中使用jClass.res時,它仍然會下降。 –