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
              }
       }

}

Tuesday, June 23, 2015

Passing data from one activity to another

To pass data from one activity to another, the putExtra() method of Intent object can be used.
Here, there are two activities, Activity1 and Activity2.
Activity1 contains an EditText and a Button. On clicking the button, the value entered in the EditText should be passed to Activity2 and the value will be displayed in a TextView.

All the activities in the project needs to be defined in the manifest file. The main activity will be defined in manifest by default. The Activity2 needs to included in the manifest file as follows:

    </activity>
       <activity android:name="Activity2"></activity>
    </application>


To enable button click, the Actvity1 needs to implement the OnClickListener and have to bind the click event to the button.

public class Activity1 extends Activity implements OnClickListener {
     @Override 
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity1);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
     } 
 
     @Override 
     public void onClick(View v)
     {
       // TODO 
     }
} 

We can use the puExtra() method of Intent object to pass data from one Activity1 to Activity2. Data is passed as extras and as key,value pairs. Here the key is 'text1' and is defined as below: 

public static final String text1="text1";

To get the value of text entered in the EditText the getText() method is used. The getText() returns a SpannableString so either while passing the data or while retrieving the data we need to convert it to string else will result in the following exception:
java.lang.ClassCastException: android.text.SpannableString 
cannot be cast to java.lang.String

To pass data on button click, the following code is used. 

   @Override 
   public void onClick(View v)
   {
      Intent i = new Intent(this,Activity2.class);
      EditText textField   = (EditText)findViewById(R.id.editText);
      i.putExtra(text1,textField.getText());
      this.startActivity(i);
   }

Here 'text1' is the key that is passed from Activity1 and it value is the text entered. From Activity2, need to fetch the value of the key and set it to the TextView.

public class Activity2  extends Activity {
    @Override 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity2);
        String str="";
        Intent intent = getIntent();
        if (null != intent) {
            str = intent.getExtras().get(text1).toString();
        }
        TextView textValue = (TextView) findViewById(R.id.textView);
        textValue.setText(str);
    }


 To make the key available in Acticity2 we need to import it as follows:

   import static com.example.athira.example1.Activity1.text1;
 
To avoid the ClassCastException mentioned above, while retrieving the data the toString() method is used.

Wednesday, June 20, 2012

Client Server Communication in Android


Here the client is the android mobile and java app is acting as the server. The client code snippet is as follows:

Socket sock=null;
       PrintStream ps=null;
System.out.println(" Trying to connect");
                       
       try
       {
              InetAddress ip =InetAddress.getByName("localhost");
              sock=new Socket("112.207.67.208",1052);//give the ip and port no:
              PrintWriter out = new PrintWriter(new BufferedWriter(new
              OutputStreamWriter (sock.getOutputStream())), true);
               out.println(“Hellooo…”);
               sock.close();  
       }
       catch(SocketException e)
       {
              System.out.println("SocketException " + e);
       }
       catch(IOException e)
       {
              System.out.println("IOException " + e);
       }



The java server code is as follows:

public class Server
{
public static final int port = 1052;
public static void main( String args[])
{
Socket sock = null;
ObjectInputStream in;
String message="";
System.out.println(" Wait…… ");
try
{
ServerSocket sersock =  new ServerSocket(port);
System.out.println("Server Running  :"+sersock);
try
{
while(true)
{
sock = sersock.accept();
System.out.println("Client Connected  :"+ sock);
in = new ObjectInputStream(sock.getInputStream());
try
{
message = (String)in.readObject();
System.out.println(message);                   
}
]
catch(ClassNotFoundException classnot){
System.err.println(“Unknown data format");
}
}
sock.close();
}
catch(SocketException se)
{
System.out.println("Server Socket Exception  "+se.getMessage());
}
}
}