Friday, February 21, 2014

CRUD operation in Android

MainActivity.java 
============

package com.crudoperation;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

EditText etName, etRollno, etClass, etRowID;
Button btnAdd, btnView, btnDelete, btnUpdate, btnViewById;

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

etName = (EditText) findViewById(R.id.etName);
etRollno = (EditText) findViewById(R.id.etRollno);
etClass = (EditText) findViewById(R.id.etClass);
etRowID = (EditText) findViewById(R.id.etRowId);

btnAdd = (Button) findViewById(R.id.btnAdd);
btnView = (Button) findViewById(R.id.btnView);
btnDelete = (Button) findViewById(R.id.btnDelete);
btnUpdate = (Button) findViewById(R.id.btnUpdate);
btnViewById = (Button) findViewById(R.id.btnViewById);

btnAdd.setOnClickListener(this);
btnView.setOnClickListener(this);
btnDelete.setOnClickListener(this);
btnUpdate.setOnClickListener(this);
btnViewById.setOnClickListener(this);

}

public void onClick(View v) {
switch (v.getId()) {
case R.id.btnAdd:

boolean didItWork = true;
try {
String name = etName.getText().toString();
String rollno = etRollno.getText().toString();
String sclass = etClass.getText().toString();

MySQLiteDatabase entry = new MySQLiteDatabase(MainActivity.this);
entry.open();
entry.createEntry(name, rollno, sclass);
entry.close();

etName.setText("");
etRollno.setText("");
etClass.setText("");

} catch (Exception e) {
didItWork = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Dang it!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
} finally {
if (didItWork) {
Dialog d = new Dialog(this);
d.setTitle("Adding!");
TextView tv = new TextView(this);
tv.setText("Success");
d.setContentView(tv);
d.show();
}
}

break;
case R.id.btnView:
Intent i = new Intent(getApplicationContext(),SQLiteView.class);
startActivity(i);
break;
case R.id.btnViewById:
try {
String s = etRowID.getText().toString();
long l = Long.parseLong(s);
MySQLiteDatabase hon = new MySQLiteDatabase(this);
hon.open();
String returnedName = hon.getName(l);
String returnedRollno = hon.getRollno(l);
String returnedClass = hon.getClasss(l);
hon.close();

etName.setText(returnedName);
etRollno.setText(returnedRollno);
etClass.setText(returnedClass);
} catch (Exception e) {

String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Oh Sit!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
break;

case R.id.btnUpdate:
try {
String mName = etName.getText().toString();
String mRollno = etRollno.getText().toString();
String mClass = etClass.getText().toString();

String sRow = etRowID.getText().toString();
long lRow = Long.parseLong(sRow);

MySQLiteDatabase ex = new MySQLiteDatabase(this);
ex.open();
ex.updateEntry(lRow, mName, mRollno, mClass);
ex.close();

etName.setText("");
etRollno.setText("");
etClass.setText("");

Toast.makeText(getApplicationContext(), "Row Updated Successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {

String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Oh Sit!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
break;
case R.id.btnDelete:
try {
String sRow1 = etRowID.getText().toString();
long lRow1 = Long.parseLong(sRow1);
MySQLiteDatabase ex1 = new MySQLiteDatabase(this);
ex1.open();
ex1.deleteEntry(lRow1);
ex1.close();
Toast.makeText(getApplicationContext(), "Row Deleted Successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {

String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Oh Sit!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
break;
}
}

}
SQLiteView
=============
package com.crudoperation;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SQLiteView extends Activity{

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

TextView info=(TextView)findViewById(R.id.tvSQLinfo);

MySQLiteDatabase myDb=new MySQLiteDatabase(this);

myDb.open();
String data=myDb.getData();
myDb.close();
info.setText(data);


}

}

MySQLiteDatabase 
==================
package com.crudoperation;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MySQLiteDatabase {

public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_ROLLNO = "rollno";
public static final String KEY_CLASS = "class";

private static final String DATABASE_NAME = "studentdatabase";
private static final String DATABASE_TABLE = "student";
private static final int DATABASE_VERSION = 1;

private MyDbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;

private static class MyDbHelper extends SQLiteOpenHelper {

public MyDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {

db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME
+ " TEXT NOT NULL, " + KEY_ROLLNO + " TEXT NOT NULL, "
+ KEY_CLASS + " TEXT NOT NULL);"
);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + DATABASE_TABLE);
onCreate(db);
}

}

public MySQLiteDatabase(Context c) {
ourContext = c;
}

public MySQLiteDatabase open() throws SQLException {

ourHelper = new MyDbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();

return this;
}

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

public long createEntry(String name, String rollno, String sClass) {
ContentValues cv = new ContentValues();

cv.put(KEY_NAME, name);
cv.put(KEY_ROLLNO, rollno);
cv.put(KEY_CLASS, sClass);

return ourDatabase.insert(DATABASE_TABLE, null, cv);
}

public String getData() {
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_ROLLNO,
KEY_CLASS };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
null, null);
String result = "";

int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iRollno = c.getColumnIndex(KEY_ROLLNO);
int iClass = c.getColumnIndex(KEY_CLASS);

for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " " + c.getString(iName)
+ " " + c.getString(iRollno) + " " + c.getString(iClass)
+ "\n";
}

