Saturday, June 27, 2015

Inserting value into database in android


The Android SDK includes the open source SQLite database engine and the classes needed to access it. SQLLiteOpenHelper class manages the access to the database. The following methods should be implemented as needed:

onCreate: this method is called the first time the database is opened by your application.
onUpdate: this method is called when your application is upgraded and the version number has changed.

The getReadableDatabase method of the helper is called if we need to read data and the getWritableDatabase method is called if we need to read and write data.

To read from a database, we use the query() method. The results of the query are returned in a Cursor object.

There is a main activity, which contains an EditText, Button and a TextView. The EditText accepts Blood Sugar reading, on clicking the button the value will be inserted into the SQLite database and based on the blood sugar reading, a text will returned which is displayed in the TextView,

The layout of the main activity is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:weightSum="1">
    <LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:weightSum="1" android:layout_height="wrap_content" android:orientation="vertical" android:layout_weight="0.71">
        <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:text="ENTER THE READING" android:layout_height="wrap_content" android:layout_weight="0.06"></TextView>
        <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editText1" android:layout_weight="0.10">
            <requestFocus></requestFocus>
        </EditText>
        <TextView android:id="@+id/textView4" android:text="" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0.06"></TextView>
        <Button android:text="SUBMIT" android:id="@+id/button1" android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_weight="0.09"></Button>
        <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_weight="0.06" android:text="" android:layout_height="wrap_content"></TextView>
        <TextView android:id="@+id/textView2" android:layout_width="match_parent" android:layout_weight="0.26" android:layout_height="wrap_content"></TextView>
    </LinearLayout>
</LinearLayout>



The main activity is as follows:

public class BloodSugarReading extends Activity implements OnClickListener {
       EditText inputContent1;
       TextView status;
       private SQLiteAdapter mySQLiteAdapter;

       @Override
       public void onClick(View v) {
              // TODO Auto-generated method stub
              String userId = “A101”;
              String sugarLevel = inputContent1.getText().toString();
              String date = DateFormat.getDateTimeInstance().format(new Date());
              String statusText= mySQLiteAdapter.insertdata(userId, sugarLevel, date);
              Log.i("returnd", "status" + statusText);
              status.setText(statusText);
       }

       public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.sugar);
              Button button = (Button) findViewById(R.id.button1);
              button.setOnClickListener(this);
              inputContent1 = (EditText) findViewById(R.id.editText1);
              status = (TextView) findViewById(R.id.textView2);
              mySQLiteAdapter = new SQLiteAdapter(this);
              mySQLiteAdapter.openToWrite();
       }

}


All the database part is put together in a single class. The activities just have the call to the database layer. The SQLiteAdapter class is as follows: 

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

public class SQLiteAdapter {

       public static final String DATABASE_NAME = "DB_HEALTHDATA";
       public static final String TABLE_1 = "BLOODSUGAR";
       public static final int DATABASE_VERSION = 1;
       public static final String KEY_ID = "_id";
       public static final String KEY_USER_ID = "USER_ID";
       public static final String KEY_BLOOD_SUGAR = "BLOODSUGAR_LEVEL";
       public static final String KEY_DATE = "DATE";

       private static final String SCRIPT_CREATE_DATABASE = "create table "
                     + TABLE_1 + " (" + KEY_ID + " integer primary key autoincrement, "
                     + KEY_USER_ID + " text not null," + KEY_BLOOD_SUGAR
                     + " text not null," + KEY_DATE + " text not null);";

       private SQLiteHelper sqLiteHelper;
       private SQLiteDatabase sqLiteDatabase;

       private Context context;

       public SQLiteAdapter(Context c) {
              context = c;
       }

       public SQLiteAdapter openToRead() throws android.database.SQLException {
              sqLiteHelper = new SQLiteHelper(context, DATABASE_NAME, null,
                           DATABASE_VERSION);
              sqLiteDatabase = sqLiteHelper.getReadableDatabase();
              return this;
       }

       public SQLiteAdapter openToWrite() throws android.database.SQLException {
              sqLiteHelper = new SQLiteHelper(context, DATABASE_NAME, null,
                           DATABASE_VERSION);
              sqLiteDatabase = sqLiteHelper.getWritableDatabase();
              return this;
       }

       public void close() {
              sqLiteHelper.close();
       }

       public String insert(String userID, String bloodSugar, String date) {
              int sugarLevel = 0;
              String status;
              String insertQuery = "insert or replace into SUGARDATA                    (USER_ID, BLOODSUGAR_LEVEL, DATE) values ("+ "'"+ userID + "'"+ ",'"
                           + bloodSugar+ "'"+ ",'"+ date + "')";
              Log.i("The formed SQL ", "Query is" + insertQuery);
              sqLiteDatabase.execSQL(insertQuery);
              String selectQuery = "select BLOODSUGAR_LEVEL from SUGARDATA where DATE='"
                           + date + "'";
              Cursor bloodSugarLevel = sqLiteDatabase.rawQuery(selectQuery, null);
              while (bloodSugarLevel.moveToNext()) {
                     sugarLevel = bloodSugarLevel.getInt(0);
                     Log.i("value", "bloodSugarLevel" + bloodSugarLevel);
              }
              if (sugarLevel >= 130) {
                     status = "CONSULT DOCTOR AS SOON AS POSSIBLE";
              } else if (sugarLevel >= 80 && sugarLevel <= 100) {
                     status = "NORMAL LEVEL";
              } else if (sugarLevel > 100 && sugarLevel <= 129) {
                     status = "CONTROL YOUR SUGAR LEVEL";
              } else {
                     status = "LOW SUGAR LEVEL";
              }
              return status;
       }

       public class SQLiteHelper extends SQLiteOpenHelper {

              public SQLiteHelper(Context context, String name,
                           CursorFactory factory, int version) {
                     super(context, name, factory, version);
              }

              @Override
              public void onCreate(SQLiteDatabase db) {
                     // TODO Auto-generated method stub
                     db.execSQL(SCRIPT_CREATE_DATABASE);
              }

              @Override
              public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                     // TODO Auto-generated method stub
              }
       }

}

No comments:

Post a Comment