如何通过单击listview项目编辑已保存到sqlite数据库的数据?

时间:2017-09-25 17:04:14

标签: android sqlite listview

我有一个列表视图项,显示输入数据库的数据,单击它会打开一个带有按钮编辑的对话框。单击它时,我想编辑已输入数据库的数据。我已经创建了对话框,只需要知道要在那里编写数据库条目的代码。首先,我输入了一个通过微调器保存的数量,日期,注释和类别。保存后如何编辑数据?我也是android编程的新手,所以代码示例将不胜感激。

我的listview片段:

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;

public class tab2income extends Fragment {

    private static final String TAG = "tab2income";
    DatabaseHelper mDatabaseHelper;
    private ListView mListView;
    View rootView;
    Cursor incomedata;
    SimpleCursorAdapter sca;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.tab2income, container, false);
        return rootView;
    }

    @Override
    public void onActivityCreated( Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mListView = (ListView) rootView.findViewById(R.id.listViewincome);
        mListView.setEmptyView(rootView.findViewById(R.id.empty));
        mDatabaseHelper = new DatabaseHelper(getActivity());

        populateListView();
    }

    private void populateListView() {
        Log.d(TAG, "populateListView: Displaying data in the ListView.");
        incomedata = mDatabaseHelper.getincomeData();
        sca = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_1, incomedata, new String[]{DatabaseHelper.INCOME_AMOUNT}, new int[]{android.R.id.text1}, 0);
        mListView.setAdapter(sca);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                int csrpos = incomedata.getPosition();
                incomedata.moveToPosition(i);
                displayNoteDate(
                        incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_NOTES)),
                        incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_DATE)),
                        incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_CATEGORY)),
                        l);
                incomedata.moveToPosition(csrpos);
            }
        });
    }


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

    public void displayNoteDate(String noteContent, String dateValue,String category, final long noteID) {
        MaterialDialog.Builder builder= new MaterialDialog.Builder(getActivity())
                .title("Income Information")
                .content("Category: "+category+"\nNote: "+noteContent+"\nDate: "+ dateValue)
                .positiveText("edit")
                .negativeText("delete")
                .neutralText("close")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    }
                })
                .onNeutral(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        mDatabaseHelper.deleteincomeData(Long.toString(noteID));
                        incomedata = mDatabaseHelper.getincomeData();
                        sca.swapCursor(incomedata);
                    }
                });
        builder.show();
    }

}

这是我的数据库助手,因此您知道我已经输入数据库的数据。

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

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

    public static final String DATABASE_NAME = "budget7.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 = "_id";
    public static final String EXPENSE_AMOUNT = "EXPENSE_AMOUNT";
    public static final String EXPENSE_DATE = "DATE";
    public static final String EXPENSE_NOTES = "NOTES";
    public static final String INCOME_AMOUNT = "INCOME_AMOUNT";
    public static final String INCOME_DATE = "DATE";
    public static final String INCOME_NOTES = "NOTES";
    public static final String INCOME_CATEGORY = "INCOME_CATEGORY";
    public static final String EXPENSE_CATEGORY = "EXPENSE_CATEGORY";

    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, EXPENSE_AMOUNT DOUBLE,DATE INTEGER,NOTES TEXT, EXPENSE_CATEGORY TEXT)");
        db.execSQL("create table " + TABLE_NAME2 + " (_id INTEGER PRIMARY KEY AUTOINCREMENT,INCOME_AMOUNT DOUBLE,DATE INTEGER,NOTES TEXT, INCOME_CATEGORY 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, String category_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);
        contentValues.put(EXPENSE_CATEGORY, category_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, String category_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);
        contentValues.put(INCOME_CATEGORY, category_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 boolean updateexpenseData(String id, String amount, String date, String notes, String catagory_income) {
        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);
        contentValues.put(EXPENSE_CATEGORY, catagory_income);
        db.update(TABLE_NAME, contentValues, "_id = ?", new String[]{id});
        return true;
    }

    public boolean updateincomeData(String id, String amount, String date, String notes, String catagory_income) {
        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);
        contentValues.put(INCOME_CATEGORY, catagory_income);
        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});
    }

    public double getNetBudget() {
        SQLiteDatabase db = this.getWritableDatabase();
        String selectQuery = "SELECT TOTAL(INCOME_AMOUNT) - (SELECT TOTAL(EXPENSE_AMOUNT) FROM expense_table) FROM income_table";
        Cursor cursor = db.rawQuery(selectQuery, null);
        double netBudget = 0.00; // if there is no row, this will mean 0 is returned. You could also set it to -1, or throw an Exception if no record is returned
        if (cursor.moveToFirst()) {
            netBudget = cursor.getInt(0);
        }
        cursor.close();
        return netBudget;
    }

    public double getTotalExpense() {
        SQLiteDatabase db = this.getWritableDatabase();
        String selectQuery = "SELECT TOTAL(EXPENSE_AMOUNT) FROM expense_table";
        Cursor cursor = db.rawQuery(selectQuery, null);
        double netExpense = 0.00; // if there is no row, this will mean 0 is returned. You could also set it to -1, or throw an Exception if no record is returned
        if (cursor.moveToFirst()) {
            netExpense = cursor.getInt(0);
        }
        cursor.close();
        return netExpense;
    }

    public double getTotalIncome() {
        SQLiteDatabase db = this.getWritableDatabase();
        String selectQuery = "SELECT TOTAL(INCOME_AMOUNT) FROM income_table";
        Cursor cursor = db.rawQuery(selectQuery, null);
        double netIncome = 0.00; // if there is no row, this will mean 0 is returned. You could also set it to -1, or throw an Exception if no record is returned
        if (cursor.moveToFirst()) {
            netIncome = cursor.getInt(0);
        }
        cursor.close();
        return netIncome;
    }

    public void deleteAllIncome() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_NAME2, null, null);
        db.execSQL("delete from " + TABLE_NAME2);
        db.close();
    }

    public void deleteAllExpense() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_NAME, null, null);
        db.execSQL("delete from " + TABLE_NAME);
        db.close();
    }
}

1 个答案:

答案 0 :(得分:0)

我没有查看您的代码,但您可以使用update命令,如下所示:

首先从`Edittext。

获取字符串

String name = editText.getText().toString();

然后使用更新命令。

db.execSQL("update table_name set column_name = 'yourtext' where youcondition");

示例 - 您可以通过EditText设置名称为Deep,其中id = 6

db.execSQL("update Table_Name2 set Name = '"+name+"' where id=6");

这样您就可以编辑并保存数据库中的更新值 您可以向该对话框添加edittext和按钮,并将此命令放在该按钮的onClick中。  
因此,对于edittext中的预写数据,您可以执行以下操作:
您可以将其放在onClick of listview中,打开对话框。

if(name!=null)
{
 edittext.setText(name,TextView.BufferType.EDITABLE);
}
如果您再次进行编辑,并且在字符串'name'中设置了edittext的值,那么

'name'将不会为空,这样edittext将包含之前输入的内容每次除了第一次以外的价值。