Langsung ke konten utama

SQLiteDatabase Part4: Update an Delete data in Table Example

Part4: update and delete the data in table

 Update Screenshots:












Delete Screenshots:










Step 1: Add the following update and delete methods in DBAdapter.java to manipulate the database

DBAdapter.java

public Cursor getValuesById(int id){
       return database.rawQuery("select * from sample_table where _id = "+id, null);
}

public int updateValues(int id, String name, String contact) {
       ContentValues values2 = new ContentValues();
       values2.put("name", name);
       values2.put("phone", contact);

       return database.update(DBOpenHelper.SAMPLE_TABLE_NAME, values2,
                     "_id=?", new String[] { "" + id });
}
public int deleteById(int id){
       return database.delete(DBOpenHelper.SAMPLE_TABLE_NAME, "_id=?", new String[]{""+id});
}

Step 2: Create context menu xml file to display option when long click on the list item

res/menu/listview_context_menu.xml

listview_context_menu.xml

<?xml version="1.0"encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/context_item_edit"
        android:title="Edit"/>
    <item
        android:id="@+id/context_item_delete"
        android:title="Delete"/>

</menu>

ViewAllDetails.java

Step 3: Register context menu for listView, write the following code in onCreate()

registerForContextMenu(listView);

Step 4: Add the following code in onCreate()

listView.setOnItemLongClickListener(newOnItemLongClickListener() {

       @Override
       public booleanonItemLongClick(AdapterView<?> arg0, View arg1,
                     int arg2, long arg3) {
              String id = ((TextView) arg1
                           .findViewById(R.id.custom_textView_id)).getText()
                           .toString();
              selected_item_id = Integer.parseInt(id);
              return false;
       }

});

Step 5: Add two methods onCreateContextMenu and onContextItemSelected in ViewAllDetails.java

@Override
public voidonCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
       getMenuInflater().inflate(R.menu.listview_context_menu, menu);
       super.onCreateContextMenu(menu, v, menuInfo);
}
      
@Override
public booleanonContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.context_item_edit:
       dialog = newDialog(ViewAllActivity.this);
       dialog.setTitle("Edit Details");
       dialog.setContentView(R.layout.custom_dialog);
       dialog.show();

       Cursor cursor = dbAdapter.getValuesById(selected_item_id);
       cursor.moveToFirst();

       editText_name = (EditText) dialog
                     .findViewById(R.id.custom_dialog_editText_name);
       editText_phone = (EditText) dialog
                     .findViewById(R.id.custom_dialog_editText_phone);
       Button button_save = (Button) dialog
                     .findViewById(R.id.custom_dialog_button_save);
       Button button_cancel = (Button) dialog
                     .findViewById(R.id.custom_dialog_button_cancel);

       editText_name.setText(cursor.getString(1));
       editText_phone.setText(cursor.getString(2));

       button_save.setOnClickListener(new OnClickListener() {
              @Override
              public void onClick(View v) {
              String name = editText_name.getText().toString();
              String phone = editText_phone.getText().toString();
              int response = dbAdapter.updateValues(selected_item_id,
                           name, phone);

              if (response == -1) {
                     Toast.makeText(getApplicationContext(),  "Data Failed Update", Toast.LENGTH_LONG).show();
              } else {
                     refreshListView();
                     Toast.makeText(getApplicationContext(),  "Data Updated successfully", Toast.LENGTH_LONG)
                                  .show();
              }
              dialog.dismiss();
              }
       });

       button_cancel.setOnClickListener(new OnClickListener() {

              @Override
              public void onClick(View v) {
                     dialog.dismiss();
              }
       });

       break;

case R.id.context_item_delete:
       int response = dbAdapter.deleteById(selected_item_id);
       if (response == -1) {
       Toast.makeText(getApplicationContext(),  "Data failed to delete successfully", Toast.LENGTH_LONG).show();
       } else {
       Toast.makeText(getApplicationContext(),  "Data deleted successfully", Toast.LENGTH_LONG).show();
       refreshListView();
       }
       break;
}
       return super.onContextItemSelected(item);
}

Step 6: Add refreshListView() to refresh the listView content after Update and Delete Items

private void refreshListView() {
              cursor = dbAdapter.getAllValues();
              cursor.moveToFirst();
              MyAdapter adapter = new MyAdapter();
              listView.setAdapter(adapter);
       }



Komentar

Postingan populer dari blog ini

How Create a Accessibility Service in Android

Hello friends, In this Tutorial. In this post, I will show you how to use Accessibility Service for Android. Before that, we need to know What is Accessibility Service . Accessibility Service Here, I am taking an example for creating Virtual Service Button instead of Default Back Button. Project Structure: Create a new Project in Android Studio with the required Specifications. Codes: AndroidManifest.xml Don't forget to add the following permission in your manifest file. <uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE"/> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> Don't forget to add the following Lines in your manifest file to create service for your application. <service android:name=".MyService" android:label="@string/app_name" android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"> <intent-filter> <...

How to Perform Rest API using Retrofit in Android (Part-1)

In this post, I will show you How to use Retrofit in Android. Retrofit is a new born baby of web services such as AsyncTask, JSONParsing and Volley. This post is Split into Two Parts. First Part Contains Architecture of Retrofit and How to create MySQL DB and PHP Scripts for Basic Operations. Second Part Contains how to perform Retrofit Operations in Android. Architecture of Retrofit Web Service We need 3 Things for Complete Retrofit Architecture. RestAdapter An Interface with all networking methods and parameters. Getter Setter Class to save data coming from server. Project Structure: Create MySQL DataBase and PHP Scripts. Following image shows my database structure. PHP Scripts: I created db_config.php which contains the script to connect DB. <?php /** * Database config variables */ define("DB_HOST", "localhost"); define("DB_USER", "root"); define("DB_PASSWORD", ""); define("DB_DATABASE", "retrofit_exampl...

Download file using Okio in Android

Okio is a library that complements java.io and java.nio to make it much easier to access, store, and process your data. Simply Okio is a modern I/O API for Java.  In this post, we will see how to download image or any file using Okio. Okio is component for OkHttp Coding Part Create a new project in Android Studio. Add following dependencies to your  app-level  build.gradle  file. compile 'com.squareup.okhttp3:okhttp:3.6.0' Don't forget to add the following permission in your AndroidManifest.xml <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> Implementation Paste the following code in your Activity and Here, I have kept as MainActivity.java public void downloadImg(View view) { try { Request request = new Request.Builder() .url(imageLink) .build(); new OkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFail...