我的应用程序有一个RecyclerView列表,并且它填充了SQLite表中的数据: UserDatabase 。我通过在DbHelper类中调用方法 getAllUser 来实现这一点,如下所示。我在Recylcerview的ListAdaptor中也有一个方法,它在列表项的单击上启动 ItemEditActivty 。 ItemEditActivity 允许用户使用方法 UpdateUserDetail 和 DeleteRowItem 编辑或删除他们刚刚点击/打开的行数据,如如下所示。
这一切都很完美,但是,我不知道如何将 ItemEditActivity 的三个EditTexts设置为NAME,QUANTITY和DESCRIPTION的行的Table值;存储在表中。目前,当用户打开 ItemEditActivity 时,EditText的 et_name,et_quantity和et_description 为空。 如何在onCreate期间将这些EditText设置为保存在表格行中的数据?
编辑:我通过传递ListAdapter的意图并将变量设置为 ItemEditActivity 中的 itemPosition 来获取所选列表位置项。
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class DbHelper extends SQLiteOpenHelper {
String stringo;
private static final String TAG = "DbHelper";
private static final String DATABASE_NAME = "UserDatabase";
private static final int DATABASE_VERSION = 1;
private static DbHelper mDbHelper;
public static String TABLE_USERdETAIL = "userdetail";
private static final String _ID = "_id";
private static final String NAME = "name";
private static final String QUANTITY = "quantity";
private static final String DESCRIPTION = "description";
public static synchronized DbHelper getInstance(Context context) {
if (mDbHelper == null) {
mDbHelper = new DbHelper(context.getApplicationContext());
}
return mDbHelper;
}
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_USERDETAIL_TABLE = "CREATE TABLE " + TABLE_USERdETAIL +
"(" +
_ID + " INTEGER PRIMARY KEY ," +
NAME + " TEXT," +
QUANTITY + " INTEGER," +
DESCRIPTION + " TEXT" +
")";
db.execSQL(CREATE_USERDETAIL_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion != newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERdETAIL);
onCreate(db);
}
}
/*
Insert a user detail into database
*/
public void insertUserDetail(UserData userData) {
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(NAME, userData.name);
values.put(QUANTITY, userData.quantity);
values.put(DESCRIPTION, userData.description);
db.insertOrThrow(TABLE_USERdETAIL, null, values);
db.setTransactionSuccessful();
} catch (SQLException e) {
e.printStackTrace();
Log.d(TAG, "Error while trying to add post to the database insertUserDetail");
} finally {
db.endTransaction();
}
}
public void updateUserDetail(int id, String v1, String v2, String v3){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NAME, v1);
values.put(QUANTITY, v2);
values.put(DESCRIPTION, v3);
db.update(TABLE_USERdETAIL, values, "_id="+id, null);
}
/*
fetch all data from UserTable
*/
public List<UserData> getAllUser() {
List<UserData> usersdetail = new ArrayList<>();
String USER_DETAIL_SELECT_QUERY = "SELECT * FROM " + TABLE_USERdETAIL;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(USER_DETAIL_SELECT_QUERY, null);
try {
if (cursor.moveToFirst()) {
do {
UserData userData = new UserData();
userData.id = cursor.getString(cursor.getColumnIndex(_ID));
userData.name = cursor.getString(cursor.getColumnIndex(NAME));
userData.quantity = cursor.getString(cursor.getColumnIndex(QUANTITY));
userData.description = cursor.getString(cursor.getColumnIndex(DESCRIPTION));
usersdetail.add(userData);
} while (cursor.moveToNext());
}
} catch (Exception e) {
Log.d(TAG, "Error while trying to get posts from database");
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
return usersdetail;
}
/*
Delete single row from UserTable
*/
void deleteRow(String name) {
SQLiteDatabase db = getWritableDatabase();
try {
db.beginTransaction();
db.execSQL("delete from " + TABLE_USERdETAIL + " where name ='" + name + "'");
db.setTransactionSuccessful();
Log.d(TAG, "delete called");
} catch (SQLException e) {
Log.d(TAG, "Error while trying to delete users detail");
} finally {
db.endTransaction();
}
}
void deleteRowItem(String id) {
SQLiteDatabase db = getWritableDatabase();
try {
db.beginTransaction();
db.execSQL("delete from " + TABLE_USERdETAIL + " where _id ='" + id + "'");
db.setTransactionSuccessful();
Log.d(TAG, "delete called");
} catch (SQLException e) {
Log.d(TAG, "Error while trying to delete users detail");
} finally {
db.endTransaction();
}
}
}
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
public class ItemEditActivity extends AppCompatActivity {
private static final String TAG = "ItemCreateActivity";
DbHelper dbHelper;
EditText et_name, et_quantity, et_description;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_creation);
setTitle("Edit Item");
Intent Intent = getIntent();
Integer itemPostion = Intent.getIntExtra("ItemNumber", 1)
dbHelper = DbHelper.getInstance(getApplicationContext());
et_name = (EditText) findViewById(R.id.et_name);
et_quantity = (EditText) findViewById(R.id.et_quantity);
et_description = (EditText) findViewById(R.id.et_description);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.character_edit_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent Intent = getIntent();
final Integer itemPostion = Intent.getIntExtra("ItemNumber", 1);
switch (item.getItemId()) {
case R.id.save_character:
Log.d(TAG, "Save character creation activity");
UserData userData = new UserData();
if (!et_name.getText().toString().isEmpty()) {
userData.name = et_name.getText().toString();
if (!et_quantity.getText().toString().isEmpty()) {
userData.quantity = "Quantity: " + et_quantity.getText().toString();
if (!et_description.getText().toString().isEmpty()) {
userData.description = et_description.getText().toString();
dbHelper.updateUserDetail(itemPostion, et_name.getText().toString(), "Quantity: " + et_quantity.getText().toString(), et_description.getText().toString());
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(this, "Enter Description", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Enter Quantity", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Enter Name", Toast.LENGTH_SHORT).show();
}
return true;
case R.id.delete_character:
new AlertDialog.Builder(this)
.setMessage("This item will be deleted")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
dbHelper.deleteRowItem(itemPostion + "");
finish();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
答案 0 :(得分:1)
您必须在数据库中创建方法以获取单行。在DbHelper类
中创建如下方法 public UserData getSingleUserDetial(String userId) {
SQLiteDatabase db = this.getWritableDatabase();
UserData userData = null;
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_USERdETAIL + " WHERE " + _ID + "= ?", new String[]{userId});
try {
while (cursor.moveToNext())
{
userData = new UserData();
userData.name = cursor.getString(cursor.getColumnIndex(NAME));
userData.quantity = cursor.getString(cursor.getColumnIndex(QUANTITY));
userData.description = cursor.getString(cursor.getColumnIndex(DESCRIPTION));
}
cursor.close();
} catch (Exception e) {
Log.d(TAG, "Error while trying to get data from database");
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
return userData;
}
和ItemEditActivity一样获取
UserData userData = dbHelper.getSingleUserDetial(userId);