Wednesday, March 28, 2012

How to Connect SQLite Database in Android & A Simple App: "Accessing Data With Android Cursors"

Hi Everyone! I'd showed you how to do an application on Android in the last article. This one is going to be about connection SQLite database and access data with cursors.

If you want to use your data or something else, should connect a database. Using SQLite on Android is so simple. There are so much SQLite Editor but I will use Firefox SQLite Manager in this article. For that, first open your Firefox Browser, then download SQLite Manager and as result go this directory: Tools/SQLite Manager. After that, you can range database. 

And now, it's time to ready our files we use to. Just follow this directories:


Documents:
1- src/DatabaseActivity.java
2- src/Database.java
3- layout/data.xml

We need "database.java" file, that's why is gotta a table on database. If you want to add something, I must have a database. Now, code Database.java file.
package database.connection;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class Database extends SQLiteOpenHelper {
 private static final String MYDATABASE = "names";
 private static final int VERSION = 1;

 public Database(Context connection) {
  super(connection, MYDATABASE, null, VERSION);
 }

 @Override
 public void onCreate(SQLiteDatabase db) {
  db.execSQL("CREATE TABLE mynames(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);");
 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
  db.execSQL("DROP TABLE IF EXIST mynames");
  onCreate(db);
 }
}

So, we've just created a database, as called MYDATABASE. Table's name is "names". There are two fields on it: "id and name". As you know that is all about SQL. If you know SQL, you can get it easily. id field is an integer piece of table. The other one is a text field.

We'got a database and a table of this. The form we can add data is what we need exactly. For that, gotta compose a Android XML File. This file will have a textfield widget and a button widget, that's it! Let's do data.xml file!


    
        
    

    

If you want, just look what we got up right now. We created a database, a table of this database and form widgets. I can add a data after make this platform up:) Let's do our platform: DatabaseActivity.java file
package database.connection;
//Those are included by the system 
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
public class DataBaseActivity extends Activity {
    private DB names;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.data); //including layout/data.xml file
        names = new DB(this);
        final EditText name=(EditText) findViewById(R.id.editText1);
 
        Button senddata=(Button) findViewById(R.id.senddata);
 
        senddata.setOnClickListener(new View.OnClickListener() {
 
            public void onClick(View v) {
                    try{
                     AddDATA(name.getText().toString());
                     Cursor cursor = ShowDATA();
                     ShowDATA(cursor);
                     }
                     finally{
                     names.close();
                    }
            }
        });
 
    }
    
    private void AddDATA(String ResultName){

    SQLiteDatabase db = names.getWritableDatabase();
    ContentValues datas = new ContentValues();
    datas.put("name", ResultName);
    db.insertOrThrow("ournames", null, datas);
    }

    private String[] SELECT = {"id", "name"};

    private Cursor ShowDATA(){
    SQLiteDatabase db = names.getReadableDatabase();
    Cursor cursor = db.query("ournames", SELECT, null, null, null, null, null);

    startManagingCursor(cursor);
    return cursor;
    }

    private void ShowDATA(Cursor cursor){
        StringBuilder builder = new StringBuilder("RESULTS!:\n");

        while(cursor.moveToNext()){

        String whatthenameis = cursor.getString((cursor.getColumnIndex("name")));
        builder.append(whatthenameis).append("\n");
        }

        TextView text = (TextView)findViewById(R.id.textView1);
        text.setText(builder);
    }
}
Generally, coder need to use a database, while saving data. We use SQLite Database on Android'cuz it's simple. Here, SQL is as you know before. "SELECT" command using also. By the way, if you want to check your db file out, just go this directory on Eclipse: file explorer/data/[your project name]/database
Write Something
That's it! We can add and save our datas, through SQLite Database on Android.
When you write something and click button, data will been saved and can show it on the screen. We'll you guys next article!

