我是android的新手,我刚刚创建了一个sqlite数据库!我在其中添加值(希望如此),我想在ListView中显示这些值。
现在更多细节......我有一个ViewPager,在第一个片段中我有一个按钮,它触发了我的sqlite数据库的setmethod。在ViewPager的第二个片段中,我想要一个ListView,在按下按钮后将显示Sqlite的结果。问题是即使我创建了Listview,它也没有显示在我的片段中。此外,当我在我的设备中运行我的代码时,应用程序崩溃并返回我在下面发布的错误。如果有人能帮我正确实现ListView并使其正常工作,我将不胜感激!
OnCreateView:
public class PeopleManager extends ListFragment {
private PeopleHelper getHelper;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_people_manager,null);
getHelper = new PeopleHelper(getActivity());
ListView list = (ListView) v.findViewById(R.id.list);
List<PeopleModel> values = new ArrayList<PeopleModel>();
ArrayAdapter<PeopleModel> adapter = new ArrayAdapter<PeopleModel>(getActivity(),
android.R.id.list, values);
setListAdapter(adapter);
return v;
}
我的xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="vertical" >
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<Button
android:id="@+id/peopleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="People List" />
</LinearLayout>
LogCat:
03-02 17:37:10.449: E/AndroidRuntime(5555): java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
答案 0 :(得分:1)
首先修复例外:替换
android:id="@+id/list"
带
android:id="@android:id/list"
在您的布局XML中。该ID必须来自android.R
,而不是您应用的R
。
之后,在此处修复代码:
ListView list = (ListView) v.findViewById(R.id.list);
更改为android.R.id.list
。
ArrayAdapter<PeopleModel> adapter = new ArrayAdapter<PeopleModel>(getActivity(),
android.R.id.list, values);
ArrayAdapter
构造函数需要每个列表行layout
资源ID。传入android.R.id.list
将无效 - 它甚至不是layout
标识符。
之后考虑将一些数据添加到传递给适配器的ArrayList
。