Skip to main content

Writing into an SQLite database(A guide to Android SQLite part 3(a))- x-droov

Now that you can create a database, part 3(a) is to teach you how to write records into your database because you can't read records which you haven't written into the database. Writing records in the database is an interesting activity because your app's memory increases during runtime.
There are several methods of writing into the database and we will cover the best methods to use.
If you missed any part, catch up with us by checking on the contents below.

A guide to Android sqlite: contents( course outline)

Part 1: A guide to Android SQLite( part 1: what it is)

The introduction to SQLite and the database working space. A detailed guide of what you can do with it and a wrap-up of what to look out for in an Android SQLite tutorial.

Part 2: A guide to Android SQLite ( part 2: Creating the database)

This is the first thing to learn as you embark on data management. Many will tell you that if you can create a database, you can read an existing database.
That's wrong. In this series, you'll learn both. Or you can navigate to what you want to learn.
Part 3: A guide to Android SQLite ( part 3: Reading and writing into a database)
Now that you can create a database, this article will teach you how to read records from a database and how to write into it.

Part 4: A guide to Android SQLite ( part 4: Displaying content from the database)

Once you have read data, you have to display it. Here you'll learn about using adapters, using other views and creating your own adapters manually.

Part 5: A guide to Android SQLite ( part 5: Reading an existing database)

This is the fun part. We'll drain-out what almost no Android development book will teach you, reading existing SQLite.
I spent long learning this and finally got to what I was looking for. In this part, I will let you know all I learnt and how you can apply it.

Part 6: A guide to Android SQLite ( part 6: how cursors work)

Worried of managing data that you have queried from your database, read this carefully and I will teach you something.
This is the master guide to cursors, cursor loaders and all you need to process your results.

Part 7: A guide to Android SQLite ( part 7: Living with SQLite on your own)

Don't get worried. This is your seal. I'll run you through how to organize SQLite code like a pro and tip you on how you can further deepen your knowledge on SQLite.

Part 8: A guide to Android SQLite ( part 8: SQL - the basics)

The SQL you need to survive. This is the basic guide, but will let you get what you want and leave what you want in a database.

Methods used for writing into a database

1. Using rawQuery

Using rawQuery, we'll use an instance of the SQLiteDatabase class and apply our sql statement to insert data into the database.
db.rawQuery("your query",null);

2. Using execSQL

We use execSQL in the same way as raw query, but it only takes in one argument, the query.
db.execSQL("YOUR_QUERY");

3. Using Android methods

There are other methods like insert(....) which take in a large number of arguments. They are made by Android for those who can't frame queries. Trust me I won't waste time teaching those methods here.
The main reason is that you can't remember all the arguments at once and it wastes time checking your Android pdfs for arguments in a select() function yet you could just use a query.

The SQL "insert into" query

The syntax is simple
INSERT INTO table_name(Columns to insert into) VALUES ( values to insert )
It can also be
INSERT INTO table_name VALUES( ...)
If you are inserting into all columns.
Lets start with a simple example using a button that inserts values we hard coded in our code.

1. Inserting values in SQLite using a simple button

Here you have already prepared values to insert and the user just presses the button and they are inserted.


package com.rea;

import android.database.sqlite.SQLiteDatabase;

import android.database.SQLException;

import android.app.Activity;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;

import android.content.Context;

import android.database.sqlite.SQLiteException;


public class MainActivity extends Activity {

   // Cursor c;

Context cc= this;

public static SQLiteDatabase db;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.layout_main);

        ((Button) findViewById(R.id.button01)).setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                b dbhelp= new b(cc);

                try {

                    SQLiteDatabase db= dbhelp.getWritableDatabase();

                    db.rawQuery("insert into emmy values(50,'takan')",null);

                    

                 

                    //db.close();

                    Toast.makeText(cc, "Successfully created", Toast.LENGTH_SHORT).show();

                } catch (SQLiteException ioe) {

                    //throw new Error("Unable to create database");

               Toast.makeText(cc, "db not created", Toast.LENGTH_SHORT).show();

                }

                try{

                    

               

                }

                catch(SQLException e){

                  Toast.makeText(cc, "query jode", Toast.LENGTH_SHORT).show();  

                }

                

           

            }

        });

    }

}

2. Using an edit text to get user input

Here we add an edittext to our layout with an id "textg". 
When the button is clicked, the program gets the value of the edittext and passes it to our query. You shouldn't forget to escape quotes for the sql to work.
Strings from a java code are not strings in sql so we use".... \""+str" \"..." As you know that backsplashes are for escaping.
The code is the one below. If you need the layout it's given after.


package com.rea;

import android.database.sqlite.SQLiteDatabase;

import android.database.SQLException;

import android.app.Activity;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.widget.EditText;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;

import android.content.Context;

import android.database.sqlite.SQLiteException;


public class MainActivity extends Activity {

   // Cursor c;

Context cc= this;

public static SQLiteDatabase db;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.layout_main);

       

        ((Button) findViewById(R.id.button01)).setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                EditText edt= (EditText) findViewById(R.id.textg);

                String valu=edt.getText().toString();

                b dbhelp= new b(cc);

                try {

                    db= dbhelp.getWritableDatabase();

                    

                    

                 

                    //db.close();

                    Toast.makeText(cc, "Successfully created", Toast.LENGTH_SHORT).show();

                } catch (SQLiteException ioe) {

                    //throw new Error("Unable to create database");

               Toast.makeText(cc, "db not created", Toast.LENGTH_SHORT).show();

                }

                try{

                    

               db.rawQuery("insert into emmy values(50,\""+valu+"\")",null);

                }

                catch(SQLException e){

                  Toast.makeText(cc, "query jode", Toast.LENGTH_SHORT).show();  

                }

                

           

            }

        });

    }

}


Layout for the edittext and button


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
   
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, World!" />
      <EditText
          android:id="@+id/textg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="enter ur text" />
   
         <Button
         android:id="@+id/button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="click" />
   
</LinearLayout>

Thanks for getting to the end. Our guide continues and I encourage you to put any questions in the comments section and also give your experiences with SQLite.
The next sub part of reading and writing into the database is:

Reading, updating and deleting SQLite database records(A guide to Android SQLite part 3(b))- x-droov

We have inserted values into our database, lets read them, remove the unnecessary and replace some. It'll be a great job, won't it?

AUTHOR

Emmy Jayson x-droov



Comments