I am having a problem getting my SQLite working properly in this Android application that I'm developing. It appears as though the table isn't properly being created based on the LogCat messages. I feel like I've been staring at the screen too long. Can anyone here spot the problem in my code?
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBHelper extends SQLiteOpenHelper {
// table name
public static final String TABLE_JOKES = "jokes";
// database field names
public static final String COLUMN_ID = "_id";
public static final String COLUMN_CATEGORY = "category";
public static final String COLUMN_SUBCATEGORY = "subcategory";
public static final String COLUMN_JOKE_TYPE = "jokeType";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_QUESTION_TEXT = "questionText";
public static final String COLUMN_ANSWER_TEXT = "answerText";
public static final String COLUMN_MONOLOGUE_TEXT = "monologueText";
public static final String COLUMN_RATING_SCALE = "ratingScale";
public static final String COLUMN_COMMENTS = "comments";
public static final String COLUMN_JOKE_SOURCE = "jokeSource";
public static final String COLUMN_RELEASE_STATUS = "releaseStatus";
public static final String COLUMN_CREATED = "created";
public static final String COLUMN_MODIFIED = "modified";
private static final String DATABASE_NAME = "jokes.db"; // file name
private static final int DATABASE_VERSION = 1;
// Database creation raw SQL statement
private static final String DATABASE_CREATE = "create table " + TABLE_JOKES
+ "( " + COLUMN_ID + " integer primary key autoincrement, "
+ COLUMN_CATEGORY + " text not null, " + COLUMN_SUBCATEGORY
+ " text not null, " + COLUMN_JOKE_TYPE + " integer not null, "
+ COLUMN_DESCRIPTION + " text," + COLUMN_QUESTION_TEXT + "text,"
+ COLUMN_ANSWER_TEXT + "text," + COLUMN_MONOLOGUE_TEXT + "text,"
+ COLUMN_RATING_SCALE + "integer," + COLUMN_COMMENTS + "text,"
+ COLUMN_JOKE_SOURCE + "text," + COLUMN_RELEASE_STATUS + "integer,"
+ COLUMN_CREATED + "text," + COLUMN_MODIFIED + "text" + ");";
// static instance to share DBHelper
private static DBHelper dbHelper = null;
private SQLiteDatabase db ;
/**
* Constructor
*
* #param context
* #param name
* #param factory
* #param version
*/
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
db = getWritableDatabase();
}
/**
* This is a static method that makes sure that only one database helper
* exists across the app's lifecycle
*
* #param context
* #return
*/
public static DBHelper getDBHelper(Context context) {
if (dbHelper == null) {
dbHelper = new DBHelper(context.getApplicationContext());
}
return dbHelper;
}
/*
* (non-Javadoc)
*
* #see
* android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite
* .SQLiteDatabase)
*/
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
/*
* (non-Javadoc)
*
* #see
* android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite
* .SQLiteDatabase, int, int)
*/
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
Log.w(DBHelper.class.getName(), "Upgrading database from version "
+ oldVersion + " to " + newVersion);
}
/**
* CRUD - Update
*
* #param category
* #param subcategory
* #param jokeType
* #param description
* #param questionText
* #param answerText
* #param monologueText
* #param comments
* #param jokeSource
* #param ratingScale
* #param releaseStatus
* #return
*/
public long insertNewJoke(String category, String subcategory,
int jokeType, String description, String questionText,
String answerText, String monologueText, String comments,
String jokeSource, int ratingScale, int releaseStatus) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_CATEGORY, category);
cv.put(COLUMN_SUBCATEGORY, subcategory);
cv.put(COLUMN_JOKE_TYPE, jokeType);
cv.put(COLUMN_DESCRIPTION, description);
cv.put(COLUMN_QUESTION_TEXT, questionText);
cv.put(COLUMN_ANSWER_TEXT, answerText);
cv.put(COLUMN_MONOLOGUE_TEXT, monologueText);
cv.put(COLUMN_COMMENTS, comments);
cv.put(COLUMN_JOKE_SOURCE, jokeSource);
cv.put(COLUMN_RATING_SCALE, ratingScale);
cv.put(COLUMN_RELEASE_STATUS, releaseStatus);
cv.put(COLUMN_CREATED, ""); // how to put date??
cv.put(COLUMN_CREATED, "");
long code = getWritableDatabase().insert(TABLE_JOKES, null, cv);
return code;
}
/**
* CRUD - Retrieve
*
* #return
*/
public Cursor getJokes() {
String[] columns = { COLUMN_CATEGORY, COLUMN_SUBCATEGORY,
COLUMN_JOKE_TYPE, COLUMN_DESCRIPTION, COLUMN_ANSWER_TEXT,
COLUMN_MONOLOGUE_TEXT, COLUMN_RATING_SCALE, COLUMN_COMMENTS,
COLUMN_JOKE_SOURCE, COLUMN_RELEASE_STATUS, COLUMN_CREATED,
COLUMN_MODIFIED }; // might need the _id column
return getWritableDatabase().query(TABLE_JOKES, columns, null, null,
null, null, null);
}
/**
* CRUD - Delete
*
* #param id
*/
public void deleteJoke(int id) {
getWritableDatabase().delete(TABLE_JOKES, COLUMN_ID + "=?",
new String[] { String.valueOf(id) });
}
}
So in onCreate() (in my MainActivity) I try to insert a new record into the database and then try to retrieve it into a cursor. However, it seems to be getting caught at the insert statement.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// the projection (fields from the database that we want to use)
String from[] = { DBHelper.COLUMN_DESCRIPTION };
// matching fields on the layout to be used with the adapter
int to[] = { R.id.tv1 };
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lvMainJokes);
dbHelper = DBHelper.getDBHelper(this);
long code = dbHelper.insertNewJoke("Holiday", "", 2, "Joke 1 Description", "", "",
"joke", "", "", 5, 1);
if (code != -1)
cursor = dbHelper.getJokes();
...
Here is the LogCat output:
11-15 15:19:08.040: I/Choreographer(1016): Skipped 45 frames! The application may be doing too much work on its main thread.
11-15 15:19:35.358: D/dalvikvm(1064): GC_FOR_ALLOC freed 58K, 4% free 2726K/2836K, paused 42ms, total 45ms
11-15 15:19:35.368: I/dalvikvm-heap(1064): Grow heap (frag case) to 3.315MB for 635812-byte allocation
11-15 15:19:35.438: D/dalvikvm(1064): GC_FOR_ALLOC freed 2K, 4% free 3344K/3460K, paused 63ms, total 63ms
11-15 15:19:35.548: E/SQLiteLog(1064): (1) table jokes has no column named releaseStatus
11-15 15:19:35.568: E/SQLiteDatabase(1064): Error inserting category=Holiday releaseStatus=1 jokeType=2 created= monologueText=joke description=Joke 1 Description subcategory= answerText= questionText= jokeSource= ratingScale=5 comments=
11-15 15:19:35.568: E/SQLiteDatabase(1064): android.database.sqlite.SQLiteException: table jokes has no column named releaseStatus (code 1): , while compiling: INSERT INTO jokes(category,releaseStatus,jokeType,created,monologueText,description,subcategory,answerText,questionText,jokeSource,ratingScale,comments) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at com.teamdotgetname.android.phase1.jokeapplication.persistence.DBHelper.insertNewJoke(DBHelper.java:143)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at com.teamdotgetname.android.phase1.jokeapplication.presentation.MainActivity.onCreate(MainActivity.java:53)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at android.app.Activity.performCreate(Activity.java:5133)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at android.os.Handler.dispatchMessage(Handler.java:99)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at android.os.Looper.loop(Looper.java:137)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at java.lang.reflect.Method.invoke(Method.java:525)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-15 15:19:35.568: E/SQLiteDatabase(1064): at dalvik.system.NativeStart.main(Native Method)
11-15 15:19:35.798: I/Choreographer(1064): Skipped 42 frames! The application may be doing too much work on its main thread.
11-15 15:19:35.868: D/gralloc_goldfish(1064): Emulator without GPU emulation detected.
Thanks for taking a look.
At a quick glance, your code looks good. The exception:
android.database.sqlite.SQLiteException: table jokes has no column named releaseStatus (code 1)
seems erroneous because clearly you are creating the releaseStatus column in your create table DATABASE_CREATE String. I ran into a problem where I was modifying the schema of my database and the changes were not taking effect in my application because I was not incrementing the DATABASE_VERSION.
Your options to try which will all cause the database to get recreated are:
Clear the applications data via the Settings apk
Manually uninstall then reinstall your application. (Just running gradle installDebug or having Eclipse install your app isn't good enough)
Increment your DATABASE_VERSION value
I would say that you need some space in Create statement.
Starting: COLUMN_QUESTION_TEXT + "text," into COLUMN_QUESTION_TEXT + " text,".
It looks just like you don't have spaces between the column names and the column types. Try this.
private static final String DATABASE_CREATE = "create table " + TABLE_JOKES
+ "( " + COLUMN_ID + " integer primary key autoincrement, "
+ COLUMN_CATEGORY + " text not null, " + COLUMN_SUBCATEGORY
+ " text not null, " + COLUMN_JOKE_TYPE + " integer not null, "
+ COLUMN_DESCRIPTION + " text," + COLUMN_QUESTION_TEXT + " text,"
+ COLUMN_ANSWER_TEXT + " text," + COLUMN_MONOLOGUE_TEXT + " text,"
+ COLUMN_RATING_SCALE + " integer," + COLUMN_COMMENTS + " text,"
+ COLUMN_JOKE_SOURCE + " text," + COLUMN_RELEASE_STATUS + " integer,"
+ COLUMN_CREATED + " text," + COLUMN_MODIFIED + " text" + ");";
In DATABASE_CREATE mistake "integer," + COLUMN_COMMENTS + "text,". No sepparate space.
Related
This is DatabaseHelper.java class, in this class I write query for SQLite Database. I think there is not any problem in query.
package com.example.ankurnamikaze.myapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import static android.R.attr.id;
import static android.R.attr.name;
public class DatabaseHelper extends SQLiteOpenHelper {
SQLiteDatabase db;
public static final String DATABASE_NAME = "notes_db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "notes";
public static final String COL_ID = "id";
public static final String COL_NAME = "name";
public static final String COL_PASS = "pass";
This method is used for creating Database.
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (" +COL_ID + " integer autoincrement," + COL_NAME + " text," + COL_PASS+ " text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE_NAME);
onCreate(db);
}
// INSERTING ROW IN DATABASE
public void insertData(int id, String name, String pass){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_ID, id);
values.put(COL_NAME, name);
values.put(COL_PASS, pass);
db.insert(TABLE_NAME, null, values);
}
}
This is MainActivity.java class. I think I'm getting problem in defining the DatabaseHelper class because before when i defined this outside the onCreate method it make app crash then i saw some code which tell me to define it inside the onCreate method but still it didnt work for me.
package com.example.ankurnamikaze.myapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import static android.R.attr.id;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
public class MainActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
EditText name, password;
String user_name, user_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
databaseHelper = new DatabaseHelper(this);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.user_name);
password = (EditText)findViewById(R.id.user_pass);
user_name = String.valueOf(name.getText());
user_pass = String.valueOf(password.getText());
databaseHelper.insertData(id, user_name, user_pass);
}
}
This is activiy_main.xml, in this I create the attributes. And I don't think this is the source of problem.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.ankurnamikaze.myapp.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="USERNAME"
android:id="#+id/user_name"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="PASSWORD"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="sumbit"
android:id="#+id/button" />
</LinearLayout>
There are a few errors/issues.
Issue 1
You have coded " integer autoincrement," this will result in a syntax error as the AUTOINCREMENT keyword can only be used with INTEGER PRIMARY KEY (saying that it's not recommended to use it as INTEGER PRIMARY KEY is more efficient and has very much the same result, that is automatically generating a unique id (actually it only makes the id an alias of the rowid in either situation)).SQLite Autoincrement
e.g.
The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and
disk I/O overhead and should be avoided if not strictly needed. It is
usually not needed
The error would result in something along the lines of the following :-
09-19 07:32:10.040 7200-7200/? E/SQLiteLog: (1) near "autoincrement": syntax error
09-19 07:32:10.040 7200-7200/? D/AndroidRuntime: Shutting down VM
09-19 07:32:10.040 7200-7200/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa62e9288)
09-19 07:32:10.044 7200-7200/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{so52399661.so52399661/so52399661.so52399661.MainActivity}: android.database.sqlite.SQLiteException: near "autoincrement": syntax error (code 1): , while compiling: create table notes (id integer autoincrement,name text,pass text)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: near "autoincrement": syntax error (code 1): , while compiling: create table notes (id integer autoincrement,name text,pass text)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1663)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1594)
at so52399661.so52399661.DatabaseHelper.onCreate(DatabaseHelper.java:23)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at so52399661.so52399661.DatabaseHelper.insertData(DatabaseHelper.java:38)
at so52399661.so52399661.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Instead I'd suggest just coding :-
db.execSQL("create table " + TABLE_NAME + " (" +COL_ID + " INTEGER PRIMARY KEY," + COL_NAME + " TEXT," + COL_PASS+ " TEXT)");
Issue 2
You have no id user_pass defined in the layout.
Issue 3
id cannot be resolved (see below this isn't needed).
Solution
The following is the fixed code (see comments) with some additional code to list the tables in the Database :-
activity_main.xml (id user_pass added to PASSWORD EditText) :-
<?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">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="USERNAME"
android:id="#+id/user_name"/>
<EditText
android:id="#+id/user_pass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="PASSWORD"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="sumbit"
android:id="#+id/button" />
</LinearLayout>
DatabaseHelper.java (see comments) :-
public class DatabaseHelper extends SQLiteOpenHelper {
SQLiteDatabase db;
public static final String DATABASE_NAME = "notes_db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "notes";
public static final String COL_ID = "id";
public static final String COL_NAME = "name";
public static final String COL_PASS = "pass";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//db.execSQL("create table " + TABLE_NAME + " (" +COL_ID + " integer autoincrement," + COL_NAME + " text," + COL_PASS+ " text)"); //<<<<<<<<<< ERROR
db.execSQL("create table " + TABLE_NAME + " (" +COL_ID + " INTEGER PRIMARY KEY," + COL_NAME + " TEXT," + COL_PASS+ " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE_NAME);
onCreate(db);
}
// INSERTING ROW IN DATABASE
//<<<<<<<<<< as INTEGER PRIMARY KEY then id will be automatically generated
public void insertData(String name, String pass){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
//values.put(COL_ID, id); not needed will autogenerate
values.put(COL_NAME, name);
values.put(COL_PASS, pass);
db.insert(TABLE_NAME, null, values);
}
}
MainActivity.java (see comments) :-
public class MainActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
EditText name, password;
String user_name, user_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
databaseHelper = new DatabaseHelper(this);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.user_name);
password = (EditText)findViewById(R.id.user_pass);
user_name = String.valueOf(name.getText());
user_pass = String.valueOf(password.getText());
//databaseHelper.insertData(id, user_name, user_pass); //<<<<<<<<<< got rid of id
databaseHelper.insertData(user_name, user_pass);
//<<<<<<<<<< ADDED to List the tables
Cursor csr = databaseHelper.getWritableDatabase().query("sqlite_master",null,null,null,null,null,null );
while (csr.moveToNext()) {
Log.d("TABLES","Found table " + csr.getString(csr.getColumnIndex("name")));
}
csr.close();
}
}
Result in the Log :-
09-19 07:10:20.628 6977-6977/so52399661.so52399661 D/TABLES: Found table android_metadata
Found table notes
i.e. you notes table exists, android_metedata is a table created by the SQLiteOpenhelper class that you DatabaseHelper is a subclass of. It contains the locale.
This is my first SQLite App and I found a lot of errors and I don't what to do.
Can anyone tell me what I need to do?
This is my log cat:
12-26 18:58:05.870 26185-26185/? I/art: Late-enabling -Xcheck:jni
12-26 18:58:05.889 26185-26185/? E/Environment: initForCurrentUser:userId= 0
12-26 18:58:05.889 26185-26185/? D/Environment: UserEnvironment current
userId IS : 0
12-26 18:58:05.889 26185-26185/? D/Environment: UserEnvironment PRIMARY
STORAGE IS : MEDIA_INTERNAL
12-26 18:58:05.982 26185-26185/com.example.acer.sqlitecrud I/LoadedApk: No
resource references to update in package com.hmct.hmcttheme
12-26 18:58:06.010 26185-26185/com.example.acer.sqlitecrud W/art: Before
Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
12-26 18:58:06.135 26185-26185/com.example.acer.sqlitecrud E/SQLiteLog: (1)
near "TABLEstudentTable": syntax error
12-26 18:58:06.136 26185-26185/com.example.acer.sqlitecrud D/AndroidRuntime:
Shutting down VM
12-26 18:58:06.138 26185-26185/com.example.acer.sqlitecrud E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.example.acer.sqlitecrud, PID: 26185
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.acer.sqlitecrud/com.example.acer.sqlitecrud.MainActivity}: android.database.sqlite.SQLiteException: near "TABLEstudentTable": syntax error (code 1): , while compiling: CREATE TABLEstudentTable(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2328)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2394)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1306)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5270)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:708)
Caused by: android.database.sqlite.SQLiteException: near "TABLEstudentTable": syntax error (code 1): , while compiling: CREATE TABLEstudentTable(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at com.example.acer.sqlitecrud.DatabaseHelper.onCreate(DatabaseHelper.java:27)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.example.acer.sqlitecrud.DatabaseHelper.<init>(DatabaseHelper.java:22)
at com.example.acer.sqlitecrud.MainActivity.onCreate(MainActivity.java:22)
at android.app.Activity.performCreate(Activity.java:6075)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2281)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2394)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1306)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5270)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:708)
12-26 18:58:06.249 26185-26185/com.example.acer.sqlitecrud I/Process: Sending signal. PID: 26185 SIG: 9
This is my class:
DatabaseHelper.Java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String dbName = "Student.db";
public static final String tbName = "studentTable";
public static final String colID = "ID";
public static final String colName = "NAME";
public static final String colMarks = "MARKS";
public DatabaseHelper(Context context) {
super(context, dbName, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE"+tbName+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS"+tbName);
onCreate(db);
}
public boolean insertData (String Name, String Marks){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(colName,Name);
contentValues.put(colMarks,Marks);
long result = db.insert(tbName,null,contentValues);
if (result == -1){
return false;
}else {
return true;
}
}
}
MainActivity.java:
package com.example.acer.sqlitecrud;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText Name, Marks;
Button addData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
Name = (EditText)findViewById(R.id.edtNama);
Marks = (EditText)findViewById(R.id.edtNilai);
addData = (Button)findViewById(R.id.btnInsert);
InsertData();
}
private void InsertData() {
addData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.insertData(Name.getText().toString(),
Marks.getText().toString());
if (isInserted = true){
Toast.makeText(MainActivity.this,"Data Telah Di Inputkan !!",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this,"Data Gagal Di Inputkan !!",Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+tbName+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)");
}
note the space between the TABLE and tbName
Query syntax error, space is missing.
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+tbName+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)");
}
You are missing space in syntax of create table
db.execSQL("CREATE TABLE "+tbName+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)");
In drop table also you missed the space
"DROP TABLE IF EXISTS "+tbName
check below code
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+tbName+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)"); //add space after TABLE
}
When I call function 'test' my app crashes. Any ideas why does that happen?
DB class
package com.example.paulcosma.app2;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DB extends SQLiteOpenHelper{
public static final String
dbName = "foods.db",
tableName = "foods",
colId = "id",colName = "name",colCarbs = "carbs";
public DB(Context context) {
super(context, dbName, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + dbName + "( " + colId + " INTEGER PRIMARY KEY AUTOINCREMENT," + colName + " TEXT," + colCarbs + " REAL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + dbName);
onCreate(db);
}
public boolean addFood(String Name, float Carbs){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(colName,Name);
contentValues.put(colCarbs,Carbs);
long result = db.insert(tableName,null,contentValues);
return result != -1; // -1 == not inserted
}
}
MainActivity
package com.example.paulcosma.app2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DB db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DB(this);
}
public void test(View v){
boolean insertedSuccessfully = db.addFood("Milk",4); // crashes when called
if(insertedSuccessfully)
Toast.makeText(this,"inserted",Toast.LENGTH_LONG).show();
else Toast.makeText(this,"not inserted",Toast.LENGTH_LONG).show();
}
}
logcat
01-20 19:59:47.888 9565-9565/com.example.paulcosma.app2 E/InstantRun:
Could not find slices in APK; aborting. 01-20 19:59:47.988
9565-9565/com.example.paulcosma.app2 E/dalvikvm: Could not find class
'android.graphics.drawable.RippleDrawable', referenced from method
android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
01-20 19:59:48.005 9565-9565/com.example.paulcosma.app2 E/TextView:
zhangcl: get font resource from application failed. 01-20
19:59:48.013 9565-9565/com.example.paulcosma.app2 E/TextView: zhangcl:
get font resource from application failed -- 2. 01-20 19:59:48.045
9565-9565/com.example.paulcosma.app2 E/TextView: zhangcl: get font
resource from application failed. 01-20 20:00:02.211
9565-9565/com.example.paulcosma.app2 E/SQLiteLog: (10) Failed to do
file read, got: 0, amt: 100, last Errno: 2 01-20 20:00:02.244
9565-9565/com.example.paulcosma.app2 E/SQLiteLog: (1) unknown database
foods 01-20 20:00:02.263 9565-9565/com.example.paulcosma.app2
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.paulcosma.app2, PID: 9565
java.lang.IllegalStateException: Could not execute method for
android:onClick
You've got a typo in onCreate(). You're using dbName instead of tableName to create your table, therefore when you're running your query which is looking up the correct name, you're looking up a table that doesn't exist. So:
db.execSQL("create table " + dbName + "( " + colId + " INTEGER PRIMARY KEY AUTOINCREMENT," + colName + " TEXT," + colCarbs + " REAL)");
needs to become:
db.execSQL("create table " + tableName + "( " + colId + " INTEGER PRIMARY KEY AUTOINCREMENT," + colName + " TEXT," + colCarbs + " REAL)");
I was writing an app using Android Studio. It's simple app for exercises.
I was sure it will work, but no. Something is wrong.
I will paste my code here:
package programowanie.android.sql;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DatabaseHelper db;
EditText editTextImie;
EditText editTextNazwisko;
EditText editTextTelefon;
EditText editTextEmail;
EditText editTextUlica;
EditText editTextKod;
Button btDodaj;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(this);
editTextImie = (EditText) findViewById(R.id.editTextImie);
editTextNazwisko = (EditText) findViewById(R.id.editTextNazwisko);
editTextTelefon = (EditText) findViewById(R.id.editTextTelefon);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextUlica = (EditText) findViewById(R.id.editTextUlica);
editTextKod = (EditText) findViewById(R.id.editTextKod);
btDodaj = (Button) findViewById(R.id.btDodaj);
btDodaj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean czysieudalo;
czysieudalo = db.wstawdane(editTextImie.getText().toString(), editTextNazwisko.getText().toString(), editTextTelefon.getText().toString(), editTextEmail.getText().toString(), editTextUlica.getText().toString(), editTextKod.getText().toString());
if(czysieudalo){
Toast.makeText(MainActivity.this, "Udało się!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Niestety nie udało się :(!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
This is my DatabaseHelper class:
package programowanie.android.sql;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Kudłaty on 2016-02-19.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String database_name ="Kontakty";
public static final String database_table ="Osoby";
public DatabaseHelper(Context context) {
super(context, database_name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table" + database_table + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, IMIE TEXT, NAZWISKO TEXT, NUMER_TELEFONU TEXT, EMAIL TEXT, ULICA TEXT, KOD_MIASTO TEXT");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST" + database_table);
onCreate(db);
}
public boolean wstawdane(String imie, String nazwisko, String nr_tel, String email, String ulica, String kod ){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("Imie", imie);
cv.put("Nazwisko", nazwisko);
cv.put("Nr telefonu", nr_tel);
cv.put("Email", email);
cv.put("Ulica", ulica);
cv.put("Kod pocztowy", kod);
if (db.insert(database_table, null, cv)==-1){
return false;
} else {
return true;
}
}
}
I have no errors, but when I'm trying to add Record app stopping and I get "SQL has stopped"
I forgot to paste Log! Here u are!
02-19 18:02:43.119 2087-2087/programowanie.android.sql I/art: Not late-enabling -Xcheck:jni (already on)
02-19 18:02:43.195 2087-2087/programowanie.android.sql W/System: ClassLoader referenced unknown path: /data/app/programowanie.android.sql-1/lib/x86
02-19 18:02:43.348 2087-2115/programowanie.android.sql D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-19 18:02:43.410 2087-2115/programowanie.android.sql I/OpenGLRenderer: Initialized EGL, version 1.4
02-19 18:02:43.544 2087-2115/programowanie.android.sql W/EGL_emulation: eglSurfaceAttrib not implemented
02-19 18:02:43.544 2087-2115/programowanie.android.sql W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xabdff300, error=EGL_SUCCESS
02-19 18:03:19.132 2087-2087/programowanie.android.sql E/SQLiteLog: (1) near "tableOsoby": syntax error
02-19 18:03:19.133 2087-2087/programowanie.android.sql D/AndroidRuntime: Shutting down VM
02-19 18:03:19.133 2087-2087/programowanie.android.sql E/AndroidRuntime: FATAL EXCEPTION: main
Process: programowanie.android.sql, PID: 2087
android.database.sqlite.SQLiteException: near "tableOsoby": syntax error (code 1): , while compiling: create tableOsoby(ID INTEGER PRIMARY KEY AUTOINCREMENT, IMIE TEXT, NAZWISKO TEXT, NUMER_TELEFONU TEXT, EMAIL TEXT, ULICA TEXT, KOD_MIASTO TEXT
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at programowanie.android.sql.DatabaseHelper.onCreate(DatabaseHelper.java:21)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at programowanie.android.sql.DatabaseHelper.wstawdane(DatabaseHelper.java:31)
at programowanie.android.sql.MainActivity$1.onClick(MainActivity.java:43)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
change this
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table" + database_table + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, IMIE TEXT, NAZWISKO TEXT, NUMER_TELEFONU TEXT, EMAIL TEXT, ULICA TEXT, KOD_MIASTO TEXT");
}
to this
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + database_table + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, IMIE TEXT, NAZWISKO TEXT, NUMER_TELEFONU TEXT, EMAIL TEXT, ULICA TEXT, KOD_MIASTO TEXT);");
}
you had no spaces between 'table and (ID' so your command would have been
"create tableOsoby(ID INTEGER PRIMARY KEY AUTOINCREMENT, IMIE TEXT, NAZWISKO TEXT, NUMER_TELEFONU TEXT, EMAIL TEXT, ULICA TEXT, KOD_MIASTO TEXT"
which wont run.
Also I noticed you forgot the ) and you have forgotten the ; at the end of the statement.You must remember the ; for security reasons
Given the error log:
android.database.sqlite.SQLiteException: near "tableOsoby": syntax error (code 1): , while compiling: create tableOsoby(ID INTEGER PRIMARY KEY AUTOINCREMENT, IMIE TEXT, NAZWISKO TEXT, NUMER_TELEFONU TEXT, EMAIL TEXT, ULICA TEXT, KOD_MIASTO TEXT
I identified here two issues that probably led the SQLite to crash:
1) On the line db.execSQL("create table" + database_table + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, IMIE TEXT, NAZWISKO TEXT, NUMER_TELEFONU TEXT, EMAIL TEXT, ULICA TEXT, KOD_MIASTO TEXT"); it is missing a space between the "create table" string and the table name variable, resulting in "create tableOsoby". Same occours with the next concatenated string.
2) The closing parenthesis is missing in the string "(ID INTEGER PRIMARY KEY AUTOINCREMENT, IMIE TEXT, NAZWISKO TEXT, NUMER_TELEFONU TEXT, EMAIL TEXT, ULICA TEXT, KOD_MIASTO TEXT".
The corrected line should be:
db.execSQL("create table " + database_table + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, IMIE TEXT, NAZWISKO TEXT, NUMER_TELEFONU TEXT, EMAIL TEXT, ULICA TEXT, KOD_MIASTO TEXT)");
I have an Android project (running in emulator) in which clicking the 'Novels' button on the main menu should lead to the values of pieces where the typeField = 0 (ie false) in the 'pieceTable' in the SQL database being displayed in a ListActivity through an ArrayList.
However, when the Novels button is clicked, the application is stopped and a dialogue box shown, stating 'Unfortunately, EnglishLitRevision has stopped'. There is no LogCat output.
I wouldn't be surprised if this is a very basic error out of ignorance, but I would be grateful if anyone can identify the problem.
UPDATE - filter was not set to 'error' on LogCat!
LogCat output is shown below:
01-02 18:26:06.344: E/AndroidRuntime(548): FATAL EXCEPTION: main
01-02 18:26:06.344: E/AndroidRuntime(548): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lawson.englishlitrevision/com.lawson.englishlitrevision.Novel}: java.lang.NullPointerException
01-02 18:26:06.344: E/AndroidRuntime(548): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.app.ActivityThread.access$600(ActivityThread.java:123)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.os.Handler.dispatchMessage(Handler.java:99)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.os.Looper.loop(Looper.java:137)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-02 18:26:06.344: E/AndroidRuntime(548): at java.lang.reflect.Method.invokeNative(Native Method)
01-02 18:26:06.344: E/AndroidRuntime(548): at java.lang.reflect.Method.invoke(Method.java:511)
01-02 18:26:06.344: E/AndroidRuntime(548): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-02 18:26:06.344: E/AndroidRuntime(548): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-02 18:26:06.344: E/AndroidRuntime(548): at dalvik.system.NativeStart.main(Native Method)
01-02 18:26:06.344: E/AndroidRuntime(548): Caused by: java.lang.NullPointerException
01-02 18:26:06.344: E/AndroidRuntime(548): at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.widget.ListView.setAdapter(ListView.java:460)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.app.ListActivity.setListAdapter(ListActivity.java:265)
01-02 18:26:06.344: E/AndroidRuntime(548): at com.lawson.englishlitrevision.Novel.onCreate(Novel.java:24)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.app.Activity.performCreate(Activity.java:4465)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
01-02 18:26:06.344: E/AndroidRuntime(548): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
01-02 18:26:06.344: E/AndroidRuntime(548): ... 11 more
I would be grateful if anyone can identify the cause of the error.
Code from three relevant classes is shown below.
Main Menu:
/**
* Main Menu (launcher item)
* #author Daniel Lawson
* #Version 29/12/13
*/
package com.lawson.englishlitrevision;
import android.os.Bundle;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainMenu extends Activity {
/** Button for accessing novels area */
private Button novelBut;
/** Button for accessing plays area */
private Button playBut;
/** Button for viewing progress/statistics */
private Button progressBut;
/** Button for viewing about screen */
private Button aboutBut;
/** Button for exiting the application */
private Button exitBut;
/**
* Method called when activity is started. Sets up required data.
*
* #param savedInstanceState
* : The saved state of the application
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Sets up layout
setContentView(R.layout.main_menu_layout);
createButton();
}
/** Sets up the buttons */
public void createButton() {
novelBut = (Button) findViewById(R.id.novelBut);
playBut = (Button) findViewById(R.id.playBut);
progressBut = (Button) findViewById(R.id.addNovBut);
aboutBut = (Button) findViewById(R.id.aboutBut);
exitBut = (Button) findViewById(R.id.exitBut);
}
/**
* Method called when novel button is clicked. Starts novel activity.
*
* #param novBut
* : The view of the novel button, which has been clicked.
*/
public void goNovel(View novBut) {
startActivity(new Intent(this, Novel.class));
}
/**
* Method called when play button is clicked. Starts play activity.
*
* #param playBut
* : The view of the play button, which has been clicked.
*/
public void goPlay(View playBut) {
startActivity(new Intent(this, Play.class));
}
/**
* Method called when progress button is clicked. Starts stats activity.
*
* #param progBut
* : The view of the progress button, which has been clicked.
*/
public void goStats(View progBut) {
startActivity(new Intent(this, Stats.class));
}
/**
* Method called when abpit button is clicked. Starts about activity.
*
* #param aboutBut
* : The view of the about button, which has been clicked.
*/
public void goAbout(View aboutBut) {
startActivity(new Intent(this, About.class));
}
/**
* Method called when exit button is clicked. Quits application.
*
* #param closeBut
* : The view of the exit button, which has been clicked.
*/
public void goClose(View closeBut) {
this.finish();
}
}
Novel:
package com.lawson.englishlitrevision;
import java.util.ArrayList;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.content.Context;
public class Novel extends ListActivity {
ArrayList<String> novels = new ArrayList<String>();
#Override
public void onCreate(Bundle icicle) {
ManipulateDatabase md = new ManipulateDatabase(this);
super.onCreate(icicle);
novels = md.getPieces("0");
setContentView(R.layout.novel_layout);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, novels));
}
public void addNovel() {
// show text input
// add the String put in to database as new novel
// update list
}
public void deleteNovel() {
// show checkboxes
// allow selection
// delete selected records from database
// update list
}
}
ManipulateDatabase:
/**
* Contains SQL statements and manages connections
*
* #author Daniel Lawson
* #version 29/12/13
*/
package com.lawson.englishlitrevision;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import java.util.ArrayList;
import java.util.Scanner;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class ManipulateDatabase {
/** String representing the name of the database */
private static final String databaseName = "EnglishDatabase.db";
/** Int representing the current version of the database */
private static final int databaseVersion = 1;
// ----------------------------------------------------------------------------------
/**
* String representing the table that stores the name of the piece and
* whether it is a play or not.
*/
private static final String pieceTable = "pieceTable";
/**
* String representing the table that stores the name of the point made,
* which piece it belongs to, and which element it pertains to.
*/
private static final String specificTable = "specificTable";
/**
* String representing the table that stores the element, the piece it
* belongs to, and whether or not it is a character.
*/
private static final String elementTable = "elementTable";
/**
* String representing the table that stores the quote and the point it
* links to.
*/
private static final String quoteTable = "quoteTable";
/**
* String representing the table that stores the piece and the
* correct/incorrect responses on various dates
*/
private static final String statsTable = "statsTable";
// ----------------------------------------------------------------------------------
/** String representing the piece field of the piece table */
private static final String pieceField = "piece";
/** String representing the type field of the piece table */
private static final String typeField = "isPlay";
/** String representing the point field of the specific table */
private static final String pointField = "point";
/** String representing the element field of the element table */
private static final String elementField = "element";
/** String representing the elType field of the element table */
private static final String elTypeField = "isCharacter";
/** String representing the quote field of the quote table */
private static final String quoteField = "quote";
/** String representing the ID field of the stats table */
private static final String idField = "statId";
/** String representing the correct field of the stats table */
private static final String correctField = "correct";
/** String representing the incorrect field of the stats table */
private static final String incorrectField = "incorrect";
/** String representing the date field of the stats table */
private static final String dateField = "date";
// ----------------------------------------------------------------------------------
/** String array representing all the fields of the piece table */
private static final String[] pieceTableFields = { pieceField, typeField };
/** String array representing all the fields of the specific table */
private static final String[] specificTableFields = { pointField,
pieceField, elementField };
/** String array representing all the fields of the quote table */
private static final String[] quoteTableFields = { quoteField, pointField };
/** String array representing all the fields of the element table */
private static final String[] elementTableFields = { elementField,
pieceField, elTypeField };
/** String array representing all the fields of the stats table */
private static final String[] statsTableFields = { idField, pieceField,
correctField, incorrectField, dateField };
// ----------------------------------------------------------------------------------
/** SQL statement to create the piece table. */
private static final String createPieceTable = "CREATE TABLE " + pieceTable
+ " (" + pieceField + " TEXT NOT NULL PRIMARY KEY, " + typeField
+ " INTEGER);";
/** SQL statement to create the specific table. */
private static final String createSpecificTable = "CREATE TABLE "
+ specificTable + "(" + pointField + " TEXT NOT NULL PRIMARY KEY,"
+ pieceField + " TEXT NOT NULL," + elementField + " TEXT NOT NULL)";
/** SQL statement to create the quotes table. */
private static final String createQuoteTable = "CREATE TABLE " + quoteTable
+ "(" + quoteField + " TEXT NOT NULL PRIMARY KEY," + pointField
+ " TEXT NOT NULL PRIMARY KEY)";
/** SQL statement to create the element table. */
private static final String createElementTable = "CREATE TABLE "
+ elementTable + "(" + elementField + " TEXT NOT NULL PRIMARY KEY,"
+ pieceField + " TEXT NOT NULL," + elTypeField + " INTEGER)";
/** SQL statement to create the stats table. */
private static final String createStatsTable = "CREATE TABLE " + statsTable
+ "(" + idField + " INTEGER PRIMARY KEY," + pieceField
+ " TEXT NOT NULL," + correctField + " INTEGER," + incorrectField
+ " INTEGER," + dateField + " DATE)";
// ----------------------------------------------------------------------------------
/**
* SQL statement to search the piece table - replace [columnName] and
* [value] with field to be searched and what value to look for.
*/
private static final String searchPieceTable = "SELECT * FROM "
+ pieceTable + " WHERE [columnName] = '[value]';";
/**
* SQL statement to search the specific table - replace [columnName] and
* [value] with field to be searched and what value to look for.
*/
private static final String searchSpecificTable = "SELECT * FROM "
+ specificTable + " WHERE [columnName] = '[value]'";
/**
* SQL statement to search the quote table - replace [columnName] and
* [value] with field to be searched and what value to look for.
*/
private static final String searchQuoteTable = "SELECT * FROM "
+ quoteTable + " WHERE [columnName] = '[value]'";
/**
* SQL statement to search the element table - replace [columnName] and
* [value] with field to be searched and what value to look for.
*/
private static final String searchElementTable = "SELECT * FROM "
+ elementTable + " WHERE [columnName] = '[value]'";
/**
* SQL statement to search the stats table - replace [columnName] and
* [value] with field to be searched and what value to look for.
*/
private static final String searchStatsTable = "SELECT * FROM "
+ statsTable + " WHERE [columnName] = '[value]'";
// ----------------------------------------------------------------------------------
/**
* SQL statement to update the piece table - replace [assignValues] and
* [condition] with items to be altered + their new values and the condition
* where if true, this change should be applied.
*/
private static final String updatePieceTable = "UPDATE " + pieceTable
+ " SET [assignValues] WHERE [condition]";
/**
* SQL statement to update the specific table - replace [assignValues] and
* [condition] with items to be altered + their new values and the condition
* where if true, this change should be applied.
*/
private static final String updateSpecificTable = "UPDATE " + specificTable
+ " SET [assignValues] WHERE [condition]";
/**
* SQL statement to update the quote table - replace [assignValues] and
* [condition] with items to be altered + their new values and the condition
* where if true, this change should be applied.
*/
private static final String updateQuoteTable = "UPDATE " + quoteTable
+ " SET [assignValues] WHERE [condition]";
/**
* SQL statement to update the element table - replace [assignValues] and
* [condition] with items to be altered + their new values and the condition
* where if true, this change should be applied.
*/
private static final String updateElementTable = "UPDATE " + elementTable
+ " SET [assignValues] WHERE [condition]";
/**
* SQL statement to update the stats table - replace [assignValues] and
* [condition] with items to be altered + their new values and the condition
* where if true, this change should be applied.
*/
private static final String updateStatsTable = "UPDATE " + statsTable
+ " SET [assignValues] WHERE [condition]";
// ----------------------------------------------------------------------------------
/**
* SQL statement to delete from the piece table - replace [condition] the
* condition where if true, this deletion should be applied.
*/
private static final String deleteFromPieceTable = "DELETE FROM "
+ pieceTable + " WHERE [condition]";
/**
* SQL statement to delete from the specific table - replace [condition] the
* condition where if true, this deletion should be applied.
*/
private static final String deleteFromSpecificTable = "DELETE FROM "
+ specificTable + " WHERE [condition]";
/**
* SQL statement to delete from the quote table - replace [condition] the
* condition where if true, this deletion should be applied.
*/
private static final String deleteFromQuoteTable = "DELETE FROM "
+ quoteTable + " WHERE [condition]";
/**
* SQL statement to delete from the element table - replace [condition] the
* condition where if true, this deletion should be applied.
*/
private static final String deleteFromElementTable = "DELETE FROM "
+ elementTable + " WHERE [condition]";
/**
* SQL statement to delete from the stats table - replace [condition] the
* condition where if true, this deletion should be applied.
*/
private static final String deleteFromStatsTable = "DELETE FROM "
+ statsTable + " WHERE [condition]";
// ----------------------------------------------------------------------------------
/**
* SQL statement to insert into the piece table - replace [values] with the
* values to be inserted.
*/
private static final String insertIntoPieceTable = "INSERT INTO "
+ pieceTable + " VALUES ([values])";
/**
* SQL statement to insert into the specific table - replace [values] with
* the values to be inserted.
*/
private static final String insertIntoSpecificTable = "INSERT INTO "
+ specificTable + " VALUES ([values])";
/**
* SQL statement to insert into the quote table - replace [values] with the
* values to be inserted.
*/
private static final String insertIntoQuoteTable = "INSERT INTO "
+ quoteTable + " VALUES ([values])";
/**
* SQL statement to insert into the element table - replace [values] with
* the values to be inserted.
*/
private static final String insertIntoElementTable = "INSERT INTO "
+ elementTable + " VALUES ([values])";
/**
* SQL statement to insert into the quote table - replace [values] with the
* values to be inserted.
*/
private static final String insertIntoStatsTable = "INSERT INTO "
+ statsTable + " VALUES ([values])";
// ----------------------------------------------------------------------------------
/**
* SQLiteDatabase representing the English database
*/
private SQLiteDatabase dataBase;
/**
* Instance of DatabaseHelper class utilised to 'access' database
*/
private DatabaseHelper baseHelper;
/**
* Content of the Database Manipulator (ManipulateDatabase class)
*/
private Activity context;
/**
* Boolean to store whether or not this is the first time this base/version
* has been launched
*/
private boolean initialLaunch = false;
/**
* Scanners to read the .txt lists to to input to database
*/
private Scanner pieceScan = new Scanner("pieceList.txt");
private Scanner specificScan = new Scanner("specificList.txt");
private Scanner elementScan = new Scanner("elementList.txt");
private Scanner quoteScan = new Scanner("quoteList.txt");
/**
* Method to open the database
*/
private void openSesame() {
try {
dataBase = baseHelper.getWritableDatabase();
} catch (SQLiteException e) {
System.out.println("Database couldn't be opened");
e.printStackTrace();
}
}
/**
* Method to close the database
*/
private void closeSesame() {
baseHelper.close();
}
public ArrayList<String> getPieces(String typePiece) {
try {
openSesame();
ArrayList<String> pieces = new ArrayList<String>();
String command = searchPieceTable
.replace("[columnName]", typeField);
command = command.replace("[value]", typePiece);
Cursor cursor = dataBase.rawQuery(command, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
pieces.add(cursor.getString(cursor.getColumnIndex(pieceField)));
cursor.moveToNext();
}
closeSesame();
return pieces;
} catch (SQLiteException e) {
e.printStackTrace();
System.out.println("SQL Problem");
return null;
}
}
/**
* Constructor
*
* #param contextIn
* Context of the MainpulateDatabase class
*/
public ManipulateDatabase(Activity contextIn) {
baseHelper = new DatabaseHelper(contextIn);
context = contextIn;
openSesame();
String line;
String pieceName;
String isDrama;
String point;
String element;
String quote;
String isCharacter;
int commaPoint;
int commaPoint2;
if (initialLaunch) {
while (pieceScan.hasNext()) {
line = pieceScan.nextLine();
commaPoint = line.indexOf(",");
pieceName = line.substring(0, commaPoint);
isDrama = line.substring(commaPoint + 1, line.length() - 1);
ContentValues pv = new ContentValues();
pv.put(pieceField, pieceName);
pv.put(typeField, isDrama);
dataBase.insert(pieceTable, null, pv);
System.out.println("DAMN YOU MORONIC CRETIN!!");
}
while (specificScan.hasNext()) {
line = specificScan.nextLine();
commaPoint = line.indexOf(",");
point = line.substring(0, commaPoint);
commaPoint2 = (line
.substring(commaPoint + 1, line.length() - 1)
.indexOf(","));
pieceName = line.substring(commaPoint + 1, commaPoint2);
element = line.substring(commaPoint2 + 1, line.length() - 1);
ContentValues sv = new ContentValues();
sv.put(pointField, point);
sv.put(pieceField, pieceName);
sv.put(elementField, element);
dataBase.insert(specificTable, null, sv);
}
while (elementScan.hasNext()) {
line = elementScan.nextLine();
commaPoint = line.indexOf(",");
element = line.substring(0, commaPoint);
commaPoint2 = (line
.substring(commaPoint + 1, line.length() - 1)
.indexOf(","));
pieceName = line.substring(commaPoint + 1, commaPoint2);
isCharacter = line
.substring(commaPoint2 + 1, line.length() - 1);
ContentValues ev = new ContentValues();
ev.put(elementField, element);
ev.put(pieceField, pieceName);
ev.put(elTypeField, isCharacter);
dataBase.insert(elementTable, null, ev);
}
while (quoteScan.hasNext()) {
line = quoteScan.nextLine();
commaPoint = line.indexOf(",");
quote = line.substring(0, commaPoint);
point = line.substring(commaPoint + 1, line.length() - 1);
ContentValues qv = new ContentValues();
qv.put(quoteField, quote);
qv.put(pointField, point);
dataBase.insert(quoteTable, null, qv);
}
}
}
// ----------------------------------------------------------------------------------
/**
* Database helper - Three basic methods - required database tasks
*
* #author Daniel Lawson
* #version 30/12/13
*/
private class DatabaseHelper extends SQLiteOpenHelper {
private DatabaseHelper(Context theContext) {
super(theContext, databaseName, null, databaseVersion);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(createPieceTable);
/*
* db.execSQL(createSpecificTable);
* db.execSQL(createQuoteTable); db.execSQL(createElementTable);
* db.execSQL(createStatsTable);
*/
// initialLaunch = true;
} catch (SQLiteException e) {
System.out.println("Failed to create table(s)");
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + pieceTable);
db.execSQL("DROP TABLE IF EXISTS " + specificTable);
db.execSQL("DROP TABLE IF EXISTS " + quoteTable);
db.execSQL("DROP TABLE IF EXISTS " + elementTable);
db.execSQL("DROP TABLE IF EXISTS " + statsTable);
onCreate(db);
}
}
}
This is the place on which you should look in logcat:
01-02 18:26:06.344: E/AndroidRuntime(548): Caused by: java.lang.NullPointerException
01-02 18:26:06.344: E/AndroidRuntime(548): at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
probably this call:
novels = md.getPieces("0");
returns null value, but from what I see this should happen only when there is an exception inside:
public ArrayList<String> getPieces(String typePiece) {
so look for problem in this function.
novels ArrayList is null
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4_r1/android/widget/ArrayAdapter.java/
Caused by: java.lang.NullPointerException
01-02 18:26:06.344: E/AndroidRuntime(548): at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
ArrayAdapter.java:330
328
329 public int getCount() {
330 return mObjects.size();
331 }
ArrayAdapter uses getCount which returns the size of the list indicating novels is null which means you should look at
novels = md.getPieces("0");