【发布时间】:2012-07-24 22:34:48
【问题描述】:
我正在设置这样的 ListView 适配器:
public class SeeAllQuestionsActivity extends Activity
{
//ArrayAdapter<Question> adapter;
SimpleAdapter mSchedule = null;
ListView list = new ListView (this);
TextView loading_questions = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.all_question_page);
TextView loading_questions = (TextView) findViewById(R.id.loading_questions);
list = (ListView) findViewById(R.id.list);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
mSchedule = new SimpleAdapter(this, mylist, R.layout.questions_list,
new String[] {"train", "from", "to"},
new int[] {R.id.TRAIN_CELL, R.id.FROM_CELL, R.id.TO_CELL});
list.setAdapter(mSchedule);
list.setTextFilterEnabled(true);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
...
然后进行远程异步调用以从我的数据库中获取列表,并尝试在 onPostExecute 方法中执行此操作:
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
try
{
JSONArray obj = new JSONArray(result);
if ( obj != null )
{
for ( int i = 0; i < obj.length(); i++ )
{
JSONObject o = obj.getJSONObject(i);
map.put("train", "Business Name");
map.put("from", ">");
map.put("to", ">");
mylist.add(map);
map = new HashMap<String, String>();
map.put("train", "103(x)");
map.put("from", "6:35 AM");
map.put("to", "7:45 AM");
mylist.add(map);
}
}
}
catch ( Exception e )
{
}
list.setAdapter(mSchedule);
但我在这一行得到一个空指针异常:
ListView list = new ListView (this);
但我认为总的来说,我在 postExecute 方法中需要如何完成这件事还有很长的路要走。非常感谢有关如何正确执行此操作的任何帮助。
【问题讨论】:
-
您的线路
ListView list = new ListView (this);不是必需的。您在 XML 中定义了您的 ListView,您可以将它分配给一个变量,就像您已经做的那样:list = (ListView) findViewById(R.id.list); -
@MartijnVanMierloo 哦,对了,好点子。我现在要试试这个,但我认为服务器返回后我的代码仍然有点混乱......不管......现在尝试你的建议。
-
@MartijnVanMierloo 您的建议确实阻止了崩溃,但仍然存在一个问题,即屏幕最终没有显示我设置的列表。
-
您确定
result不为空吗? -
@MartijnVanMierloo 是的 100% 确信结果不为空,因为我一直使用这个后端代码,而且当我以不同的方式拥有列表视图时,这个代码曾经可以工作。
标签: android android-layout android-asynctask