如何从sqlite数据库填充自定义列表视图?

时间:2018-01-30 14:05:24

标签: android sqlite listview android-sqlite custom-adapter

我创建了一个Android应用程序,我必须从sqlite数据库中获取数据并将其设置在自定义列表视图上。问题是没有显示数据。我的代码与显示输出所需的代码相同。

1 个答案:

答案 0 :(得分:0)

您需要创建一个扩展CursorAdapter的类。以下是演示代码:

public class PassCursorAdapter extends CursorAdapter {
public PassCursorAdapter(Context context, Cursor c) {
    super(context, c,0);
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return LayoutInflater.from(context).inflate(R.layout.item_todo,parent,false);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {


    TextView textID = (TextView) view.findViewById(R.id.textView6);
    TextView textName = (TextView) view.findViewById(R.id.textView3);
    TextView textUser = (TextView) view.findViewById(R.id.textView4);
    TextView textPass = (TextView) view.findViewById(R.id.textView5);

    int idColumnIndex = cursor.getColumnIndex(PassDBHelper.COLUMN_ID);
    int nameColumnIndex = cursor.getColumnIndex(PassDBHelper.PASS_COLUMN_NAME);
    int userColumnIndex = cursor.getColumnIndex(PassDBHelper.PASS_COLUMN_USERNAME);
    int passColumnIndex = cursor.getColumnIndex(PassDBHelper.PASS_COLUMN_PASSWORD);

    String id = cursor.getString(idColumnIndex);
    String name = cursor.getString(nameColumnIndex);
    String user = cursor.getString(userColumnIndex);
    String pass = cursor.getString(passColumnIndex);

    textID.setText(id);
    textName.setText(name);
    textUser.setText(user);
    textPass.setText(pass);

}

}

在newView方法中,您将返回布局文件。这是列表视图布局文件与4个文本视图的对比方式。在End中有方法bindView,你可以在其中设置id。

现在要显示数据库,您需要从sq-lite数据库获取数据,如下所示:

   private void displayDataBaseInfo() {

   PassDBHelper passDBHelper = new PassDBHelper(this);
   SQLiteDatabase db = passDBHelper.getReadableDatabase();
   String [] columns = {
      PassDBHelper.COLUMN_ID,
      PassDBHelper.PASS_COLUMN_NAME,
      PassDBHelper.PASS_COLUMN_USERNAME,
      PassDBHelper.PASS_COLUMN_PASSWORD
   } ;

   Cursor cursor = db.query(PassDBHelper.TABLE_NAME,columns,null,null,null,null,null);


    ListView listView = (ListView)findViewById(R.id.list);

    PassCursorAdapter passCursorAdapter = new  PassCursorAdapter(this,cursor);

    listView.setAdapter(passCursorAdapter);

}//displayDatabaseInfo