Hossa The Coder
Hossa The Coder

Reputation: 85

my contacts app stops when i try to write or update to my SQLite database

my app seems to stop everytime i try to add new contacts or update existing ones

my app is simple , i make the user enter the data of his contacts (firstname, lastname,mobile...etc) and he saves it to a database then he can see it in the main list view (notdone yet :) ) and then he can choose which contact to be displayed inorder to edit or delete him

can you help me with those crashes please??

below is the database class

public class DBcreator extends SQLiteOpenHelper {
/*
 * this class is responsible for all the database manipulation and
 * requirements it is called inside other classes for implementation
 */
public static final String DATABASE_NAME = "contacts";// NAME OF THE
                                                        // DATABASE//
public static final String DATABASE_TABLE = "contactsdisplay";// NAME OF THE
                                                                // TABLE
                                                                // INSIDE OF
                                                                // IT//
// THE DATA INSIDE THE TABLE//
public static final String KEY_FNAME = "first name";
public static final String KEY_LNAME = "last name";
public static final String KEY_MOBILE = "mobile";
public static final String KEY_ADDRESS = "address";
public static final String KEY_ROWID = "_id";
// VERSION OF THE DATABASE//
public static final int DATABASE_VERSION = 1;
// create database//
public static final String DATABASE_CREATE = "Create table"
        + DATABASE_TABLE + "(" + KEY_ROWID
        + "integer primary key autoincrement," + KEY_FNAME + "TEXT"
        + KEY_LNAME + "TEXT" + KEY_MOBILE + "TEXT" + KEY_ADDRESS + "TEXT);";

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

@Override
public void onCreate(android.database.sqlite.SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL(DATABASE_CREATE);// this orders the code to create the
                                // database//

}

@Override
public void onUpgrade(android.database.sqlite.SQLiteDatabase db,
        int oldVersion, int newVersion) {
    // drop old version and use the new one//
    db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
    onCreate(db);

}

public long add(String fname, String lname, String mob, String address) {
    // getting the database and editing in it//
    SQLiteDatabase db = this.getWritableDatabase();
    // insert what the user had entered in the database//
    ContentValues cv = new ContentValues();
    cv.put(KEY_FNAME, fname);
    cv.put(KEY_LNAME, lname);
    cv.put(KEY_MOBILE, mob);
    cv.put(KEY_ADDRESS, address);
    // db.insert(DATABASE_TABLE, null, cv);
    return db.insert(DATABASE_TABLE, null, cv);

}

public void savechanges(String fname, String lname, String mob,
        String address) {
    // change the existing data of the contact by lookup then replace//
    SQLiteDatabase db = this.getWritableDatabase();
    String[] array = new String[] { KEY_ROWID, KEY_FNAME, KEY_LNAME,
            KEY_MOBILE, KEY_ADDRESS };
    Cursor c = db.query(DATABASE_TABLE, array, fname, null, null, null,
            null);
    // we need to loop inside the database to find the existing values and
    // replace them//
    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        int firstname = c.getColumnIndex(KEY_FNAME);
        int lastname = c.getColumnIndex(KEY_FNAME);
        int mobile = c.getColumnIndex(KEY_FNAME);
        int address2 = c.getColumnIndex(KEY_FNAME);
        if (c.getString(firstname).equals(fname)) {
            ContentValues changes = new ContentValues();
            changes.put(KEY_FNAME, fname);
            changes.put(KEY_LNAME, lname);
            changes.put(KEY_MOBILE, mob);
            changes.put(KEY_ADDRESS, address);
            db.update(DATABASE_TABLE, changes, KEY_FNAME + "=" + fname,
                    null);
            break;
        }
    }
}

public void deletecontact(String fnamedelete) {
    // TODO Auto-generated method stub
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(DATABASE_TABLE, KEY_FNAME + "=" + fnamedelete, null);
}

public String[] queryall() {
    String[] FirstNames = new String[] { KEY_FNAME };
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cfname = db.query(DATABASE_TABLE, FirstNames, null, null, null,
            null, null);// to see all contacts//
    int GetTheName = cfname.getColumnIndex(KEY_FNAME);
    List<String> TheNames = new ArrayList<String>();
    {

        cfname.moveToFirst();
        while (cfname.moveToNext()) {
            TheNames.add(cfname.getString(GetTheName));

        }
        return TheNames.toArray(new String[TheNames.size()]);
    }

}

}

