I am trying to display set of fetch results as a list. Whenever I try to use dummy data, it's displayed correctly but when I change it to the data retrieved from the server nothing happens. I do not get any errors so that's very confusing
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class BlogFragment extends ListFragment {
String[] countries = new String[] {
"India",
"Pakistan",
"Sri Lanka",
"China",
"Bangladesh",
"Nepal",
"Afghanistan",
"North Korea",
"South Korea",
"Japan"
};
String [] titles ={};
ArrayAdapter<String> adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
/** Creating an array adapter to store the list of countries **/
new AsyncFetchData().execute();
adapter = new ArrayAdapter<String>(inflater.getContext(), android.R.layout.simple_list_item_1,titles);
return super.onCreateView(inflater, container, savedInstanceState);
}
private class AsyncFetchData extends AsyncTask
{
@Override
protected Object doInBackground(Object... arg0) {
JSONArray a = new JSONArray();
ArrayList<String> aList = new ArrayList<String>();
a = ServerAPI.getData();
for (int i = 0; i < a.length(); i++) {
String title = null;
String content = null;
try {
title = a.getJSONObject(i).getString("title");
content = a.getJSONObject(i).getString("content");
aList.add(title);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(title);
// System.out.println(content);
}
titles = aList.toArray(new String[aList.size()]);
/** Setting the list adapter for the ListFragment */
return null;
}
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
ArrayAdapter aa = new ArrayAdapter(getActivity().getBaseContext(), android.R.layout.simple_list_item_1, titles);
aa.notifyDataSetChanged();
setListAdapter(aa);
}
}
}
The string array countries
is displayed correctly in the runOnUiThread
method while titles does not. I check the data placed in titles string array and it's valid.
Any idea why this is happening?
The problem is:
Your adapter was already initialized with old set of data. So you are updating the underlying data, but adapter still holds the old data.
You need to update adapter with new data.
For that,
call
just before