paul590 paul590 - 5 months ago 36
Android Question

Updating listview on fragment

I have a

ListView
that has a
SwipeRefreshLayout
implemented on it. What I am trying to do is update the
ListView
when the user swipes down. I've tried looking for different options but unfortunately I am unable to find a solution.

Would it be better to reload the
Fragment
or the
onCreate
function?

Here is my code

public class NewsTab extends Fragment implements OnRefreshListener{
final LinkedList<News> listnews = new LinkedList<News>();


public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.news_tab, container, false);
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);

newslist = (ListView) view.findViewById(R.id.displaynews);

populatelist(listnews);
adapter = new CustomAdapter(getActivity(),listnews);
newslist.setAdapter(adapter);
return view;
}

public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
new StartNewsLoad().execute("");
}

private class StartNewsLoad extends AsyncTask<String, Void, String> {
//ProgressDialog pd = null;
protected String doInBackground(String... params) {
reloadNews();
loadTopNews();
//NewsTab.listnews = new LinkedList<News>();
return null;
}

protected void onPostExecute(String result) {
adapter = new CustomAdapter(getActivity(),listnews);
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
}


///ANSWER

I found the answer! I added the following line of code inside my costume adapter and called it outside as adapter.refresh();

public void refresh(LinkedList<News> newsList)
{
this.results = newsList;
notifyDataSetChanged();
}


Thank you everybody for your help!

Answer

First of all no need to create the adapter again in onPostExecute() as you have already initialized it in onCreateView().You simple need to notify the adapter of the changes in the "listnews" if it has changed.Make sure that your list actually changes before calling the notifyDataSetChanged().

Also please use debugger or log to check whether your onRefresh() is called or not.From the way i see, it should be overriden with @override annotation as it is the method of the interface implemented by your fragment(swipeRefreshLayout.setOnRefreshListener(this);).It should be like:

@Override
public void onRefresh() {
    swipeRefreshLayout.setRefreshing(true);
    new StartNewsLoad().execute("");
    }
Comments