4

I have a part of code which returns an array after querying the database but when I run the the application , it crashes

//info is the name of the object of the type DataBase
    info.open();
    String[] data = info.queryAll();
    info.close();

Part of the database code , where I am trying to retrieve all the rows of Database of a certain column

public String[] queryAll() {
    String[] columns = new String[] { KEY_NAME };
    Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, null, null,
            null, null, null);
    if (cursor != null) {
        try {
            final int nameColumnIndex =                     cursor.getColumnIndex(KEY_NAME);
            List<String> names = new ArrayList<String>();
            while (cursor.moveToNext()) {
                names.add(cursor.getString(nameColumnIndex));
            }
            return names.toArray(new String[names.size()]);
        } finally {
            cursor.close();
        }
    }
    return null;

}

Is it because my DataBase is null in the beginning??If so how do I correct the code ?? All suggestions will be helpful' Thank You

LOGCAT

09-23 22:26:47.780: E/AndroidRuntime(2825): FATAL EXCEPTION: main
09-23 22:26:47.780: E/AndroidRuntime(2825): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.contactlist/com.example.contactlist.Contacts}: android.database.sqlite.SQLiteException: no such table: mycontacts (code 1): , while compiling: SELECT Contact_name FROM mycontacts
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.os.Looper.loop(Looper.java:137)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.app.ActivityThread.main(ActivityThread.java:4745)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at java.lang.reflect.Method.invokeNative(Native Method)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at java.lang.reflect.Method.invoke(Method.java:511)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at dalvik.system.NativeStart.main(Native Method)
09-23 22:26:47.780: E/AndroidRuntime(2825): Caused by: android.database.sqlite.SQLiteException: no such table: mycontacts (code 1): , while compiling: SELECT Contact_name FROM mycontacts
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at com.example.contactlist.DBContact.queryAll(DBContact.java:97)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at com.example.contactlist.Contacts.onCreate(Contacts.java:38)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.app.Activity.performCreate(Activity.java:5008)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
09-23 22:26:47.780: E/AndroidRuntime(2825):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
09-23 22:26:47.780: E/AndroidRuntime(2825):     ... 11 more

DATABASE CODE

public class DBContact {

    public static final String KEY_ROWID = "_id";
    public static final String KEY_NAME = "Contact_name";
    public static final String KEY_PERSONALPHONE = "Personal_Phonenumber";
    public static final String KEY_HOMEPHONE = "Home_Phonenumber";
    public static final String KEY_OFFICEPHONE = "Office_Phonenumber";

    private static final String DATABASE_NAME = "Contact_name";
    private static final String DATABASE_TABLE = "mycontacts";
    private static final int DATABASE_VERSION = 1;

    // Instance of the class DbHelper
    private DbHelper ourHelper;
    private final Context ourContext;
    private SQLiteDatabase ourDatabase;

    public static final String[] KEYS_ALL = { DBContact.KEY_ROWID,
            DBContact.KEY_NAME, DBContact.KEY_PERSONALPHONE,
            DBContact.KEY_HOMEPHONE, DBContact.KEY_OFFICEPHONE };

    private static class DbHelper extends SQLiteOpenHelper {

        private static final String DATABASE_CREATE = "create table contacts (_id integer primary key autoincrement, "
                + "Contact_name text not null, Personal_Phonenumber text not null, Home_Phonenumber text not null, Office_Phone text not null); ";

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

        @Override
        public void onCreate(SQLiteDatabase ourDatabase) {
            // TODO Auto-generated method stub
            try {
                ourDatabase.execSQL(DATABASE_CREATE);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }           

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

        }

    }

    // Context of constructor withhin our Class
    public DBContact(Context c) {
        ourContext = c;
    }

    // Opens the database
    public DBContact open() throws SQLException {
        // Constructor for DB Helper class takes in a Context
        // Context is passed in is "ourContext" for within our class

        ourHelper = new DbHelper(ourContext);
        // Passes in DB Name and Version
        // ourDatabase is of type SQLite DataBase
        ourDatabase = ourHelper.getWritableDatabase();
        return this;
    }

    // Closes the database connection
    public void close() {
        // refer to our DbHelper and close the SQLite DataBase Helper
        ourHelper.close();
        ourHelper = null;
        ourDatabase = null;
    }

    // Deletes the Row
    public boolean deleteRow(long rowId) {
        return ourDatabase.delete(DATABASE_TABLE, DBContact.KEY_ROWID + "="
                + rowId, null) > 0;
    }

