Miyerkules, Enero 23, 2013

Android Database Programming basics (THIRD AND FINAL STEP)


 


 Third, Implement the method to insert records and read records from the SQLite db
 

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.content.Context;
import com.eglobiotraining.DbHelper;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.database.Cursor;
import android.widget.TextView;
import android.widget.EditText;
public class DbSample extends Activity {
    DbHelper dh;
    SQLiteDatabase dbwrite;
    SQLiteDatabase dbread;
   
    EditText input;
    TextView output;
   
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
           
        dh = new DbHelper(getApplicationContext());
        dbwrite = dh.getWritableDatabase();
        dbread = dh.getReadableDatabase();
       
        // you cannot put the findViewById here, it causes errors
       
        super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
    }
   
   
    public void recAdd(View v) {
        input = (EditText) findViewById(R.id.todoedit);
        output = (TextView) findViewById(R.id.tododisplay);
       
        String itemtoadd = input.getText().toString();     
       
        ContentValues cv = new ContentValues();
        cv.put("item", itemtoadd);
        dbwrite.insertOrThrow("todo",null,cv);
       
        String temptext = (String) output.getText();
       
        //Write the dbExtraction routine here
       
        //temptext = temptext + "\n";
        output.setText(getTodos());
       
    }
   
    private String getTodos() {
       
        String cols[] = {"item"};
        StringBuilder sb = new StringBuilder("");
        Cursor cursor = dbread.query("todo",cols,null,null,null,null,"item");
        startManagingCursor(cursor);
       
        while(cursor.moveToNext()) {
            sb.append(cursor.getString(0));
            sb.append("\n");
        }
        return sb.toString();
    }
}
The DBSample class is a regular Activity class. It's bad coding practice to embed the database logic in the UI, but were just starting out to learn about database programming in Android, we will let it pass for now---if we partition this app properly and use the nice design patterns, we will have more code to deal with (and to understand).
We instantiated the DbHelper class so that we can create the database during our first run of this app. We also used the DbHelper to create 2 SQLiteDatabase objects, one for reading (dbread) and another for writing (dbwrite).
The recAdd method starts out by getting the object references to the EditText and TextView components, todoedit and tododisplay respectively.
Once we extracted whatever the user typed inside the EditText (via getText() method), we stored it in the "itemtoadd" String variable.
The ContentValues object is some sort of a Dictionary data structure (key value pair), this data structure is required by the insert method of the SQLiteDatabase object, that is why we used it to wrap the string data we got from the EditText. You don't have to use the insertOrThrow method if you don't want to, you can insert a record to the database using raw SQL. If you pass an "INSERT INTO todo …" inside an execSQL method, that will do the job just as well.
Run the code
Compile and Test *ant debug install. The onCreate()* method of DbHelper should kick in the first time your app issues a db related command.

Walang komento:

Mag-post ng isang Komento