Najd
Najd

Reputation: 78

AsyncTask return null

I'm working on app that enables me to load users from php mysql and when I select on of them it opens a new activity to display the name of user and button to delete it. the problem is when I run the app, AllUsersActivity dosen't return the users. It displays an empty page here is the code of the method LoadAllUsers, there was an "else " to move to another avtivity to create user if there was not any user. but I removed it because I want it to display users and delete them without adding. After I removed the add part it returned to me null, although the connection is working right and it retrived the data from the DB in the logcat. can anyone help me with it please

/**
     * Background Async Task to Load all users by making HTTP Request
     * */
    class LoadAllUsers extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AllUsersActivity.this);
            pDialog.setMessage("Loading users. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All users from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_users, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All users: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // user found
                    // Getting Array of user
                    user = json.getJSONArray(TAG_USER);

                    // looping through All users
                    for (int i = 0; i < user.length(); i++) {
                        JSONObject c = user.getJSONObject(i);

                        // Storing each json item in variable
                        String U_mail = c.getString(TAG_UMAIL);
                        String Name = c.getString(TAG_NAME);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_UMAIL, U_mail);
                        map.put(TAG_NAME, Name);

                        // adding HashList to ArrayList
                        usersList.add(map);
                    }
                } 
            } 

            catch (JSONException e) {
                e.printStackTrace();  }

            return null;
        }

/**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all users
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            AllUsersActivity.this, usersList,
                            R.layout.list_item, new String[] { TAG_UMAIL,
                                    TAG_NAME},
                            new int[] { R.id.um, R.id.name });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

here is the logcat

04-23 09:22:36.814: W/System.err(916): org.json.JSONException: No value for users
04-23 09:22:36.814: W/System.err(916):  at org.json.JSONObject.get(JSONObject.java:354)
04-23 09:22:36.814: W/System.err(916):  at org.json.JSONObject.getJSONArray(JSONObject.java:544)
04-23 09:22:36.824: W/System.err(916):  at com.example.androidhive.AllUsersActivity$LoadAllUsers.doInBackground(AllUsersActivity.java:140)
04-23 09:22:36.824: W/System.err(916):  at com.example.androidhive.AllUsersActivity$LoadAllUsers.doInBackground(AllUsersActivity.java:1)
04-23 09:22:36.824: W/System.err(916):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-23 09:22:36.865: W/System.err(916):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)

 04-23 09:22:36.924: W/System.err(916):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
    04-23 09:22:36.924: W/System.err(916):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor

.java:573)

Upvotes: 0

Views: 4380

Answers (2)

ScouseChris
ScouseChris

Reputation: 4397

You don't have an onPostExecute() override, there you should be dismissing the dialog and updating your UI.

I also noticed you use return null; in your doInBackground() method, if you want to return a string as your method signature suggests then you would return a string here to pass into the onPostExecute() method.

As Gordak suggested you could change your method signature to AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> (NB you have to use a capital V for Void ) then you can simply return your HashMap and process it in onPostExecute()

EDIT

I noticed a couple of things with your updated question, first, your exception is being caused because when you try to load the users array the field isn't found in the JSON. user = json.getJSONArray(TAG_USER); Check your feed to make sure there aren't any typos in the field names, or TAG_USER.

Second you always apss null into your onPostExecute() so the file path will always be null.

Finally, onPostExecute() always executes on the UI thread so you don't need the runOnUIThread() call.

Upvotes: 1

Gordak
Gordak

Reputation: 2070

I don't understand what you are trying to do. I guess you what to get data from a JSON string. Looking at your code, this data contains some an array of JSONObject. Each object containing a mail and a name.

What I would probably do in this case. Instead of extending a AsyncTask<String, String, String>, extend a AsyncTask<void, void, ArrayList<HashMap<String, String>>>. This way, your doInBackground method return a ArrayList<HashMap<String, String>> which is maybe more interesting than a single String.

At the end of your for loop, return usersList.

If you get an exception, handle it and return null or a empty new ArrayList> object.

Then decide what you are going to do in the onPostExecute method.

Hope it helps you.

Upvotes: 0

Related Questions