2

I've a ListView in my app to which the user can Add/Remove items. I'm using SQLiteDatabase to store the items when app is not in use but, the SQLiteDatabase giving me a strange error saying "No such table found:subjects(code 1). I can't figure out why's this happening, I've used SQLiteDatabase a few times before, but this time around it's just not working.

This is my code:

SubjectsDatabase.java -

import java.util.ArrayList;

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 SubjectsDatabase extends SQLiteOpenHelper {

private static final String SUBJECT_ID = "id";
private static final String SUBJECT_NAME = "name";

private static final String DATABASE_NAME = "subjectsDatabase";
private static final String TABLE_SUBJECTS = "subjects";
private static final int DATABASE_VERSION = 1;

private static final String DATABASE_CREATE = "CREATE_TABLE" + TABLE_SUBJECTS + "(" + 
                        SUBJECT_ID + "INTEGER_PRIMARY_KEY, " + SUBJECT_NAME + "TEXT" + ")";
public SubjectsDatabase(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
    try {
        db.execSQL(DATABASE_CREATE);
    }
    catch(SQLException e) {
        e.printStackTrace();
    }
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL("DROP TABLE IF EXSISTS topics");
    onCreate(db);
}
public void addSubject(Subject subject) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues topics = new ContentValues();
    topics.put(SUBJECT_NAME, subject.getSubject());

    db.insert(TABLE_SUBJECTS, null, topics);
    db.close();
}
public void removeSubject(Subject subject) {

    SQLiteDatabase db = this.getWritableDatabase();

    db.delete(TABLE_SUBJECTS, SUBJECT_NAME + " = ?", 
            new String[] {String.valueOf(subject.getSubject())});

    db.close();
}
public ArrayList<Subject> getSubjects(){

    ArrayList<Subject> topics = new ArrayList<Subject>();

    String selectQuery = "SELECT * FROM " + TABLE_SUBJECTS;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cur = db.rawQuery(selectQuery, null);

    if(cur.moveToFirst()) {
        do {
            Subject subject = new Subject();
            subject.setId(Integer.parseInt(cur.getString(0)));
            subject.setSubject(cur.getString(1));
            topics.add(subject);
        } while(cur.moveToNext());
    }
    db.close();
    return topics;
}
public void updateSubject(Subject old_name, Subject new_name) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues topic = new ContentValues();

    topic.put(SUBJECT_NAME, new_name.getSubject());

    db.update(TABLE_SUBJECTS, topic, SUBJECT_NAME + " = ?", 
            new String[] {String.valueOf(old_name.getSubject())});
    db.close();
}
}

Subject.java -

public class Subject {

String _subject;
int _id;
public Subject() {

}
public Subject(String subject) {
    this._subject = subject;
}
public String getSubject() {
    return _subject;
}
public void setSubject(String subject) {
    this._subject = subject;
}
public int getId() {
    return _id;
}
public void setId(int id) {
    this._id = id;
}
}

Add_Notes.java -

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;


public class Add_Notes extends Activity {

private ItemAdapter adapter;
private ArrayList<Subject> menu_items;
private SubjectsDatabase db = new SubjectsDatabase(this);
private ListView subjects;
private InputMethodManager imm;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add__notes);

    menu_items = db.getSubjects();
    adapter = new ItemAdapter(this, menu_items);
    subjects = (ListView) findViewById(R.id.subjects);

    subjects.setAdapter(adapter);
}

public void onClickAddSubjects(View v) {
    showDialog(0);
    showKeyboard();
}

protected Dialog onCreateDialog(int id) {
    switch(id) {
    case 0:
        Builder builder = new AlertDialog.Builder(this);
        final EditText SubjectName = new EditText(this);
        SubjectName.setHint("Subject Name");
        builder.setView(SubjectName);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {

                String subjectName = SubjectName.getText().toString();

                db.addSubject(new Subject(subjectName));

                adapter.add(new Subject(subjectName));
                adapter.notifyDataSetChanged();

                SubjectName.setText("");
                dismissDialog(0);
                removeDialog(0);
                hideKeyboard();
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {

                SubjectName.setText("");
                dismissDialog(0);
                removeDialog(0);
                hideKeyboard();

            }
        });
        return builder.create();
    }
    return null;
}

public void showKeyboard() {
    imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}

public void hideKeyboard() {
    imm.toggleSoftInput(InputMethodManager.RESULT_HIDDEN, 0);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_add__notes, menu);
    return true;
}
}

Here are the error logs -

