2

I have an asynctask which gets its data through php. The asynctask works fine, it passes the values to a global arraylist. However, when i try to call the variable on onCreate after .execute(), it returns a null size/value(s). I would like to know why this global variable returns a null when its supposed to have a value. Thanks in advance!

this is the code for asyntask:

 private class  get_pendingreq extends AsyncTask<String, Integer, String> 
 {
    @Override
    protected String doInBackground(String... arg0) 
    {
        InputStream is = null;
        String result = "";

        try 
        {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url+"pending_requests.php");

            List<NameValuePair> parameter = new ArrayList<NameValuePair>();
            parameter.add(new BasicNameValuePair("email", globalVariables.accountemail));


            httppost.setEntity(new UrlEncodedFormEntity(parameter));

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) 
        {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        try 
        {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null) 
            {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) 
        {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        return result;
    }

    @Override
    protected void onPostExecute(String result) 
    {
        super.onPostExecute(result);

        try 
        {
            /*  JSON parsing starts here    */
            JSONObject jArray = new JSONObject(result);
            /*globalVariables.pendingdate = new ArrayList<String>();*/
            JSONArray request = jArray.getJSONArray("request");

            for (int i = 0; i < request.length(); i++) 
            {

                JSONObject e = request.getJSONObject(i);

                /* puts values to arraylist<String>  */                 
                globalVariables.pendingdate.add(e.getString("date"));

            }

            Log.d("striiing", globalVariables.pendingdate.toString());
        } catch (JSONException e) 
        {
            e.printStackTrace();
                }
    }
}

Main activity:

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.calendar);

    new get_pendingreq().execute();

    System.out.print("alalala" + globalVariables.pendingdate.size());
      }//this returns null

Global Variable:

public static ArrayList<String> pendingdate = new ArrayList<String>;

4 Answers 4

4

Because AsyncTask not finished. Put System.out.print("finish"); in onPostExcute() and see who is printed first.

1
  • yes, it will return null because code not wait AsyncTask until finish. just execute it then go to next code line.
    – AwadKab
    Commented Mar 17, 2013 at 5:11
1

The idea behind an AsyncTask is that it runs asynchronously from the main thread, thus on a background thread. That way it doesn't block the execution of any code on the main thread.

Knowing that, the following lines will execute right after each other:

new get_pendingreq().execute();
System.out.print("alalala" + globalVariables.pendingdate.size());

Your get_pendingreq class will not do any actual work until after a small delay, meaning that after calling the first lines in above snippet, nothing has really happened. You've only instructed the platform to start the async task somewhere in the near future.

Now, the globalVariables.pendingdate field you're accessing on the second line will not have any values until the async task finishes its work. That doesn't happen until onPostExecute() is executed. In other words: you're trying to print the values at the wrong moment in time.

Simply move that print to the end of the async task's onPostExectute() method (but obviously before the return - why's that even there at all?).

I highly recommend you have a read through the AsyncTask class documentation and the Processes and Threads article.

1
  • the return was not supposed to be there.. i guess i overlooked it. Yes, will do some reading on the article. thank you.
    – wacko
    Commented Mar 17, 2013 at 4:48
0

It is clear form the name indeed AsyncTask runs Asynchronously ... Let me explain taking your code into consideration:

new get_pendingreq().execute();

This line will create a new thread for execution and it will run asynchronously and so the next line(i.e.System.out.print("alalala" + globalVariables.pendingdate.size());) gets executed immidiatly after this line without waiting the async task to get executed completly.so put this system.print line inside the post execute method...

0

Are u sure, that globalVariables.pendingdate.add(e.getString("date")); realy have field "data" ?

1
  • yes, it has values because when i call the variable inside asynctask, it displays the values and the size
    – wacko
    Commented Mar 17, 2013 at 4:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.