Update Data in SQLite Database

In this tutorial, we will learn about how to Update data in SQLite Database. In the last tutorial, we have learned how to fetch data from the SQLite database. In this tutorial, we will update existing contacts. We will show a popup with options update and delete when a user will click on the list item. If a user will choose update option then we will show a new activity called UpdateContact where a user can update contact.

First of all, we will show and popup when a user will click on an item of listView. To show popup first step is to add make a new file in res/menu (if there is no menu resource folder create a new menu folder by right-clicking on res) with options check this code:

Menu XML code:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/update"
        android:title="Update" />
    <item android:id="@+id/delete"
        android:title="Delete"
        />
</menu>

After this we will write code in MainActivity to show popup on list item click and to open UpdateContact activity on choose of Update option in popup.

MainActivity Java Code:

public class MainActivity extends AppCompatActivity {

    ListView listView;
    DatabaseHelper databaseHelper;
    List<contactmodel> contactList=new ArrayList<contactmodel>();
    int i=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView);

        databaseHelper = new DatabaseHelper(getApplicationContext());

        Cursor cursor = databaseHelper.getData();

        String namesArray[] = new String[cursor.getCount()];

        while (cursor.moveToNext()) {
            namesArray[i] = cursor.getString(cursor.getColumnIndex("NAME"));
            contactList.add(new ContactModel(cursor.getInt(cursor.getColumnIndex("ID")),cursor.getString(cursor.getColumnIndex("NAME")),cursor.getString(cursor.getColumnIndex("CONTACT"))));
            i++;
        }

        ArrayAdapter<string> arrayAdapter = new ArrayAdapter<>(getApplication(), android.R.layout.simple_list_item_1, namesArray);
        listView.setAdapter(arrayAdapter);


        listView.setOnItemClickListener(new ListView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<!--?--> adapterView, View view,final int i, long l) {
                PopupMenu popup = new PopupMenu(getApplicationContext(), view);
                MenuInflater inflater = popup.getMenuInflater();
                inflater.inflate(R.menu.popup_menu, popup.getMenu());


                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                       switch (item.getItemId()){
                           case R.id.update:
                               Intent intent=new Intent(getApplicationContext(),UpdateContact.class);
                               intent.putExtra("ID",contactList.get(i).getId());
                               intent.putExtra("NAME",contactList.get(i).getName());
                               intent.putExtra("CONTACT",contactList.get(i).getNumber());
                               startActivity(intent);
                               break;
                           case R.id.delete:
                               break;
                       }

                       return true;
                    }
                });
                popup.show();
            }
        });

    }
}

Now we will write code in layout file of UpdateContact activity. Check this code:

UpdateContact Activity XML Code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".UpdateContact">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/nameET"
        android:hint="Please Enter Name"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/contactET"
        android:hint="Please Enter Contact Number"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/updateContactB"
        android:text="Update Contact"/>

</LinearLayout>

Now we will define a new method in DatabaseHelper to update contact information. check this code:

DatabaseHelper class code:

public class DatabaseHelper extends SQLiteOpenHelper {

    //writing database name
    private static final String DATABASE_NAME = "PhoneBook.db";
    //writing table name
    private static final String TABLE_NAME = "Contacts_Table";


    //Constructor here
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }


    //On create and onUpgrade these two are abstract methods in SQLiteOpenHelper class
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        //use this execSQL method to create new table in database
        sqLiteDatabase.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT , CONTACT TEXT )");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }


    //Creating this method to insert data in the table
    public boolean insertData(String name, String contact) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("NAME", name);
        cv.put("CONTACT", contact);

        long result = db.insert(TABLE_NAME, null, cv);

        if (result == -1) {
            return false;

        } else {
            return true;
        }
    }


    //getData method to fetch data from SQLite database
    public Cursor getData() {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_NAME;
        Cursor cursor = db.rawQuery(query, null);
        return cursor;
    }


    //updateData method to update contact info
    public int updateData(int id, String name, String contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("NAME", name);
        contentValues.put("CONTACT", contact);
        int i = db.update(TABLE_NAME, contentValues, "ID =" + id, null);
        return i;
    }
}

Now we will write code in java file of UpdateContact activity to update contact information in SQLite database.

UpdateContact Activity Java Code:

public class UpdateContact extends AppCompatActivity {

    EditText nameET, contactET;
    Button updateContactB;
    DatabaseHelper databaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_contact);

        nameET=(EditText)findViewById(R.id.nameET);
        contactET=(EditText)findViewById(R.id.contactET);
        updateContactB=(Button)findViewById(R.id.updateContactB);

        databaseHelper=new DatabaseHelper(getApplicationContext());

        Bundle bundle=getIntent().getExtras();

        final int id=bundle.getInt("ID");
        String name=bundle.getString("NAME");
        final String contact=bundle.getString("CONTACT");

        nameET.setText(name);
        contactET.setText(contact);

        updateContactB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                databaseHelper.updateData(id,nameET.getText().toString(),contactET.getText().toString());
                startActivity(new Intent(getApplicationContext(),MainActivity.class));
            }
        });

    }
}

 

Spread the love
Scroll to Top