04-09 18:08:42.133: E/linker(31508): load_library(linker.cpp:759): library "libmaliinstr.so" not found
04-09 18:08:42.965: E/SQLiteLog(31508): (1) no such table: subjects
04-09 18:08:42.984: E/AndroidRuntime(31508): FATAL EXCEPTION: main
04-09 18:08:42.984: E/AndroidRuntime(31508): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Swap.RR/com.Swap.RR.Add_Notes}: android.database.sqlite.SQLiteException: no such table: subjects (code 1): , while compiling: SELECT * FROM subjects
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2416)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.app.ActivityThread.access$600(ActivityThread.java:174)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1382)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.os.Handler.dispatchMessage(Handler.java:107)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.os.Looper.loop(Looper.java:194)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.app.ActivityThread.main(ActivityThread.java:5409)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at java.lang.reflect.Method.invokeNative(Native Method)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at java.lang.reflect.Method.invoke(Method.java:525)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at dalvik.system.NativeStart.main(Native Method)
04-09 18:08:42.984: E/AndroidRuntime(31508): Caused by: android.database.sqlite.SQLiteException: no such table: subjects (code 1): , while compiling: SELECT * FROM subjects
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:886)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:497)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1253)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at com.Swap.RR.SubjectsDatabase.getSubjects(SubjectsDatabase.java:66)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at com.Swap.RR.Add_Notes.onCreate(Add_Notes.java:32)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.app.Activity.performCreate(Activity.java:5122)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1146)
04-09 18:08:42.984: E/AndroidRuntime(31508):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2328)
04-09 18:08:42.984: E/AndroidRuntime(31508):    ... 11 more

Please, help me figure out what's wrong with my code. Thanks in Adavnce!!

3 Answers 3

7

It's an easy fix: you miss a space here (and have an extra UNDERSCORE):

"CREATE_TABLE" + TABLE_SUBJECTS + "("

and here (and have extra UNDERSCOREs)

SUBJECT_ID + "INTEGER_PRIMARY_KEY, "

and here

SUBJECT_NAME + "TEXT" 

It should read:

"CREATE TABLE " + TABLE_SUBJECTS + " (" // Note: NO UNDERSCORE!

and

SUBJECT_ID + " INTEGER PRIMARY KEY, " // Note: NO UNDERSCORES!

and

SUBJECT_NAME + " TEXT" 

The table isn't created because of the erroneous CREATE TABLE syntax.

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

4 Comments

I just tried to run it again after adding the space.... But still it's crashing!!
remove your old application and then run again.
I edited my answer, to add the other missing spaces and remove the underscores
I have no doubt... ;)
0

change this line to

private static final String DATABASE_CREATE = "CREATE_TABLE" + TABLE_SUBJECTS + "(" SUBJECT_ID + "INTEGER_PRIMARY_KEY, " + SUBJECT_NAME + "TEXT" + ")";

to

private static final String DATABASE_CREATE = "CREATE TABLE" + TABLE_SUBJECTS + "(" + 
                    SUBJECT_ID + " INTEGER_PRIMARY_KEY, " + SUBJECT_NAME + " TEXT" + ")";

you need to add space after columname and datatype. Then uninstall your previous app and run it again

3 Comments

private static final String DATABASE_CREATE = "CREATE TABLE " + TABLE_SUBJECTS + "(" + SUBJECT_ID + " INTEGER_PRIMARY_KEY, " + SUBJECT_NAME + " TEXT" + ")";
@nikhil.thakkar Tried your suggestion, but unfortunately, it didn't help!
I edited my answer once check and uninstall your app and againg run it
0

Why don't you check your SQLite db from Eclipse's DDMS perspective -> File Explorer. Download to your desktop and check using any SQLite browser tool.

If you find table is missing, you need to add try - catch blocks while creating your table (and everywhere else as recommendation) and log the exception so you know what is happening behind the scene. db.execSQL throws android.database.SQLException; and hence you can catch it.

Further, load_library(linker.cpp:759): library "libmaliinstr.so" not found error is related to missing permissions: RECORD_AUDIO & WRITE_EXTERNAL_STORAGE. Permissions needs to be added to AndroidManifest.xml file.

Note: If you use log several exceptions in your code, don't forget to disable logging while publishing your app.

2 Comments

Further, what I suspect is that earlier you had topics table and then you modified TABLE_SUBJECTS variable to subjects. Your database actually has topics table and now you are trying to access subjects table ! I am guessing this because you have topics table specified in your onUpgrade method !
Further, load_library(linker.cpp:759): library "libmaliinstr.so" not found error is related to missing permissions: RECORD_AUDIO & WRITE_EXTERNAL_STORAGE - are you sure?

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.