itzick binder
itzick binder

Reputation: 562

Getting array with JSON and android application

I'm trying to create an android application using a database on a remote server using php and json. The query I'm running suppose to return one row as an answer and it seems that there is a problem because the json array always returns empty. This is my JSON class code:

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

And this is how I use the class: 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;

The php link is: "http://pickupfriend.fulba.com/android_project/query1.php?uname=itzick&password=maccabi" and it returns this result: "[{"UserID":"1"}]". When I check the results as a jsonArray (my res), its length is always 0. Can someone please tell me where I'm making a mistake? Thank you in advance!

Upvotes: 0

Views: 444

Answers (2)

Jamsheed Kamarudeen
Jamsheed Kamarudeen

Reputation: 728

AsyncTask happens asynchronously. The execute() function starts the asynctask and proceeds with the code. In your case it executes res = jClass.res; But at this point, the jClass.res will be null because the asynctask may not have completed yet. So res becomes null. That is why your jarray size is 0.

On completion, Asynctask executes the function OnPostExecute() as in

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
}

}

Now, if you can only do what you want in the activity, not the in the asynctask, you have to send back the data to the activity using a Handler.

To make a handler, add this to the activity or fragment you are calling the async task

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
    }
}

On initialization of asynctask, add the handler object too

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;
}

Dont forget to pass it along with your parameters from activity on initialization.

Also in 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();
    }
}

Upvotes: 0

David Ferrand
David Ferrand

Reputation: 5470

There seems to be a problem with your use of the AsyncTask. You shouldn't get the result res = jClass.res just after execute() because you probably haven't got the HTTP response yet. Maybe that's the error you get when you say your length is 0, the object is actually null.

You should update your UI accordingly after receiving data in the onPostExecute() method of your AsyncTask. Something like this:

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
    }

}

Upvotes: 2

Related Questions