数组适配器显示字段值,而不是android中数据库的数据值

时间:2015-01-18 05:27:59

标签: android sqlite android-fragments android-listview android-arrayadapter

我正在尝试在listview中显示来自数据库的fragments数据。出于这个原因,我在数据库中添加了一个表。现在我正在尝试创建数据适配器。这是我的代码

list=(ListView)rootView.findViewById(R.id.listView1);
try{
DatabaseHandler db = new DatabaseHandler(getActivity());
List<Label> allLabel = db.getAllLabels();
for (Label label : allLabel) {   
ArrayAdapter<Label> dataadapter= new ArrayAdapter<Label>(getActivity(),android.R.layout.simple_list_item_1,allLabel);   
list.setAdapter(dataadapter);

list.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent,View v, int position,long id)
    {
        Toast.makeText(getActivity(), ((TextView)v).getText(), Toast.LENGTH_LONG).show();

    }
});
}
}
catch (Exception e)
{
    e.printStackTrace();
}

这是我输入的包含字段值而不是数据值:

   com.qcash.atmlocator.Label@52852d88
   com.qcash.atmlocator.Label@52852dd8
   com.qcash.atmlocator.Label@52852e08
   com.qcash.atmlocator.Label@52852e38

这是我的代码中使用的getAllLabels()函数:

public List<Label> getAllLabels(){

List<Label> labels = new ArrayList<Label>();

// Select All Query
String selectQuery = "SELECT  * FROM " + TABLE_LABELS;

SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

// looping through all rows and adding to list
if (cursor.moveToFirst()) {
    do {
        Label label = new Label();
        label.setId(cursor.getInt(0));
        label.setName(cursor.getString(1));
        label.setLatitude(cursor.getDouble(2));
        label.setLongitude(cursor.getDouble(3));
        labels.add(label);
    } while (cursor.moveToNext());
}

// closing connection
cursor.close();
db.close();

// returning lables
return labels;
}

如何获取数据库值?请帮帮我。

2 个答案:

答案 0 :(得分:0)

覆盖标签类中的toString()方法。我假设你的班级有一个变量&#39; name&#39;。

class Label{
   // other variables. 

    @Override
    public String toString() {
        return name;
    }
}

<强>更新

更改onItemclick侦听器

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent,View v, int position,long id)
    {
        Label label = (Label)parent.getItemAtPosition(position);
        Toast.makeText(getActivity(), "" + label.toString(), Toast.LENGTH_LONG).show();

    }
});

答案 1 :(得分:0)

将光标数据添加到字符串并将该字符串添加到调用函数片段解决了这个问题。这是代码:

 String name=cursor.getString(0)+"\n"+cursor.getString(1)+"\n"+cursor.getString(2)+"\n"+cursor.getString(3);
                FindPeopleFragment.ArrayofName.add(name);

最后显示数组到适配器完成:

ArrayAdapter<String> dataadapter= new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,ArrayofName);