Featured post

Displaying Multiple Fragments in a single Activity

Saturday, 23 July 2016

Storage Mechanisms in Android Application-1

#Tutorial 1 (Creating Database and table)
Android provides several options to store persistent data. Some of them are Internal Storage, External Storage, SQLite Database and Shared Preferences. In this tutorial, i will discuss about SQLite Database to store persistent data.

Important Points:
  • SQLite is an open source database
  • SQLite supports standard relational database features
  • Each android device comes up with built in SQLite database implementation
  • Data stored in database remains private to other applications
  • To create SQLite database, you need to create a subclass of SQLiteOpenHelper class.
Let's us go for a simple demo inheriting SQLiteOpenHelper class to create a database and a table inside it. To start with, create a new android application project and assign the names as per IDE defaults. I assume that, the name of the Activity is MainActivity and layout_name is activity_main.xml.

activity_main.xml-----
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="vertical">

<EditText
android:id="@+id/editText1"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:hint="Enter Book Name"/>

<EditText
android:id="@+id/editText2"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:hint="Enter Book Author"/>

<Button
android:id="@+id/submit"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="Submit"/>

</LinearLayout>


MainActivity.java---

public class MainActivity extends Activity
{
DatabaseHelper myDb;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb=new DatabaseHelper(this);
}
}

DatabaseHelper.java---

public class DatabaseHelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME="Library.db";
public static final String TABLE_NAME="Books";
// constructor with one argument
public DatabaseHelper(Context context)
{
super(context,DATABASE_NAME,null,1);
SQLiteDatabase db=this.getWritableDatabase();
}
// implementing default methods
@Override
public void onCreate(SQLiteDatabase db)
{
db.exexSQL("create table"+TABLE_NAME+ "(id number primary key autoincrement , book_name text, book_author text)");
}
@Override
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS"+TABLE_NAME);
onCreate(db);
}
}

So running this application, will only create the database and the table, To learn how to insert data inside the table follow the next series of this tutorial. 

No comments:

Post a Comment