22.1 C
New York
Friday, August 19, 2022

SQLite Database Update in Android

- Advertisement -

Please follow the below steps in order to update data in SQLite database using our Android app:

Step 1) First add one more button and this button we are going to use to update the data, so I’m going to change the name of the button as an update.

Step 2) And one more thing we want to do is, if you remember our database table contains four columns. First one was id, the second one was name, surname and the marks scored by the students. And to update the data we need a unique reference of the row so that we can tell SQLite that we want to delete the data from this row.

Because names can be same so if you want to change the name of one partner which shares the name with the other person then the data can be changed for both the names if you don’t know what is the unique you know row or unique column in this, So id we have defined as a unique column for this database table.

Step 3) Now we need to create a function in our database helper .javaclass which we have created in the last tutorial so go to the database helper .javafile and in here till now we have created insert data and get all data function right. Now we will create one more function here and we will call it as updateData.

So it will be public and it’ll return boolean and It’s going to take four arguments. The First argument we are going to pass here will be string id, second is string name, third is string surname and fourth is string marks.

basically, we want to pass all the four column data to it. Because our table will contain four columns, id, name, surname and marks right.

Step 4) Now in here what we’re going to do is, as we have done inserting data function. First of all, we will create SQLite database instance and then we are going to create an instance of content value.

Step 5) And then as we have done in this insert data function that we’re putting whatever data is passed from the argument to this content value using put. So let’s do it and one more column we need to add here and this will be for column 1 and its id in our case right. Because this contains extra id here. The only difference in update data functions and insert data function is, the method we are going to use now.

Step 6) So just take your database instance now and then call update here. And this update will update whatever argument you pass here. The first argument it takes is the name of your table okay. So give the name if you remember. we have declared table name here right so first argument is the table name right. Second is the content value. So it takes the second argument as a content value so we take this instance of content value and pass it here. The third argument is the condition which we want to pass here. So what we want to do, we want to update data on the basis of for example id because id is our unique primary key here and on the basis of primary key we can differentiate data. So in here we will write id=question. So we will you know ask whatever id is passed using this id parameter we are going to query this and fourth is the value on the basis of which we want to update our data so this is the column name on the basis of which we want to update the data and our column name is id so you can just write here column name, id is equal to and then in here, fourth argument. Lets go inside this update, so hover over control and click and see it takes the fourth argument as the string array right. So we will go back and pass string array here right.

And if everything goes well, we want to return, return to know that if the data is really updated or not.

Step 7) Now this is done, what we are going to do is we are going to move to our main activity .javafile and in here we will declare one more button variable which will be our button for update so button update and then we are going to take this button instance and we will cast it as a button using the id.

So go to the onCreate method where you have type casted all other tools or widgets and cast this button. 

Complete Code for Database Update in Android

app-java-Database.java

package com.example.programmingknowledge.sqliteapp;

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

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "Student.db";
    public static final String TABLE_NAME = "student_table";
    public static final String COL_1 = "ID";
    public static final String COL_2 = "NAME";
    public static final String COL_3 = "SURNAME";
    public static final String COL_4 = "MARKS";
    
    public DatabaseHelper (Context context) { 
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + TABLE_NAME +" ( ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT, SURNAME TEXT,MARKS INTEGER)");
    }

    @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
        db.execSQL("DROP TABLE IF EXIST " +TABLE_NAME);
        onCreate(db);
    }

    public boolean insertData(String name, String surname, String marks) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2,name);
        contentValues.put(COL_3,surname);
        contentValues.put(COL_4,marks);
        long result = db.insert(TABLE_NAME,null, contentValues);
        if (result == -1){
            return false;
        }else
        return true;
    }

    public Cursor getAllData(){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
        return res;
    }

    public boolean updateData(String id, String name, String surname, String marks){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_1,id);
        contentValues.put(COL_2,name);
        contentValues.put(COL_3,surname);
        contentValues.put(COL_4,marks);

        db.update(TABLE_NAME, contentValues, "ID = ?", new String[] { id });
        return true;
    }

}

app-java-MainActivity.java

package com.example.programmingknowledge.sqliteapp;

import ...
public class MainActivity extends ActionBarActivity {
    DatabaseHelper myDb;
    EditText editName, editSurname, editMarks, editTextId;
    Button btnAddData;
    Button btnViewAll;
    Button btnviewUpdate;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myDB = new DatabaseHelper(this)
        editName = (EditText)findById(R.id.editText_name);
        editSurame = (EditText)findById(R.id.editText_surname);
        editMarks = (EditText)findById(R.id.editText_Marks);
        editTextId = (EditText)findById(R.id.editText_id);
        btnAddData = (Button)findViewById(R.id.button_add);
        btnViewAll = (Button)findViewById(R.id.button_viewAll);
        btnviewUpdate = (Button)findViewById(R.id.button_update);
        AddData();
        viewAll();
        UpdateData();
    }
    public void AddData(){

        btnAddData.setOnClickListener(
                new View.OnCLickListener() {
                    @Override
                    public void onClick(View v) {
                        boolean isInserted = myDb.insertData(editName.getText().toString(),
                            editSurame.getText().toString(),
                            editMarks.getText().toString());
                        if(isInserted == true)
                            Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
                        else
                            Toast.makeText(MainActivity.this,"Data Not Inserted",Toast.LENGTH_LONG).show();
                    }
                }
            );
    }
    public void viewAll() {
        btnViewAll.setOnClickListener(
            new View.OnCLickListener() {
                @Override
                public void onClick(View v) {
                    Cursor res = myDb.getAllData(); 
                    if(res.getCount() == 0) {
                        //show Message
                        showMessage("Error","Nothing Found!!!")
                        return;
                    }
                    StringBuffer buffer = new StringBuffer();
                    while(res.moveToNext()){
                        buffer.append("Id:"+res.getString(0)+"n");
                        buffer.append("Name:"+res.getString(1)+"n");
                        buffer.append("Surname:"+res.getString(2)+"n");
                        buffer.append("Marks:"+res.getString(3)+"nnn");
                    }
                    //Show all Data
                    showMessage("Data", buffer.toString());
                }
            }
            );
    }
    public void showMessage(String title, String Message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(Message);
        builder.show();
    }
    public void UpdateData(){
        btnviewUpdate.setOnClickListener(
                new View.OnCLickListener() {
                    @Override
                    public void onClick(View v){
                        boolean isUpdate = myDb.UpdateData(editTextId.getText().toString(),editName.getText().toString(),editSurame.getText().toString(),editMarks.getText().toString());

                        if(isUpdate == true) 
                            Toast.makeText(MainActivity.this,"Data Updated",Toast.LENGTH_LONG).show();
                        else
                            Toast.makeText(MainActivity.this,"Data Not Updated",Toast.LENGTH_LONG).show();
                    }
                }
            );
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInlater().inflate(R.menu.menu_main, menu);
        return true;
    }
}

 

- Advertisement -

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles