Wednesday, 27 May 2015

How to create SQLite table in android


   Here I am going to explain how to create SQLite table in android


Step 1).DataBaseHelper Class
 
package com.createtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHelper extends SQLiteOpenHelper 
{
static final String DATABASE_NAME = "groupchat.db";
static final int DATABASE_VERSION = 1;
private final Context context;
public static final String TABLE_MESSAGES = "messages";

public DataBaseHelper(Context _context) {
super(_contextDATABASE_NAME , null, DATABASE_VERSION );

this.context_context;
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table messages (_id integer primary key autoincrement,                                                         text,userid integer, fromUsermsg text);");
}

@Override
public void onUpgrade(SQLiteDatabase db int oldVersion, int newVersion)
         {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MESSAGES);

onCreate(db);
}

public void insertvalues() {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues Values = callForValues();
db.insert("messages", null, Values );

}

private ContentValues callForValues() {
ContentValues values = new ContentValues();
values .put("msg", "hi");
values .put("userid", 1);
values .put("fromUser", "Dhina");

return values ;

}

}

Step 2).Activity Class

package com.createtable;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

public class MainActivity extends Activity {

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

DataBaseHelper db  = new DataBaseHelper(getApplicationContext());
db .insertvalues();
}

}

Happy Coding:)