0

I have made a simple database application in android using DBhelper,I have put 2 Edittexts and 2 buttons,now i want is when i press "save" the values of 2 edittexts should be saved in database.I have tried following code but its not working,Please help me ,Thanks in advance.

Main.java

       package com.example.db;

import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.view.Menu;
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 {
EditText e1,e2;
Button b1,b2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    e1=(EditText)findViewById(R.id.editText1);
    e2=(EditText)findViewById(R.id.editText2);
    b1=(Button)findViewById(R.id.button1);
    b2=(Button)findViewById(R.id.button2);
    final String fname = null;
    final String lname = null;

    b1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
             String f=e1.getText().toString();
                String l =e2.getText().toString();
                if(checkForNotEmpty(f, l)){
                try{
                    dbclas entry =new dbclas(MainActivity.this);
                entry.open();
                entry.createEntry(f,l);
                entry.close();
                }catch (Exception e) {
                    // TODO: handle exception
                    showMyDialog("Error", e.toString());
                }

            }
        Toast.makeText(getApplicationContext(),"Saved", 0).show();  
        }
    });
    b2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent i =new Intent(MainActivity.this,Sqlview.class);
            startActivity(i);

        }
    });

    }
    private boolean checkForNotEmpty(String fname,String lname) {
        // TODO Auto-generated method stub

        if(fname.equals("")){
            showMyDialog("Error !!","Name Can't be blank");
            return false;
        }else if(lname.equals("")){
            showMyDialog("Error !!","Skill Can't be blank");
            return false;
        }else{
            return true;
        }
    }
    public void showMyDialog(String dialogType,String msg){
        Dialog da=new Dialog(this);
        da.setTitle(dialogType);
        TextView tv=new TextView(this);
        tv.setText(msg);
        if(dialogType.equals("Error !!")){
            tv.setTextColor(Color.RED);
        }else{
            tv.setTextColor(Color.YELLOW);
        }
        da.setContentView(tv);
        da.show();
    }

}

dbhelper.java

   package com.example.db;

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;
import android.util.Log;

public class dbclas {

    public static final String KEY_ROWID="_id";
    public static final String FIRST_NAME="first_name";
    public static final String LAST_NAME="last_name";

    private static final String DATABASE_NAME="person";
    private static final String DATABASE_TABLE="persons_table";
    private static final int DATABASE_VERSION=1;

    private DBHelper myHelper;
    private final Context myContext;
    private SQLiteDatabase myDatabase;

    private static class DBHelper extends SQLiteOpenHelper{

        public DBHelper(Context context) {
            super(context,DATABASE_NAME,null,DATABASE_VERSION);
        // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            String query="CREATE TABLE "+DATABASE_TABLE+" ( "+KEY_ROWID+" INTEGER PRIMARY KEY, "+FIRST_NAME+" TEXT NOT NULL, "+LAST_NAME+" TEXT NOT NULL);";
            db.execSQL(query);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            db.execSQL("DROP TABLE IF EXISTS"+DATABASE_TABLE);
            onCreate(db);
        }

    }
    public dbclas(Context c){
        myContext=c;
    }
    public dbclas open() throws SQLException{
        myHelper=new DBHelper(myContext);
        myDatabase=myHelper.getWritableDatabase();
        return this;
    }
    public void close(){
        myHelper.close();
    }
    public long createEntry(String fname, String lname) {
        // TODO Auto-generated method stub
        ContentValues cv=new ContentValues();
        cv.put(FIRST_NAME, fname);
        cv.put(LAST_NAME,lname);
        return myDatabase.insert(DATABASE_TABLE, null,cv);
    }
    public String getData() {
        // TODO Auto-generated method stub
        String[] columns=new String[]{KEY_ROWID,FIRST_NAME,LAST_NAME};
        Cursor c=myDatabase.query(DATABASE_TABLE, columns,null, null, null,null,null);
        String result="";
        int iRow=c.getColumnIndex(KEY_ROWID);
        int iName=c.getColumnIndex(FIRST_NAME);
        int iSkill=c.getColumnIndex(LAST_NAME);

        for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
            result=result+c.getString(iRow)+" "+c.getString(iName)+" "+c.getString(iSkill)+"\n";
        }
        return result;
    }
    public String getFName(Long l) {
        // TODO Auto-generated method stub
        String[] columns=new String[]{KEY_ROWID,FIRST_NAME,LAST_NAME};
        Cursor c=myDatabase.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 getLName(Long l) {
        // TODO Auto-generated method stub
        String[] columns=new String[]{KEY_ROWID,FIRST_NAME,LAST_NAME};
        Cursor c=myDatabase.query(DATABASE_TABLE, columns, KEY_ROWID+"="+l, null, null, null, null);
        if(c!=null){
            c.moveToFirst();
            String skill=c.getString(2);
            return skill;
        }
        return null;
    }
    public void updateEntry(long lRow, String mName, String mSkill) {
        // TODO Auto-generated method stub
        Log.v("in update method","...");
        ContentValues cvUpdate=new ContentValues();
        cvUpdate.put(FIRST_NAME, mName);
        cvUpdate.put(LAST_NAME,mSkill);
        myDatabase.update(DATABASE_TABLE, cvUpdate, KEY_ROWID+"="+lRow,null);

    }
    public boolean checkID(Long l) {
        // TODO Auto-generated method stub
        String[] columns=new String[]{KEY_ROWID,FIRST_NAME,LAST_NAME};
        Cursor c=myDatabase.query(DATABASE_TABLE, columns,null, null, null,null,null);
        int iRow=c.getColumnIndex(KEY_ROWID);


        for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
            Long l_id=Long.valueOf(c.getString(iRow));
            Log.v("L_id",""+l_id);
            if(l==l_id){
                return true;
            }
        }
        return false;

    }
    public void deleteEntry(Long lRow) {
        // TODO Auto-generated method stub
        myDatabase.delete(DATABASE_TABLE, KEY_ROWID+"="+lRow, null);
    }
}

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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="28dp"
        android:ems="10"
        android:hint="Last Name"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_alignRight="@+id/editText2"
        android:layout_marginRight="20dp"
        android:text="View" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText2"
        android:layout_marginRight="23dp"
        android:layout_marginTop="46dp"
        android:layout_toLeftOf="@+id/button2"
        android:text="Save" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="36dp"
        android:layout_marginTop="48dp"
        android:ems="10"
        android:hint="First Name"
        android:inputType="textPersonName" />