39 comments:

  1. hi,. I cant download the firefox sqlite manager.. can you give me a copy of it?

    ReplyDelete
    Replies
    1. Help This url: https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/

      Delete
  2. Did you try this one? https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/

    ReplyDelete
  3. hi,

    Please can you help me in, "how the data is going to store in mobile phone?"

    Also can you provide simple code application which provide functionality of "Addition, Deletion , Updation , Search Records in a SQLite database".

    ReplyDelete
    Replies
    1. hi indra,

      In this article, your data is already going to store in android machine. Just attention about your .db file. Did you create a database file with Firefox Sql Manager?

      Well, i'll provide codes about deletion and updation after a while. This article also has addition by the way.

      Delete
  4. This comment has been removed by the author.

    ReplyDelete
  5. private DB names; this line is error for me

    ReplyDelete
  6. Can you please give me more information?

    ReplyDelete
  7. private DB names;
    datatype error:


    What is DB ?
    can you explain how to use firefor Sql Lite...? if you dont mind...

    i am new to Android...

    i got three files.. but still says the datatype undefined for DB and names..
    that lines or errror.
    plz reply soon...

    mail ID:baskar.atr@gmail.com

    ReplyDelete
  8. I also have the same error.. "DB cannot be resolved to a type"..
    what may be the reason..
    please reply...

    ReplyDelete
    Replies
    1. You have to be sure that you've created and defined database file on it. I dont know whether which db editor did u use, but you must connect files on eclipse and db editor somehow. I used firefox sqlite manager for example.

      Can you show me your screen view?

      Delete
  9. How can I connect dbfiles to eclpise? I got the same error. Please help. Thanks

    ReplyDelete
  10. How can I connect datbase files in netbeans, can you help me?

    ReplyDelete
  11. private DB names; returns an error

    ReplyDelete
    Replies
    1. Like i said before, you have to be sure that you've created and defined database file on your manager. Let me see what kind of error on the screen?

      Delete
  12. Its a Database.java file
    He defined it as DB. Dont get confused. Just change DB by Database.

    ReplyDelete
  13. where this database is stored in eclipse?
    when i open file explorer nothing is there.
    but still i can access the data from db.
    i do not know where it is stored.
    can any help me?

    ReplyDelete
  14. I got error(logcat) in R.layout.activity_main...
    force close

    ReplyDelete
  15. Hi,
    thanks for your quick tutorial. It's very useful for beginners.

    ReplyDelete
  16. I can't get this to work, I've done the database "MYDATABASE.db" and placed it in assets/ but when i run the app it says "Unfortionally *** have stopped.".

    ReplyDelete
  17. Unfortunately, "myApp-name" has stopped.....

    I think it is due to database connectivity. I've just developed simple-small apps of android before it and first time developing the app related to database connectivity. Please guide me
    I've downloaded, installed and now opened the SQLite-Manger but did not do anything else and also having no idea about anything else

    ReplyDelete
  18. creating coding in eclipse is fine.
    creating database is fine.
    But how to access it???
    Whether we wanna export the database to asset folder of our project????
    or what else.....

    ReplyDelete
  19. sir,,,i got the error "DB cannot be resolved to a type".
    i am unable to find out this,,what is the problem in this,,?
    please help me out through this problem,,bcoz i am nt getting any idea to resolve this
    problem,
    m emailid is= rachita.baderai22@gmail.com

    ReplyDelete
  20. Thanks, Everything went fine for me

    ReplyDelete
  21. Replies
    1. channge DB by your another .class file name

      Delete
  22. May U post the exercise code please?
    TNX A LOT!!!

    RedLuck

    ReplyDelete
  23. hi sir,your explanation is so good,in programming,while declaring var/fun,give some explanation about that for avoiding the confusions.I also got the same problem in
    DatabaseActivity.java file at "private DB names;"

    ReplyDelete
  24. My question is how Firefox SQLite database is connected to eclips...

    ReplyDelete
  25. 09-11 19:05:33.519: E/AndroidRuntime(21454): android.database.sqlite.SQLiteException: no such table: ournames: , while compiling: INSERT INTO ournames(name) VALUES(?);
    .. whts d problem..?

    ReplyDelete
  26. hi, the code it itself has some typos. "private DB names" and "names = new DB(this);" in the database activity should have been "private database names" and "names = new database (this);".

    And the "ournames" in the code should have been the name of the table, as in this tutorial, which should be "names". Hope this helps.

    ReplyDelete
  27. how can I browse the data in SQLite? to check if data was really saved on the database? thank you :)

    ReplyDelete
  28. How can I connect dbfiles to eclpise? I got the same error. Please help.

    ReplyDelete
  29. great tutorial bro, keep sharing :D owh ya i want to remote my database sqlite for update,delete,etc data via server, how to do it bro? maybe you know :)

    ReplyDelete
  30. how to build a table in UI and how to connect it to data base.. is any link between them .

    ReplyDelete
  31. sir in my code id is not getting recognized by the eclipse can you please help me with this (ID of text field is textView1 and Button ID is senddata)

    ReplyDelete

Thanks