当单击listview项时,如何从sqlite数据库中读取某些数据并在对话框中显示?

时间:2017-08-22 23:26:20

标签: android sqlite listview

这显示了我的listview onclick监听器,我想在单击一个项目时打开一个对话框并显示sqlite信息。如何在listview项目上单击时获取日期和注释。以下是我的尝试,但它不起作用。另外我对android编程还是比较新的,所以如果你能在代码中对问题进行排序对我有用。

        ListAdapter adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, listData);
        mListView.setAdapter(adapter);

        //set an onItemClickListener to the ListView
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String name = adapterView.getItemAtPosition(i).toString();
                Log.d(TAG, "onItemClick: You Clicked on " + name);

                Cursor data = mDatabaseHelper.getexpenseItemID(name); //get the id associated with that name
                int itemID = -1;
                while(data.moveToNext()){
                    itemID = data.getInt(0);
                }
                if(itemID > -1){
                    displayNoteDate(mDatabaseHelper.getexpenseNote(data2),mDatabaseHelper.getexpenseDate(data1));
                }
                else{
                    toastMessage("No ID associated with that name");
                }
            }
        });

    public void displayNoteDate(String noteContent, String dateValue) {
        final Dialog builder = new Dialog(getActivity());
        builder.setContentView(R.layout.custom_dialog);

        builder.setTitle("Display note date");

        TextView note = (TextView)builder.findViewById(R.id.note);
        TextView date = (TextView)builder.findViewById(R.id.date);

        //add the database note and date
        note.setText(noteContent);
        date.setText(dateValue);

        Button closeButton = (Button)builder.findViewById(R.id.close);
        closeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
        builder.show();
    }

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";

public static final String DATABASE_NAME = "budget.db";
public static final String TABLE_NAME = "expense_table";
public static final String TABLE_NAME2 = "income_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "ID2";
public static final String EXPENSE_AMOUNT = "AMOUNT";
public static final String EXPENSE_DATE = "DATE";
public static final String EXPENSE_NOTES = "NOTES";
public static final String INCOME_AMOUNT = "AMOUNT";
public static final String INCOME_DATE = "DATE";
public static final String INCOME_NOTES = "NOTES";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 3);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,AMOUNT INTEGER,DATE INTEGER,NOTES TEXT)");
    db.execSQL("create table " + TABLE_NAME2 + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,AMOUNT INTEGER,DATE INTEGER,NOTES TEXT)");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME2);
    onCreate(db);
}

public boolean insertexpenseData(String amount_expense, String date_expense, String notes_expense) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(EXPENSE_AMOUNT, amount_expense);
    contentValues.put(EXPENSE_DATE, date_expense);
    contentValues.put(EXPENSE_NOTES, notes_expense);
    long result = db.insert(TABLE_NAME, null, contentValues);
    if (result == -1)
        return false;
    else
        return true;
}

public boolean insertincomeData(String amount_income, String date_income, String notes_income) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(INCOME_AMOUNT, amount_income);
    contentValues.put(INCOME_DATE, date_income);
    contentValues.put(INCOME_NOTES, notes_income);
    long result = db.insert(TABLE_NAME2, null, contentValues);
    if (result == -1)
        return false;
    else
        return true;
}

public Cursor getexpenseData() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
    return res;
}

public Cursor getincomeData() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from " + TABLE_NAME2, null);
    return res;
}

public Cursor getexpenseDate(Cursor date){
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_NAME + " WHERE " + EXPENSE_DATE + " = '" + date + "'";
    Cursor data1 = db.rawQuery(query, null);
    return data1;

}

public Cursor getexpenseNote(Cursor note){
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_NAME + " WHERE " + EXPENSE_NOTES + " = '" + note + "'";
    Cursor data2 = db.rawQuery(query, null);
    return data2;
    }



public Cursor getexpenseItemID(String name){
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "SELECT " + COL_1 + " FROM " + TABLE_NAME + " WHERE " + EXPENSE_AMOUNT + " = '" + name + "'";
    Cursor data = db.rawQuery(query, null);
    return data;
}

public Cursor getincomeItemID(String name){
    SQLiteDatabase db = this.getWritableDatabase();
    String query = "SELECT " + COL_2 + " FROM " + TABLE_NAME2 + " WHERE " + INCOME_AMOUNT + " = '" + name + "'";
    Cursor data = db.rawQuery(query, null);
    return data;
}

