Wednesday 16 January 2013

Simple SQLiteDatabase Example in Android

ScreenShots:
activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

</LinearLayout>

MainActivity.java:

package com.ram.simplesqlitedatabase;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {

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

SQLiteDatabase db = openOrCreateDatabase("ramsdb", MODE_PRIVATE, null);

db.execSQL("create table if not exists sampletable(firstname varchar,lastname varchar)");

db.execSQL("insert into sampletable values('ram','babu')");

Cursor c = db.rawQuery("select * from sampletable", null);

c.moveToFirst();

//Getting data using column name
String fname = c.getString(c.getColumnIndex("firstname"));

//Getting data using column index number
String lname = c.getString(1);

Toast.makeText(getApplicationContext(), "firstname :"+fname+"\n"+"lastname :"+lname, Toast.LENGTH_LONG).show();

}



8 comments:

  1. wow thanks for give this information

    ReplyDelete
  2. Thanx...but can we do the same for EditTexts value?

    ReplyDelete
    Replies
    1. yep.
      All you have to do is to output the string to a TextView.
      like
      Text1.setText("firstname :"+fname+"\n"+"lastname :"+lname);

      Delete
  3. Not working for me, I get a blank display on the emulator. Any ideas?

    ReplyDelete
    Replies
    1. Hi Eamon...can you post the code....so that i can see

      Delete
  4. can you post the code....so that i can see

    ReplyDelete
  5. Hi can you please tell me how to do login activity with session and dashboard.please give me info or any link

    ReplyDelete
  6. Very simply,,,
    Can you develop it,, So User can see the data that was
    entered

    ReplyDelete