0

I am trying to populate fragment listview using async task, But listvew is not populating. I am getting data in logs, And there is no error and exception in logs.

I am following this example

dynamic listview adding "Load more items" at the end of scroll

Here is code:-

    public class HindiFragment extends Fragment {
        // XML node keys
            static final String KEY_SONG = "song"; // parent node
            static final String KEY_ID = "id";
            static final String KEY_TITLE = "title";
            static final String KEY_ARTIST = "artist";
            static final String KEY_DURATION = "duration";
            static final String KEY_THUMB_URL = "thumb_url";
            static final String KEY_VIDEO_URL = "video";
            static final String KEY_UPLOAD_BY = "upload_by";
            Context abc=null;
            static int startIndex = 0;
             private WeakReference<MyAsyncTask> asyncTaskWeakRef;
            ListView list;
            static LazyAdapter adapter;
            JSONObject json;
            static int offset = 10;
            static ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

            public static Context hindiFragment=null;
            private static int catId=0;
             static View rootView ;
        public HindiFragment(){}

        public HindiFragment(int position) {
            // TODO Auto-generated constructor stub
            catId=position;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

            //StrictMode.setThreadPolicy(policy); 


             rootView = inflater.inflate(R.layout.main, container, false);
               // TextView tvLabel =  (TextView)rootView.findViewById(R.id.txtLabel);
               // tvLabel.setText("Hello"); try
             hindiFragment=rootView.getContext();
             try{
                 //Toast.makeText(hindiFragment,  "catid is "+catId, 
                    //     Toast.LENGTH_LONG).show();
                UserFunctions userFunction = new UserFunctions();
                json=userFunction.getAndroidVersion();
                 JSONArray android_version_array = json.getJSONArray("version");
                 TextView tv = (TextView) rootView.findViewById(R.id.android_version);
                 //getting android version
                 for (int i = 0; i < android_version_array.length(); i++) {
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
                         JSONObject myObj = android_version_array.getJSONObject(i);
                         if(! myObj.getString("version").equalsIgnoreCase(String.valueOf(getString(R.string.android_version)))){
                         tv.setText( Html.fromHtml(myObj.getString("text")));
                         tv.setMovementMethod(LinkMovementMethod.getInstance());
                         }else
                         {
                             tv.setVisibility(View.GONE);
                         }
                        // adding each child node to HashMap key => value
                    }

                 startNewAsyncTask(this.getActivity());

           return rootView;
             }catch(Exception e){
                 e.printStackTrace();
             }
            return rootView;

        }

        public static void loadMore(int startIndex,int page,Activity myActivity){
            try{
            UserFunctions userFunction = new UserFunctions();
            Log.e("page ",""+page);
            int status=0;
            JSONObject json;
             json = userFunction.getChannelData(String.valueOf(catId),page);
             if(json.has("video")){
             JSONArray deletedtrs_array = json.getJSONArray("video");

            for (int i = 0; i < deletedtrs_array.length(); i++) {
                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();
                 JSONObject myObj = deletedtrs_array.getJSONObject(i);
                // adding each child node to HashMap key => value
                map.put(KEY_ID, myObj.getString("uid"));
                map.put(KEY_TITLE, myObj.getString("uid"));
                map.put(KEY_ARTIST,myObj.getString("video"));
                map.put(KEY_DURATION, myObj.getString("duration"));
                map.put(KEY_THUMB_URL,myObj.getString("thumb_url"));
                map.put(KEY_VIDEO_URL, myObj.getString("url"));
                map.put(KEY_UPLOAD_BY,"By: "+ myObj.getString("upload_by"));

                // adding HashList to ArrayList
                //if(!songsList.contains(map))
                {
                songsList.add(map);
                status=1;
                }
            }
             }
            //if(status==1)
            {
            //]list=(ListView)rootView.findViewById(R.id.list);
            // Getting adapter by passing xml data ArrayList
          // adapter=new LazyAdapter(myActivity, songsList);     
          // list.setAdapter(adapter);
          // adapter.notifyDataSetChanged();
            }
            }catch(Exception e){

                e.printStackTrace();
            }

        }
        private void startNewAsyncTask(Activity act) {
            MyAsyncTask asyncTask = new MyAsyncTask(act);
            this.asyncTaskWeakRef = new WeakReference<MyAsyncTask >(asyncTask );
            asyncTask.execute();
        }
        private static class MyAsyncTask extends AsyncTask<Void, Void, Void> {

            private WeakReference<HindiFragment> fragmentWeakRef;
            HindiFragment uindiFragment;
            Activity myActivity;
            private MyAsyncTask (Activity activity) {
                this.fragmentWeakRef = new WeakReference<HindiFragment>(uindiFragment);
                myActivity=activity;
            }

            @Override
            protected Void doInBackground(Void... params) {
                //Toast.makeText(hindiFragment, "helllo", 
                  // Toast.LENGTH_LONG).show();
                            //TODO: your background code
                Log.e("Now in background",offset+"");
                loadMore(startIndex, offset,myActivity);
                return null;
            }

            @Override
            protected void onPostExecute(Void response) {
                super.onPostExecute(response);
                ListView  list=(ListView)rootView.findViewById(R.id.list);
                // Getting adapter by passing xml data ArrayList
                adapter=new LazyAdapter(myActivity, songsList); 
                list.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                Log.e("Ended here11 ","now endeded11");

                if (this.fragmentWeakRef.get() != null) {
                                 //TODO: treat the result
                     adapter.notifyDataSetChanged();
                }
            }
        }


    }
Community
  • 1
  • 1
neooo
  • 241
  • 1
  • 4
  • 11
  • please clarify your question in the body of the post – Dan Beaulieu May 19 '15 at 17:20
  • it's clear. i am trying to populate listview using async task, but list with data is not showing. an epty page is showing. If i dont use async task then data in listview is showing. – neooo May 19 '15 at 17:29

2 Answers2

0

You are over-using weak reference. My guess is your async task or fragment is being garbage collected since you use them cyclically: you can verify this by seeing if weakReference.get() returns null.

In fact, you don't need WeakReference at all: just implement appropriate cancel logic that you can call from onPause onStop or onDestroy depending on how you want to handle repeated calls.

Also you shouldn't pass the context to your Async class: instead create an observer such as: public interface Callback { public void onAsyncDone(Arraylist<DataItem> listItems); } and if not cancelled, @Override public void onPostExecute(Void v) { if (!isCancelled()) { Callback c = callbackReference.get(); if (c != null) c.onAsyncDone(getListItems()); } } where getListItems() returns whatever work is done in doInBackground. Here I use a weak reference for the callback (which you implement in your activity) since you seem to want to use one. But again, as long as you release the reference to the context if cancelled, you don't actually need one. The reason the activity is wrapped as the Callback is that the async task should only have one job: process the items and pass them along. Let your activity or controller change the UI with the new items.

Ashton Engberg
  • 5,949
  • 2
  • 19
  • 14
0

I suspect the loadMore() method does not load up any data to object songsList into the adapter. Simply trace the reason why it is not. There's no way I can debug this without using debugger, the code flow is rather complicated with unusually tight references and, more so, with static access. The suspected code for review:

protected void onPostExecute(Void response) {
   super.onPostExecute(response);
   ListView  list=(ListView)rootView.findViewById(R.id.list);
   // Getting adapter by passing xml data ArrayList
   adapter=new LazyAdapter(myActivity, songsList); 
   list.setAdapter(adapter);
   adapter.notifyDataSetChanged();
...
}

Note: You can put some good logging in LazyAdapter code and see if data is populated there.

The Original Android
  • 6,147
  • 3
  • 26
  • 31