return result;
}

public String getName(long l) throws SQLException {
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_ROLLNO,
KEY_CLASS };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
+ l, null, null, null, null);
if (c != null) {
c.moveToFirst();
String name = c.getString(1);
return name;
}
return null;
}

public String getRollno(long l) throws SQLException {
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_ROLLNO,
KEY_CLASS };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
+ l, null, null, null, null);
if (c != null) {
c.moveToFirst();
String rollno = c.getString(2);
return rollno;
}
return null;
}

public String getClasss(long l) throws SQLException {
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_ROLLNO,
KEY_CLASS };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
+ l, null, null, null, null);
if (c != null) {
c.moveToFirst();
String sclass = c.getString(3);
return sclass;
}
return null;
}

public void updateEntry(long lRow, String mName, String mRollno,
String mClass) throws SQLException {
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_NAME, mName);
cvUpdate.put(KEY_ROLLNO, mRollno);
cvUpdate.put(KEY_CLASS, mClass);
ourDatabase.update(DATABASE_TABLE, cvUpdate, KEY_ROWID + "=" + lRow,
null);
}

public void deleteEntry(long lRow1) throws SQLException {
ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + lRow1, null);
}

}

activity_main.xml
===================
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/linName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name:" />

        <EditText
            android:id="@+id/etName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10" >

            
        </EditText>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linRollNo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/linName"
        android:layout_below="@+id/linName"
        android:layout_marginTop="16dp"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tvRollNo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Roll No:" />

        <EditText
            android:id="@+id/etRollno"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="number" >
        </EditText>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linClass"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linRollNo"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="26dp"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tvClass"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Class:" />

        <EditText
            android:id="@+id/etClass"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linAddView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/linClass"
        android:layout_marginTop="36dp"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btnAdd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add" />

        <Button
            android:id="@+id/btnView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:text="View" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linRowId"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/linAddView"
        android:layout_marginTop="24dp"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tvRowId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Row ID:" />

        <EditText
            android:id="@+id/etRowId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linUpdate"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/linRowId"
        android:layout_marginTop="26dp"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btnViewById"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ViewById" />

        <Button
            android:id="@+id/btnDelete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Delete" />

        <Button
            android:id="@+id/btnUpdate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Update" />
    </LinearLayout>

</RelativeLayout>

view.xml
===============
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TableLayout
        android:id="@+id/tableLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TableRow>

            <TextView
                android:id="@+id/tvID"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Student ID" />

            <TextView
                android:id="@+id/tvName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="Name:" />

            <TextView
                android:id="@+id/tvRollno"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="Roll No:" />

            <TextView
                android:id="@+id/tvClass"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="Class" />
        </TableRow>
    </TableLayout>

    <TextView
        android:id="@+id/tvSQLinfo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="get info from db" >
    </TextView>

</LinearLayout>

AndroidManifest.xml
=====================

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.crudoperation"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.crudoperation.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SQLiteView" >
            <intent-filter>
                <action android:name="com.crudoperation.SQLVIEW" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

14 comments:

  1. Write two application one a MainActivity and another a Service.
    The main application should activate a Service on the click of a button.
    The Service, on activation, should broadcast a simple string message.
    This message should be received using the Broadcast Receiver in the
    Main activity and displayed on th screen.

    ReplyDelete
  2. we r dong we will give u code within 10 minutes

    ReplyDelete
    Replies
    1. We need two applications one for service and another for MainActivity.
      Plz Post it as a new topic on blog

      Delete
  3. can u check ur mail for services ur first program and customize.

    ReplyDelete
  4. I posted in ur blog also for services started program

    ReplyDelete
  5. http://android-coding.blogspot.in/2011/11/pass-data-from-service-to-activity.html

    ReplyDelete
    Replies
    1. ye wala link use karo tumhara dono application esi se ho jayega..

      Delete
  6. http://android-coding.blogspot.in/2011/11/pass-data-from-service-to-activity.html

    ReplyDelete
  7. http://crazyworldofandroid.blogspot.in/2011/08/upload-image-to-server-in-android.html

    ReplyDelete
  8. http://curious-blog.blogspot.in/2013/06/pick-image-and-upload-to-server-in.html

    ReplyDelete
  9. http://sunil-android.blogspot.in/2013/03/image-upload-on-server.html

    ReplyDelete
  10. http://curious-blog.blogspot.in/2013/06/pick-image-and-upload-to-server-in.html

    ReplyDelete
  11. http://www.codeofaninja.com/2013/04/android-http-client.html

    ReplyDelete