2014-07-04 69 views
0

我試圖在使用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.有人可以告訴我我犯了什麼錯誤嗎?先謝謝你!

回答

2

您使用AsyncTask似乎存在問題。你不應該在execute()之後得到結果res = jClass.res,因爲你可能還沒有得到HTTP響應。也許這就是你說你的長度爲0時得到的錯誤,對象實際上是空的。

在接收到AsyncTask的onPostExecute()方法中的數據後,您應該相應地更新您的用戶界面。事情是這樣的:

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 
    } 

}

+0

我嘗試過,但我不能讓我的doInBackground函數返回JSONArray,只有字符串。每當我嘗試讓它返回JSONArray時,我收到一個錯誤,Android Studio只告訴我將它返回給String。我怎樣才能讓它返回JSONArray? –

+1

檢查我發佈的代碼的第一行,您的AsyncTask類型也必須更改! –

+0

它沒有工作,我改變了我的doInBackground,如你所說,並添加:@TargetApi(Build.VERSION_CODES。KITKAT) 保護無效onPostExecute(JSONArray結果){ 嘗試res = new JSONArray(result); (JSONException e){ e.printStackTrace(); } }。但是每次我嘗試在調用它的其他類中使用jClass.res時,它仍然會下降。 –

0

的AsyncTask異步發生。​​函數啓動asynctask並繼續執行代碼。在你的情況下,它執行res = jClass.res;但是在這一點上,jClass.res將爲空,因爲asynctask可能尚未完成。所以res變爲null。這就是爲什麼你jarray大小爲0

完成後,執行的AsyncTask功能OnPostExecute()在

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"); 


    }catch(Exception e){ 

    } 
    return result; 
} 
@Override 
protected void onPostExecute(Void result) { 
    //result is sent here. now 
JSONArray res = new JSONArray(result); 
//Do what you want with JSONArray 
} 

} 

現在,如果你只能做你想做的活動是什麼,而不是在asynctask,你必須使用Handler將數據發送回活動。

要進行處理,將其添加到活動或片段您呼叫的異步任務

Handler handler = new Handler() { 
    public void handleMessage(android.os.Message msg) { 
     Bundle bundle = msg.getData(); 
     String result = bundle.getString("JSONRESULT"); 
     JSONArray res = new JSONArray(result); 
     //Now do what you want here 
    } 
} 

上的AsyncTask的初始化,添加處理程序對象太

private Handler handler; 
public JSONClass(Context context, int queryNo, String params) { 
    this.context = context; 
    link = "http://pickupfriend.fulba.com/android_project/query" + queryNo + ".php" + params; 
    this.handler=handler; 
} 

不要忘記通過它與您在初始化活動中的參數一起使用。

而且在OnPostExecute

@Override 
protected void onPostExecute(String result) { 
    super.onPostExecute(result); 
    try { 
     Bundle bundle = new Bundle(); 
     bundle.putString("JSONRESULT", result); 
     Message msg = new Message(); 
     msg.setData(bundle); 
     handler.sendMessage(msg); 
    } catch (Exception e) { 
     // TODO: handle exception 
     e.printStackTrace(); 
    } 
}