java无法在我的ListView中列出数据库中的所有值
我正在尝试将我的localhost database
中的所有值列成ListView
。基本上,REST
进程和背景内容发生在我的AsyncTask
类中,因此我不能真正使用onCreate
方法
无论如何,这是我的代码:
public class ViewNames extends Activity {
ListView listView;
ArrayAdapter<String> viewAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewnames);
listView = (ListView) findViewById(R.id.listView);
// If I add the adapter here then I can't view the results. I want to view all the values I have as soon
as I open up the form. But this process only happens in my AsyncTask class so I don't know how to model this
list
//adapter = new ArrayAdapter<String>(ViewNames.this, 安卓.R.layout.simple_list_item_1,result);
//listView.setAdapter(adapter);
}
}
public class ViewNamesJSON extends AsyncTask<String, String, String> {
... //Other methods go here. They work fine.
@Override
// This is where it doesn't work. If I display the adapter in onCreate then I have an empty list.
// But I want to display the results of all the values after the user has clicked the button.
protected void onPostExecute(String s) {
List<String> namesList = new List<String>();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.optJSONArray("names");
for(int i=0; i < jsonArray.length(); i++){
JSONObject ones = jsonArray.getJSONObject(i);
String names = ones.optString("names");
namesList.add(names);
}
String[] result = namesList.toArray(new String[namesList.size()]);
adapter = new ArrayAdapter<String>(ViewNames.this, 安卓.R.layout.simple_list_item_1,result);
listView.setAdapter(adapter);
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
我的XML
文件:
<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:tools="http://schemas.安卓.com/tools" 安卓:layout_width="match_parent"
安卓:layout_height="match_parent" 安卓:paddingLeft="@dimen/activity_horizontal_margin"
安卓:paddingRight="@dimen/activity_horizontal_margin"
安卓:paddingTop="@dimen/activity_vertical_margin"
安卓:paddingBottom="@dimen/activity_vertical_margin" tools:context=".ViewNames"
安卓:orientation="vertical"
>
<Button
安卓:layout_width="130dp"
安卓:layout_height="wrap_content"
安卓:text="Add Names"
安卓:id="@+id/addNamesButton"
安卓:layout_marginTop="10dp"
安卓:layout_gravity="center_horizontal" />
<ListView
安卓:layout_width="match_parent"
安卓:layout_height="wrap_content"
安卓:id="@+id/listView"
安卓:layout_gravity="center_horizontal" />
</LinearLayout>
我遇到了一些困难,因为我想立即将数据库中的所有内容显示到ListView
中,然后在用户单击按钮时更新ListView
任何帮助都将不胜感激
# 1 楼答案
您可以在^{中定义和添加适配器。这只是在任务完成时调用
notifyDataSetChanged
的问题通过将
List
传递给适配器而不是数组,可以按如下方式进行,这样活动和适配器共享同一个集合希望这能有所帮助