below is the CreateContact class: public class CreateContact extends Activity implements OnClickListener { Button Create; TextView fname, lname, mobile, address; EditText editfirst, editlast, editmobile, editaddress;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.createcontact);
    Create = (Button) findViewById(R.id.SaveNewContact);
    fname = (TextView) findViewById(R.id.FirstNametv1);
    lname = (TextView) findViewById(R.id.LastNametv1);
    mobile = (TextView) findViewById(R.id.Mobiletv1);
    address = (TextView) findViewById(R.id.Addresstv1);
    editfirst = (EditText) findViewById(R.id.EditFirstName);
    editlast = (EditText) findViewById(R.id.EditLastName);
    editmobile = (EditText) findViewById(R.id.EditMobile);
    editaddress = (EditText) findViewById(R.id.EditAddress);

    Create.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    DBcreator addition = new DBcreator(CreateContact.this);
    // her you ADD (put) the new data to the SQLite//
    String fname = editfirst.getEditableText().toString();
    String lname = editlast.getEditableText().toString();
    String mob = editmobile.getEditableText().toString();
    String address = editaddress.getEditableText().toString();

    addition.add(fname, lname, mob, address);
    addition.close();
    // go back to the main activity after changes took place//
    Intent k = new Intent(CreateContact.this, MainActivity.class);
    startActivity(k);
}
}

below is the EditContact class:

public class EditContact extends Activity implements OnClickListener {
Button SaveEdit, Cancel, Delete;
TextView fname2, lname2, mobile2, address2;
EditText editfirst2, editlast2, editmobile2, editaddress2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.editcontact);
    SaveEdit = (Button) findViewById(R.id.SaveChanges);
    Cancel = (Button) findViewById(R.id.CancelButton);
    Delete = (Button) findViewById(R.id.DeleteContact);
    fname2 = (TextView) findViewById(R.id.FirstNametv2);
    lname2 = (TextView) findViewById(R.id.LastNametv2);
    mobile2 = (TextView) findViewById(R.id.Mobiletv2);
    address2 = (TextView) findViewById(R.id.Addresstv2);
    editfirst2 = (EditText) findViewById(R.id.ViewFirstName);
    editlast2 = (EditText) findViewById(R.id.ViewLastName);
    editmobile2 = (EditText) findViewById(R.id.ViewMobile);
    editaddress2 = (EditText) findViewById(R.id.ViewAddress);

    SaveEdit.setOnClickListener(this);
    Cancel.setOnClickListener(this);
    Delete.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    switch (v.getId()) {
    case R.id.SaveChanges:
        DBcreator edit = new DBcreator(EditContact.this);
        String fname = editfirst2.getEditableText().toString();
        String lname = editlast2.getEditableText().toString();
        String mob = editmobile2.getEditableText().toString();
        String address = editaddress2.getEditableText().toString();
        edit.savechanges(fname, lname, mob, address);
        edit.close();
        Intent y = new Intent(EditContact.this, MainActivity.class);
        startActivity(y);
        break;
    case R.id.CancelButton:
        Intent k = new Intent(EditContact.this, MainActivity.class);
        startActivity(k);
        break;
    case R.id.DeleteContact:
        DBcreator delete = new DBcreator(EditContact.this);
        String fnamedelete = editfirst2.getEditableText().toString();
        String lnamedelete = editlast2.getEditableText().toString();
        String mobdelete = editmobile2.getEditableText().toString();
        String addressdelete = editaddress2.getEditableText().toString();
        delete.deletecontact(fnamedelete);
        delete.close();
        Intent h = new Intent(EditContact.this, MainActivity.class);
        startActivity(h);
        break;
    }
}

}

the logcat