</RelativeLayout>

View.java

package com.example.databaseexample;

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

public class SQLView extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sqlview);
        TextView tv=(TextView) findViewById(R.id.tvSQLinfo);
        DBOperations info=new DBOperations(this);
        info.open();
        String data=info.getData();
        info.close();
        tv.setText(data);
    }

}

log

   06-13 10:24:02.851: E/SQLiteLog(21041): (1) table persons_table has no column named last_name
06-13 10:24:02.899: E/SQLiteDatabase(21041): Error inserting last_name=dgsfg first_name=jimg
06-13 10:24:02.899: E/SQLiteDatabase(21041): android.database.sqlite.SQLiteException: table persons_table has no column named last_name (code 1): , while compiling: INSERT INTO persons_table(last_name,first_name) VALUES (?,?)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at com.example.db.dbclas.createEntry(dbclas.java:63)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at com.example.db.MainActivity$1.onClick(MainActivity.java:41)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at android.view.View.performClick(View.java:4204)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at android.view.View$PerformClick.run(View.java:17355)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at android.os.Handler.handleCallback(Handler.java:725)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at android.os.Handler.dispatchMessage(Handler.java:92)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at android.os.Looper.loop(Looper.java:137)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at android.app.ActivityThread.main(ActivityThread.java:5041)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at java.lang.reflect.Method.invokeNative(Native Method)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at java.lang.reflect.Method.invoke(Method.java:511)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-13 10:24:02.899: E/SQLiteDatabase(21041):    at dalvik.system.NativeStart.main(Native Method)
6
  • Not working means what ?. What error your getting post logcat. Commented Jun 13, 2013 at 9:19
  • i have put log cat,Actually i want is when i click on "save" the entered data in edit texts should be save on DB.But when i press "save" button the app is stopped running..unfortunately. Commented Jun 13, 2013 at 9:25
  • (MainActivity.java:67) which statement pointing? Commented Jun 13, 2013 at 9:27
  • @jigar see my answer. you are passing null variables. Commented Jun 13, 2013 at 9:32
  • Your should also consider using TextUtils#isEmpty(CharSequence) instead of your unsafe checkForNotEmpty method. Commented Jun 13, 2013 at 10:00

2 Answers 2

1

Your database helper looks fine to me. You are getting a null exception error because fname and lname are null.

b1.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        String f=e1.getText().toString();
        String l =e2.getText().toString();
        if(checkForNotEmpty(fname, lname)){ // replace fname and lname with f and l here
            try{
                dbclas entry =new dbclas(MainActivity.this);
            entry.open();
            entry.createEntry(fname,lname);
            entry.close();
            }catch (Exception e) {
                // TODO: handle exception
                showMyDialog("Error", e.toString());
            }

        }
    Toast.makeText(getApplicationContext(),"Saved", 0).show();  
    }
});

is supposed to be

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        String f=e1.getText().toString();
        String l =e2.getText().toString();
           String f=e1.getText().toString();
            String l =e2.getText().toString();
            if(checkForNotEmpty(f, l)){
....
}
Sign up to request clarification or add additional context in comments.

6 Comments

now error is not generated but..my entries are not saved in database table..my table is still blank.
you need to change entry.createEntry(fname,lname); to entry.createEntry(f,l); too. Could be the reason why your table is blank.
i have edited as per u told...still the problem remains same..i have edited my logcat..please chek it,,..bro
where is the DBOperations class? Isnt it supposed to be dbclas class?
It is weird to have last_name because you have defined the column as follows String LAST_NAME="last_skill";
|
1

Small error in your String objects look at this use this

fname = e1.getText().toString();
lname = e2.getText().toString();

instead of

String f = e1.getText().toString();
String l = e2.getText().toString();

2 Comments

now error is not generated but..my entries are not saved in database table..my table is still blank.
now your error solved? that will be the another problem in your code. you have to tell me clearly what is the problem and how you code for that..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.