我正在尝试将一组获取结果显示为列表。每当我尝试使用虚拟数据时,它都会正确显示,但是当我将其更改为从服务器检索到的数据时,什么也没有发生。我没有收到任何错误,所以这很令人困惑
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);
}
}
}
字符串数组countries
在方法中正确显示,runOnUiThread
而标题没有。我检查了标题字符串数组中的数据,它是有效的。知道为什么会这样吗?