Wednesday 7 August 2013

Android SQLite Database Demo

1 comment


Today we will discussed about SQLite Database in android.
android.database Package have all necessary classes for working with database. android.database.sqlite Package contains the SQLite related classes.
To extends the functionality of SQLite in your application we have to extends SQLiteOpenHelper.
This class have two methods
onCreate() – will create database for the first time.
onUpdate() – will be used to update the existing database.


Lets Begins.
Step 1:-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp"
   
  >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <EditText
        android:id="@+id/editText_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:ems="10" >
       
    </EditText>
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Marks"
        android:layout_marginTop="10dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <EditText
        android:id="@+id/editText_marks"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_marginTop="10dp"
        android:inputType="phone" >
   
    </EditText>
    <Button
        android:id="@+id/buttonAddDetail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Add Details" />
</LinearLayout>
Step 2:- create database via DatabaseManager Class
package com.arpit.sqlitedemo;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseManager extends SQLiteOpenHelper {
    private Context context;
    private static String DB_NAME = "SampleDatabase";
    private static int DB_VERSION = 1;
    public static final String TABLE_STUDENT = "Student";
   

    public DatabaseManager(Context context) {
        // TODO Auto-generated constructor stub
        super(context, DB_NAME, null, DB_VERSION);
        this.context = context;
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE Student(    Id INTEGER NOT NULL PRIMARY KEY, Name TEXT NOT NULL, Marks TEXT NOT NULL)");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE " + TABLE_STUDENT + "IF EXISTS");
        this.onCreate(db);
    }
}
Step 3:- Create MainActivity Class
package com.arpit.sqlitedemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
    EditText etName, etMarks;
    Button btn_add;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etName = (EditText) findViewById(R.id.editText_name);
        etMarks = (EditText) findViewById(R.id.editText_marks);
        btn_add = (Button) findViewById(R.id.buttonAddDetail);
        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isInserted = false;
                String name = etName.getText().toString();
                String marks = etMarks.getText().toString();
                if (etName.getText().length() <= 0) {
                    Toast.makeText(MainActivity.this, "Please Enter name",
                            Toast.LENGTH_SHORT).show();
                } else if (etMarks.getText().length() <= 0) {
                    Toast.makeText(MainActivity.this, "Please Enter Marks",
                            Toast.LENGTH_SHORT).show();
                } else {
                    DatabaseController controller = new DatabaseController(
                            MainActivity.this);
                    isInserted = controller.addValuesIntoTable(name, marks);
                    if (isInserted) {
                        Toast.makeText(getBaseContext(),
                                "Successfuly Inserted", Toast.LENGTH_SHORT)
                                .show();
                    }
//                    etName.setText("");
//                    etMarks.setText("");
                }
            }
        });
    }
}
Step 4:- Create a controller class ie DatabaseController.java which will put the information in the database via the help of ContentValues.

package com.arpit.sqlitedemo;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseController {
    private Context context;
    public DatabaseController(Context context) {
        // TODO Auto-generated constructor stub
        this.context = context;
    }
    public boolean addValuesIntoTable(String name, String marks) {
   
        boolean inserted=false;
        ContentValues values=new ContentValues();
        values.put("Name", name);
        values.put("Marks", marks);
        try
        {           
        SQLiteDatabase sqlDb=new DatabaseManager(context).getWritableDatabase();
       
        if(sqlDb.isOpen())
        {
            long inserted_row=sqlDb.insert(DatabaseManager.TABLE_STUDENT, null, values);
            if(inserted_row>0)
            {
                inserted=true;
            }
        }
       
        sqlDb.close();
        }
        catch(Exception exception)
        {
            exception.printStackTrace();
        }
       
        // TODO Auto-generated method stub
        return inserted;
       
    }
   
}



Screenshot_2013-08-07-15-59-19Screenshot_2013-08-07-16-00-09Screenshot_2013-08-07-16-24-19

Catch Me On: CreateAppFaster.com

1 comment:

  1. Your Affiliate Money Making Machine is waiting -

    Plus, making profit with it is as easy as 1-2-3!

    Here is how it all works...

    STEP 1. Tell the system what affiliate products you want to promote
    STEP 2. Add PUSH button traffic (this LITERALLY takes 2 minutes)
    STEP 3. See how the system explode your list and upsell your affiliate products on it's own!

    Are you ready to make money automatically??

    Click here to activate the system

    ReplyDelete