public boolean updateexpenseData(String id, String amount, String date, String notes) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_1, id);
    contentValues.put(EXPENSE_AMOUNT, amount);
    contentValues.put(EXPENSE_DATE, date);
    contentValues.put(EXPENSE_NOTES, notes);
    db.update(TABLE_NAME, contentValues, "ID = ?", new String[]{id});
    return true;
}

public boolean updateincomeData(String id, String amount, String date, String notes) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_2, id);
    contentValues.put(INCOME_AMOUNT, amount);
    contentValues.put(INCOME_DATE, date);
    contentValues.put(INCOME_NOTES, notes);
    db.update(TABLE_NAME2, contentValues, "ID = ?", new String[]{id});
    return true;
}

public Integer deleteexpenseData(String id) {
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(TABLE_NAME, "ID = ?", new String[]{id});
}

public Integer deleteincomeData(String id) {
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(TABLE_NAME2, "ID = ?", new String[]{id});
}


}

2 个答案:

答案 0 :(得分:0)

使用此方法

Cursor cursor = mDatabaseHelper.getexpenseItemID(name); 

if (cursor.getCount() > 0){
    cursor.moveToFirst();
    String noteContent = cursor.getString(cursor.getColumnIndex("NOTES"));
    String date = cursor.getString(cursor.getColumnIndex("DATE"));
    Toast.makeText(Activity.this, noteContent, Toast.LENGTH_SHORT).show();
    Toast.makeText(Activity.this, date, Toast.LENGTH_SHORT).show();
    displayNoteDate(noteContent, date); 

}

只要吐司回复您的数据,就知道您已成功从数据库中读取数据。

答案 1 :(得分:0)

这是一个解决方案(假设displayNoteDate有效,这是使用Toast测试的),它使用 CursorAdapter 而不是 ListAdapter

好处是双重的,无需创建中间数组,并且onItemClickListener中包含所有可用数据。

但有一个缺陷是Cursor adpater需要一个名为 _id 的列,因此我将帮助器中的onCreate方法更改为: -

public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT,AMOUNT INTEGER,DATE INTEGER,NOTES TEXT)");
        db.execSQL("create table " + TABLE_NAME2 + " (_id INTEGER PRIMARY KEY AUTOINCREMENT,AMOUNT INTEGER,DATE INTEGER,NOTES TEXT)");

    }

即。 _id 替换 ID

出于测试目的,我在下面添加了一些数据: -

    mDatabaseHelper.insertexpenseData("100.00","21/03/1904","Wow this old?");
    mDatabaseHelper.insertexpenseData("56.78","31/12/2010","New Celebrations");
    mDatabaseHelper.insertexpenseData("250.00","23/08/2017","Birthday Present");

我使用的实际代码(除了第一行以获取数据作为游标)与您的密切相关(onItemClick的正文,它从光标获取数据)): -

    .......
    expensedata = mDatabaseHelper.getexpenseData();
    SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
            android.R.layout.simple_list_item_1,
            expensedata,
            new String[]{DatabaseHelper.EXPENSE_AMOUNT},
            new int[]{android.R.id.text1}, 0);
    listdata.setAdapter(sca);
    listdata.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            int csrpos = expensedata.getPosition();
            expensedata.moveToPosition(i);
            displayNoteDate(
                    expensedata.getString(expensedata.getColumnIndex(DatabaseHelper.EXPENSE_NOTES)),
                    expensedata.getString(expensedata.getColumnIndex(DatabaseHelper.EXPENSE_DATE)));
            expensedata.moveToPosition(csrpos);
        }
    });


}

//!!!NOTE!!! Used for testing so don't use this method.
private void displayNoteDate(String notes, String date) {
    Toast.makeText(this,"Notes=" + notes + " Incurred on " + date,Toast.LENGTH_LONG).show();
}

@Override
public void onDestroy() {
    super.onDestroy();
    expensedata.close();
}

注意 expensedata 使用Cursor expensedata;声明为类变量

注意完成后应关闭光标。我使用了一个活动,因此使用了onDestroy方法。

运行时显示: -

enter image description here

点击 56.78 时(同样适用于其他列表项),然后: -

enter image description here