Ahora quiero obtener el valor seleccionado de la vista de lista en la nueva UpdateActity para poder editar o eliminar. Cómo hacer eso.
Aquí hay un ejemplo de trabajo que actualiza (va a UpdateActivity) y elimina (en Long Click de un elemento). Esto utiliza un CursorAdapter, a saber, el SimpleCursorAdapter estándar. Usar adaptadores de Cursor para datos de SQLite es bastante simple.
Primero el DatabaseHelper :-
class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(@Nullable Context context) {
super(context, "mydatabase", null, 1);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS mytable (_id INTEGER PRIMARY KEY, name TEXT, surname TEXT, phone TEXT)");
/* Add some test data */
add("Fred","Bloggs","0000000000",sqLiteDatabase);
add("Jane","Doe","1111111111",sqLiteDatabase);
add("Mary","Johnston","2222222222",sqLiteDatabase);
add("Tom","cobboly","3333333333",sqLiteDatabase);
add("Anne","Walker","4444444444",sqLiteDatabase);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long update(long id, String name, String surname, String phone) {
long rv = 0;
ContentValues cv = new ContentValues();
if (name != null && name.length() > 0) cv.put("name",name);
if (surname != null && surname.length() > 0) cv.put("surname",surname);
if (phone != null && phone.length() > 0) cv.put("phone",phone);
if (cv.size() > 0) rv = this.getWritableDatabase().update("mytable",cv,"_id=?",new String[]{String.valueOf(id)});
return rv;
}
public long delete(long id) {
return this.getWritableDatabase().delete("mytable","_id=?",new String[]{String.valueOf(id)});
}
public Cursor getAll() {
return this.getWritableDatabase().query("mytable",null,null,null,null,null,null);
}
public Cursor getById(long id) {
return this.getWritableDatabase().query("mytable",null,"_id=?",new String[]{String.valueOf(id)},null,null,null);
}
private long add(String name, String surname, String phone, SQLiteDatabase db) {
ContentValues cv = new ContentValues();
cv.put("name",name);
cv.put("surname",surname);
cv.put("phone",phone);
return db.insert("mytable",null,cv);
}
public long add(String name, String surname, String phone) {
return add(name,surname,phone,this.getWritableDatabase());
}
}
- NOTA IMPORTANTE Los adaptadores de cursor requieren una columna de id y que se llame _id .
- NOTA esto agrega algunos datos de prueba.
- Todos los métodos de acceso están incluidos
- getAll devuelve un Cursor con TODAS las filas de la tabla.
- actualiza las actualizaciones de acuerdo con los valores pasados, solo se ocupa de actualizar los valores (por ejemplo, como no hay editSurname EditText, se pasa nulo para que el apellido permanezca como estaba).
- getById devuelve un cursor con todos los valores según el id
- agregar sin el cuarto parámetro es el agregado típico, el que tiene el cuarto parámetro es para permitir su uso en onCreate antes de que DatabaaeHelper se haya instanciado por completo.
Actividad de datos de lista
public class ListDataActivity extends AppCompatActivity {
ListView listview;
SimpleCursorAdapter sca;
DatabaseHelper databaseHelper;
Cursor cursor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = this.findViewById(R.id.mylistview);
databaseHelper = new DatabaseHelper(this);
setOrRefreshListView();
}
/* handles the ListView */
private void setOrRefreshListView() {
cursor = databaseHelper.getAll(); /* Gets the data to be listed */
/* If first time then setup the adapter listeners etc */
if (sca == null) {
sca = new SimpleCursorAdapter(
this,
android.R.layout.simple_expandable_list_item_2,
cursor,
new String[]{"name","phone"},
new int[]{android.R.id.text1, android.R.id.text2},
0
);
listview.setAdapter(sca); // attach the adapter to the listview
// setup On Item Click to start the update activity passing the id
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(ListDataActivity.this,UpdateActivity.class);
intent.putExtra("my_id_extra",l);
startActivity(intent);
}
});
// setup the on Item LONG Click to delete a row
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
databaseHelper.delete(l);
setOrRefreshListView(); // after deletion refresh the data
return true;
}
});
} else {
sca.swapCursor(cursor); // if not the first time just tell the adapter the data has changed
}
}
@Override
protected void onResume() {
super.onResume();
setOrRefreshListView(); // refresh the listview when returning to the activity
}
@Override
protected void onDestroy() {
super.onDestroy();
cursor.close(); // clean up
}
}
El diseño de ListDataActivity (muy básico solo un ListView) :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ListDataActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<ListView
android:id="@+id/mylistview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/teal_200"
>
</ListView>
</LinearLayout>
- conjunto de fondo para que sea fácil ver ListView.
Actividad de actualización :-
public class UpdateActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
EditText editName, editPhone;
Button saveButtonId,showButtonId;
long currentId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
editName = this.findViewById(R.id.editName);
editPhone = this.findViewById(R.id.editPhone);
saveButtonId = this.findViewById(R.id.savebuttonId);
showButtonId = this.findViewById(R.id.showbuttonId);
databaseHelper = new DatabaseHelper(this);
currentId = this.getIntent().getLongExtra("my_id_extra",-1);
if (currentId < 0 ) {
// do something as invalid id passed
finish();
}
showData();
showButtonId.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
saveButtonId.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
databaseHelper.update(currentId,editName.getText().toString(),null,editPhone.getText().toString());
}
});
}
private void showData() {
Cursor cursor = databaseHelper.getById(currentId);
if (cursor.moveToFirst()) {
editName.setText(cursor.getString(cursor.getColumnIndex("name")));
editPhone.setText(cursor.getString(cursor.getColumnIndex("phone")));
}
cursor.close();
}
}
- el botón showData regresa a ListDataActivity (creo que eso es lo que querías).
Resultado :-
- Cuando comenzó de nuevo :-
-
Haga clic en Mary (y edite el número a 999999999 pero no guarde):-
-
Haga clic en Guardar (igual que 2)
-
Haga clic en Mostrar :-
- Haga clic largo Fred :-
- Reiniciar la aplicación:-