将数据从db获取到listview

时间:2012-03-18 11:09:14

标签: android listview adapter

我从数据库的行中提取数据,我想在listview上显示它们。想象一下,我带着名字和手机,所以我希望每行listview都有电话和名字。

到目前为止,这是我的代码:(这些项目正常启动,我使用system.out.ptintln看到它们)。所以在info [0]中我有了名字,在信息[1]中我有了电话。

这是我的适配器代码。

    public class FacilitiesAdapter extends ArrayAdapter<String> {
        private final Context context;
        private String data[] = null;

        public FacilitiesAdapter(Context context, String[] data)  {
            super(context, R.layout.expand_row);
            this.context = context;
            this.data = data;

        }
         public View getView(int position, View convertView, ViewGroup parent) {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View rowView = inflater.inflate(R.layout.expand_row, parent, false);
                TextView textView = (TextView) rowView.findViewById(R.id.name);
                System.out.println("I am in the adapter "+data[0]);
                textView.setText(data[0]);
TextView textView2 = (TextView) rowView.findViewById(R.id.phone);
textView2.setText(data[1]);
                return rowView;
         }
}

所以我想用上面的代码,我必须在每一行看到数据0和数据[1](电话)?但我错了。那是为什么?

这是我的javacode:

JSONArray jArray = new JSONArray(result);
         for(int i=0;i<jArray.length();i++){
             //each line fetches a line of the table
                JSONObject json_data = jArray.getJSONObject(i);
                if (json_data.getString("Name")!=null)  info[0]=json_data.getString("Name");
                if (json_data.getString("Phone")!=null) info[1]=json_data.getString("Phone");

                FacilitiesAdapter adapter = new FacilitiesAdapter(this,info);
                System.out.println(info[0]);
                setListAdapter(adapter);

1 个答案:

答案 0 :(得分:2)

你在循环中做setListAdapter,这很奇怪,我打赌那不是你打算做的。您只需要使用数据填充字符串数组,并使用字符串数组 字符串数组列表初始化您的FacilitiesAdapter并执行setListAdapter 一次

修改

我认为您误解了适配器背后的概念,适配器用于保存整个AdapterView的数据,这是ListView的父类,而不是用于保存单个项目的数据AdapterView。

您的适配器需要List String[],如下所示:

public FacilitiesAdapter ... {
    List<String[]> dataList;
    public FacilitiesAdapter (List<String[]> dataList) {
        this.dataList = dataList;
    }
    public View getView(int position, View convertView, ViewGroup parent) {
        String[] data = dataList.get(position);
        // set your data to the views.
    }
}

编辑2:

List<String[]> listData = new ArrayList<String[]>();
for(int i = 0; i < jArray.length(); ++i) {
    JSONObject json_data = jArray.getJSONObject(i);
    String name = json_data.getString("Name");
    String phone = json_data.getString("Phone");
    //... some code to check *nullity* of name and phone
    listData.add(new String[]{name, phone});
}    

上面的代码将填充listData,其中包含从JSONObject获取的名称和电话(存储在数组中)。现在,您可以将此listData作为参数传递给适配器的构造函数。

如果你仍然没有得到它,你需要一本关于Java编程语言的书,在使用该语言编程之前掌握语言Android将帮助你更好地学习其他东西。