0

So this question bothered me for a while because i can't seem to find out an easy, convenient and natural way to update ui while fetching data from external locations (Webserver).

I will sketch my scenario :

I got a webserver, which serves JSONArray's and JSONObject's. It always returns this because i don't like nullpointers. I tried to write a class which extends AsyncTask. I succeeded in doing this and it looks like this :

public class Server extends AsyncTask<String, Integer, Object>{

        private String fetch_url;
        private String return_type;
        private Activity ct;

        public Server() {
        }

        public Server(Activity ct) {
            this.ct = ct;
        }

        @Override
        protected void onPreExecute()
        {


        }


        @Override
        protected Object doInBackground(String... url) {
            this.fetch_url = url[0];
            this.return_type = url[1];

            if(return_type.equals("json_object")) {
                return urlToJsonObject(this.fetch_url);
            } else {
                return urlToJsonArray(this.fetch_url);
            } 



        }




        private String convertStreamToString(InputStream is) {
           /*
            * To convert the InputStream to String we use the BufferedReader.readLine()
            * method. We iterate until the BufferedReader return null which means
            * there's no more data to read. Each line will appended to a StringBuilder
            * and returned as String.
            */

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
           StringBuilder sb = new StringBuilder();

           String line = null;
           try {
               while ((line = reader.readLine()) != null) {
                   sb.append(line + "\n");
               }
           } catch (IOException e) {
               e.printStackTrace();
           } finally {
               try {
                   is.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }

           return sb.toString();
        }

    protected JSONObject urlToJsonObject(String url) {
        JSONObject arr = null;

        HttpClient httpclient = new DefaultHttpClient();

        // Prepare a request object
        HttpGet httpget = new HttpGet(url); 

        // Execute the request
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            if (entity != null) {

                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);

                // A Simple JSONArray Creation
                arr = new JSONObject(result);

                // Closing the input stream will trigger connection release
                instream.close();


            }


        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return arr;
    }

    protected JSONArray urlToJsonArray(String url) {
        JSONArray arr = null;

        HttpClient httpclient = new DefaultHttpClient();

        // Prepare a request object
        HttpGet httpget = new HttpGet(url); 

        // Execute the request
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            if (entity != null) {

                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);

                // A Simple JSONArray Creation
                arr = new JSONArray(result);

                // Closing the input stream will trigger connection release
                instream.close();


            }


        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return arr;
    }

    }

After the data came in, i transform it to my own models with getters and setters. Then i want to update my ui with these results, but for some reason i always receive nullpointers.

For example :

  • I got an GridLayout which i want to fill with multiple PhotoAlbums.
  • First i am fetching those records from my webserver.
  • Then processing each album.
  • Then if an individual Album gets added to the GridLayout it needs to update. And not all at once while blocking ui.

What is a nice central way of getting data from external sources and updating ui while it is loading? Can somebody point me to techniques, tutorials, methods, insights, etc. I am very curious about this.

Jack Sierkstra
  • 1,414
  • 2
  • 20
  • 42
  • you can use onPostExecute(param) to update ui. http://developer.android.com/reference/android/os/AsyncTask.html. You can also use lazy list or Univaersal image loader if you are downloading images from server. http://stackoverflow.com/questions/15621936/whats-lazylist – Raghunandan May 31 '13 at 17:34

1 Answers1

0

I see you have a constructor already so you can use that to accept a reference to your Activity that needs to be updated or a reference to Views. Pass a reference of your Activity when you create the AsyncTask then adjust your constructor to accept that reference. Then you can use that to call Activity methods inside onPostExecute() or onProgressUpdate() that will update the UI when finished.

See this answer for a better example

AsyncTasks getStatus may be helpful to you also if you need to know when it is finished

Community
  • 1
  • 1
codeMagic
  • 44,549
  • 13
  • 77
  • 93