    public String[] queryAll() {
        String[] columns = new String[] { KEY_NAME };
        Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, null, null,
                null, null, null);
        if (cursor != null) {
            try {
        final int nameColumnIndex = cursor.getColumnIndex(KEY_NAME);
        List<String> names = new ArrayList<String>();
        cursor.moveToFirst();
        while (cursor.moveToNext()) {
            names.add(cursor.getString(nameColumnIndex));
        }
        return names.toArray(new String[names.size()]);
    } finally {
        cursor.close();
   }
        }
        return null;
    }

    /*public Cursor queryAll(){
    String[] columns = new String[] {KEY_NAME};
        return   ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
    if(data == null){
        columns[0] = "NO CONTACTS PRESENT";
        return columns;
    }else{
        return columns;
    }


    }*/


    public long newRow(String name, String pphone, String hphone, String ophone) {
        // TODO Auto-generated method stub
        ContentValues newvalue = new ContentValues();
        newvalue.put(KEY_NAME, name);
        newvalue.put(KEY_PERSONALPHONE, pphone);
        newvalue.put(KEY_HOMEPHONE, hphone);
        newvalue.put(KEY_OFFICEPHONE, ophone);
        return ourDatabase.insert(DATABASE_TABLE, null, newvalue);

    }



    public String getName(Long l) {
        // TODO Auto-generated method stub
        String[] columns = new String[] { KEY_ROWID, KEY_NAME,
                KEY_PERSONALPHONE, KEY_HOMEPHONE, KEY_OFFICEPHONE };
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
                + 1, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
            String name = c.getString(1);
            return name;
        }
        return null;
    }

    public String getPphone(Long l) {
        // TODO Auto-generated method stub
        String[] columns = new String[] { KEY_ROWID, KEY_NAME,
                KEY_PERSONALPHONE, KEY_HOMEPHONE, KEY_OFFICEPHONE };
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
                + 1, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
            String Pphone = c.getString(2);
            return Pphone;

        }
        return null;
    }

    public String getHphone(Long l) {
        // TODO Auto-generated method stub
        String[] columns = new String[] { KEY_ROWID, KEY_NAME,
                KEY_PERSONALPHONE, KEY_HOMEPHONE, KEY_OFFICEPHONE };
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
                + 1, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
            String Hphone = c.getString(3);
            return Hphone;

        }
        return null;
    }

    public String getOphone(Long l) {
        // TODO Auto-generated method stub
        String[] columns = new String[] { KEY_ROWID, KEY_NAME,
                KEY_PERSONALPHONE, KEY_HOMEPHONE, KEY_OFFICEPHONE };
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "="
                + 1, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
            String Ophone = c.getString(4);
            return Ophone;

        }
        return null;
    }
}
14
  • i think your table has not been created yet Commented Sep 24, 2012 at 5:32
  • try to follow the link for working with database in sqlite codinglookseasy.blogspot.in/2012/08/sqlite-database.html Commented Sep 24, 2012 at 5:38
  • @ Sharath G ,when I replace info.open(); String[] data = info.queryAll(); info.close(); by info.open(); String data[] = new String[1]; data[0] = "Name"; info.close(); Database is getting created . Where am I going wrong ?? I will go through the website . Thank You Commented Sep 24, 2012 at 5:58
  • are you able to see your database? Commented Sep 24, 2012 at 6:03
  • @SharathG , Yes I can find my database in DDMS Commented Sep 24, 2012 at 6:13

4 Answers 4

2

You are creating another table

private static final String DATABASE_CREATE = "create table contacts (_id integer  
primary key autoincrement, "
            + "Contact_name text not null, Personal_Phonenumber text not null, 
Home_Phonenumber text not null, Office_Phone text not null); ";

here you are creating contacts table and not the one you need

use

mycontacts 

intead of

contacts 
Sign up to request clarification or add additional context in comments.

Comments

1

In your create table statement your table is called contacts:

private static final String DATABASE_CREATE = "create table contacts (_id integer primary key autoincrement, "
        + "Contact_name text not null, Personal_Phonenumber text not null, Home_Phonenumber text not null, Office_Phone text not null); ";

Yet in your query, its mycontacts:

private static final String DATABASE_TABLE = "mycontacts";

Which would explain why the error tells you that the table mycontacts does not exist.

Try changing your constant to:

private static final String DATABASE_TABLE = "contacts";

Which should fix that issue.

Comments

0
  private static final String DATABASE_CREATE = "create table contacts (_id integer primary key autoincrement, "
                + "Contact_name text not null, Personal_Phonenumber text not null, Home_Phonenumber text not null, Office_Phone text not null); ";

Office_Phone in the above code and the declaration do not match . Also what others said.

Comments

0

did you create your mycontacts table, if not, you should extend SQLiteOpenHelper, and override the onCreate, like this:

        @Override
    public void onCreate(SQLiteDatabase db) {
            db.execSQL("HERE IS YOUR SQL STATEMENT FOR CREATING mycontacts TABLE");
    }

every time you need to query the db, you could get the db instance using getReadabledatabase() of your own SQLiteOpenHelper;

Comments

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.