12-30 12:08:31.794: E/Trace(11691): error opening trace file: No such file or directory (2)
12-30 12:08:32.184: W/MMUMapper(11691): fail to register MVA, unsupported format(0x5)
12-30 12:08:32.477: W/MMUMapper(11691): fail to register MVA, unsupported format(0x5)
12-30 12:08:32.530: W/MMUMapper(11691): fail to register MVA, unsupported format(0x5)
12-30 12:08:33.303: I/SurfaceTextureClient(11691): [0x4f05e390] frames:9, duration:1.000000, fps:8.996834
12-30 12:08:34.680: W/MMUMapper(11691): fail to register MVA, unsupported format(0x5)
12-30 12:08:34.719: I/SurfaceTextureClient(11691): [0x4f05e390] frames:11, duration:1.407000, fps:7.816139
12-30 12:08:34.958: W/MMUMapper(11691): fail to register MVA, unsupported format(0x5)
12-30 12:08:35.019: W/MMUMapper(11691): invalid operation for unregister MVA with VA(0x526d0000) size(614400) f(0x5)
12-30 12:08:35.020: W/MMUMapper(11691): invalid operation for unregister MVA with VA(0x5295d000) size(614400) f(0x5)
12-30 12:08:35.020: W/MMUMapper(11691): invalid operation for unregister MVA with VA(0x52b00000) size(614400) f(0x5)
12-30 12:08:35.270: W/MMUMapper(11691): fail to register MVA, unsupported format(0x5)
12-30 12:08:36.274: I/SurfaceTextureClient(11691): [0x529225b8] frames:4, duration:1.462000, fps:2.734245
12-30 12:08:37.780: I/SurfaceTextureClient(11691): [0x529225b8] frames:4, duration:1.495000, fps:2.674925
12-30 12:08:38.882: I/SurfaceTextureClient(11691): [0x529225b8] frames:3, duration:1.099000, fps:2.729083
12-30 12:08:40.204: I/SurfaceTextureClient(11691): [0x529225b8] frames:4, duration:1.259000, fps:3.176750
12-30 12:08:41.403: I/SurfaceTextureClient(11691): [0x529225b8] frames:4, duration:1.267000, fps:3.156914
12-30 12:08:42.486: I/SurfaceTextureClient(11691): [0x529225b8] frames:4, duration:1.072000, fps:3.729460
12-30 12:08:43.690: I/SurfaceTextureClient(11691): [0x529225b8] frames:5, duration:1.215000, fps:4.115116
12-30 12:08:44.736: I/SurfaceTextureClient(11691): [0x529225b8] frames:4, duration:1.046000, fps:3.823227
12-30 12:08:46.119: I/SurfaceTextureClient(11691): [0x529225b8] frames:5, duration:1.379000, fps:3.625341
12-30 12:08:47.287: I/SurfaceTextureClient(11691): [0x529225b8] frames:4, duration:1.176000, fps:3.399773
12-30 12:08:48.622: I/SurfaceTextureClient(11691): [0x529225b8] frames:4, duration:1.324000, fps:3.019432
12-30 12:08:49.734: I/SurfaceTextureClient(11691): [0x529225b8] frames:5, duration:1.119000, fps:4.465023
12-30 12:08:50.987: I/SurfaceTextureClient(11691): [0x529225b8] frames:4, duration:1.155000, fps:3.463197
12-30 12:08:52.023: I/SurfaceTextureClient(11691): [0x529225b8] frames:3, duration:1.140000, fps:2.629971
12-30 12:08:52.226: E/SQLiteLog(11691): (1) near "tablecontactsdisplay": syntax error
12-30 12:08:52.227: W/dalvikvm(11691): threadid=1: thread exiting with uncaught exception (group=0x416e4908)
12-30 12:08:52.255: E/AndroidRuntime(11691): FATAL EXCEPTION: main
12-30 12:08:52.255: E/AndroidRuntime(11691): android.database.sqlite.SQLiteException: near "tablecontactsdisplay": syntax error (code 1): , while compiling: Create tablecontactsdisplay(_idinteger primary key autoincrement,first nameTEXTlast nameTEXTmobileTEXTaddressTEXT);
12-30 12:08:52.255: E/AndroidRuntime(11691):    at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1663)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1594)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at com.hossa.contactsapp.DBcreator.onCreate(DBcreator.java:45)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at com.hossa.contactsapp.DBcreator.add(DBcreator.java:60)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at com.hossa.contactsapp.CreateContact.onClick(CreateContact.java:50)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at android.view.View.performClick(View.java:4093)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at android.view.View$PerformClick.run(View.java:17149)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at android.os.Handler.handleCallback(Handler.java:615)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at android.os.Handler.dispatchMessage(Handler.java:92)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at android.os.Looper.loop(Looper.java:153)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at android.app.ActivityThread.main(ActivityThread.java:5006)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at java.lang.reflect.Method.invokeNative(Native Method)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at java.lang.reflect.Method.invoke(Method.java:511)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
12-30 12:08:52.255: E/AndroidRuntime(11691):    at dalvik.system.NativeStart.main(Native Method)
12-30 12:08:54.208: I/Process(11691): Sending signal. PID: 11691 SIG: 9

Upvotes: 0

Views: 143

Answers (5)

Luis Pena
Luis Pena

Reputation: 4354

implement the interface OnClickListener instead of using it as " inner ", and do the work there.

Instead of this:

Create.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        SQLiteDatabase addition = new SQLiteDatabase(CreateContact.this);
        // her you ADD (put) the new data to the SQLite//
        String fname = editfirst.getEditableText().toString();
        String lname = editlast.getEditableText().toString();
        String mob = editmobile.getEditableText().toString();
        String address = editaddress.getEditableText().toString();

        addition.add(fname, lname, mob, address);
        addition.close();
        // go back to the main activity after changes took place//
        Intent k = new Intent(CreateContact.this, MainActivity.class);
        startActivity(k);
    }
});

Do this: Create.setOnClickListener(this);

public class CreateContact extends Activity implements View.OnClickListener {

 //etc... etc..

 @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        SQLiteDatabase addition = new SQLiteDatabase(this);
        // her you ADD (put) the new data to the SQLite//
        String fname = editfirst.getEditableText().toString();
        String lname = editlast.getEditableText().toString();
        String mob = editmobile.getEditableText().toString();
        String address = editaddress.getEditableText().toString();

        addition.add(fname, lname, mob, address);
        addition.close();
        // go back to the main activity after changes took place//
        Intent k = new Intent(CreateContact.this, MainActivity.class);
        startActivity(k);
    }

}

Edited

Your database schema is wrong, the logcat says that there is an syntax error, it should look like this:

private static final String DATABASE_CREATE =
        "CREATE TABLE "
                + DATABASE_TABLE + "( "
                + KEY_ROWID + " INTEGER PRIMARY KEY,"
                + KEY_FNAME + " TEXT,"
                + KEY_LNAME + " TEXT,"
                + KEY_MOBILE + " TEXT,"
                + KEY_ADDRESS + " TEXT)";

You forgot to put a comma to separate every key.

Upvotes: 0

Hossa The Coder
Hossa The Coder

Reputation: 85

thx for the help guys i just found out that the classes where implementing another class that i deleted

so i changed this

   @Override
public void onCreate(android.database.sqlite.SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);// this orders the code to create the
                            // database//
}

to this

  @Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL(DATABASE_CREATE);// this orders the code to create the
                                // database//

}

you see my old class was called SQLitedatabase and thus i followed @laalto and @ramaral advice and changed some stuff :)

thx guys

Upvotes: 0

laalto
laalto

Reputation: 152867

12-29 14:02:33.748: E/AndroidRuntime(31505): java.lang.ClassCastException: com.hossa.contactsapp.CreateContact$1 cannot be cast to android.content.Context
12-29 14:02:33.748: E/AndroidRuntime(31505):    at com.hossa.contactsapp.SQLiteDatabase.<init>(SQLiteDatabase.java:35)

An anonymous inner class CreateContact$1 is not a Context.

You should not trust your IDE's problem solving skills blindly:

SQLiteDatabase addition = new SQLiteDatabase(this);

Here you are supposed to pass a Context. In an Activity, passing this works but in an OnClickListener, this refers to the listner and not the activity. Use CreateContact.this to refer to the parent this that is a Context.

Then, change the parameter you pass to SQLiteDatabase constructor to a Context and remove the cast here:

public SQLiteDatabase(OnClickListener onClickListener) {
    super((Context) onClickListener,

It's also a good idea to rename the database class as Android already has a class with the same name.


Updated: Now you have SQL syntax errors here:

Create tablecontactsdisplay(_idinteger primary key autoincrement,first nameTEXTlast nameTEXTmobileTEXTaddressTEXT);

You need whitespace between identifiers and keywords, and identifiers either need to have their whitespace removed or the whole identifier quoted. Also there's missing , commas. E.g.

Create table contactsdisplay(_id integer primary key autoincrement,`first name` TEXT, `last name` TEXT, mobile TEXT, address TEXT);

Upvotes: 2

Nikolay Ivanov
Nikolay Ivanov

Reputation: 8935

You're problem seems to be in this line: SQLiteDatabase addition = new SQLiteDatabase(this); In this context this refers to instance of onClickListener wich is not instance of context if you need to refer to instance of activity you should use CreateContact.this

Upvotes: 0

ramaral
ramaral

Reputation: 6179

One problem that I can see in or code is the DATABASE_CREATE string. Neead add some spaces and commas between words:

public static final String DATABASE_CREATE = "Create table "
        + DATABASE_TABLE + "(" + KEY_ROWID
        + " integer primary key autoincrement," + KEY_FNAME + " TEXT,"
        + KEY_LNAME + " TEXT," + KEY_MOBILE + " TEXT," + KEY_ADDRESS + " TEXT);";

Another problem is the constructor for SQLiteDatabase, it is not declared correctly

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

Upvotes: 2

Related Questions