Accessing inner class method from causes nullpointerexception - java

I am trying to add database in my app.I wrote this class:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "testDb";
private static final String TABLE_KISILER = "loginCre";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "username";
private static final String KEY_PASS = "password";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Database Oluşturma işlemi.
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_KISILER_TABLE = "CREATE TABLE " + TABLE_KISILER + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " VARCHAR(50),"
+ KEY_PASS + " VARCHAR(50)" + ")";
db.execSQL(CREATE_KISILER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_KISILER);
onCreate(db);
}
//CRUD
// Yeni Kayıt Eklemek.
public void addLoginInfo(String username,String password) {
/*
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, username); // Kisi Adı Getir
values.put(KEY_PASS, password); // Kisi Soyadı Getir
// Ekleme işlemi...
db.insert(TABLE_KISILER, null, values);
db.close(); // Açık olan database i kapat.
*/
}
}
I want to access addLoginInfo method from main activity then I used this lines in onCreate
private DatabaseHandler _db;
_db.addLoginInfo("test", "test");
But I app is crashing.There is the logcat:
12-05 11:24:55.802: E/AndroidRuntime(2841): FATAL EXCEPTION: main
12-05 11:24:55.802: E/AndroidRuntime(2841): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.impact.xxx/com.impact.xxx.MainActivity}: java.lang.NullPointerException
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.os.Handler.dispatchMessage(Handler.java:99)
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.os.Looper.loop(Looper.java:137)
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-05 11:24:55.802: E/AndroidRuntime(2841): at java.lang.reflect.Method.invokeNative(Native Method)
12-05 11:24:55.802: E/AndroidRuntime(2841): at java.lang.reflect.Method.invoke(Method.java:525)
12-05 11:24:55.802: E/AndroidRuntime(2841): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-05 11:24:55.802: E/AndroidRuntime(2841): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-05 11:24:55.802: E/AndroidRuntime(2841): at dalvik.system.NativeStart.main(Native Method)
12-05 11:24:55.802: E/AndroidRuntime(2841): Caused by: java.lang.NullPointerException
12-05 11:24:55.802: E/AndroidRuntime(2841): at com.impact.xxx.MainActivity.onCreate(MainActivity.java:164)
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.Activity.performCreate(Activity.java:5133)
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-05 11:24:55.802: E/AndroidRuntime(2841): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
12-05 11:24:55.802: E/AndroidRuntime(2841): ... 11 more
Why I am getting nullPointerException ?

you are not initializing _db object.try this :
private DatabaseHandler _db = new DatabaseHandler(this);
_db.addLoginInfo("test", "test");

In your activity put these lines, i hope it will work
DatabaseHandler _db = new DatabaseHandler(this);
_db.getWritableDatabase();
_db.addLoginInfo("test", "test");

Related

How to create a local database in android for my application

I want to create a simple database for my android application in sqlite. I just want to add my values to the table.
This is my code but this is not working for me because the table is not shown at DDMS.
public class QuickSubmitContext extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "submitManager";
private static final String TABLE_CONTACTS = "submit";
private static final String KEY_ID = "id";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_DNCA = "donotca";
private static final String KEY_CA = "callagain";
private static final String KEY_NOTE = "note";
public QuickSubmitContext(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_PH_NO + " TEXT,"
+ KEY_DNCA + " TEXT," + KEY_CA + " TEXT," + KEY_NOTE + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
}
Logcat
10-21 04:39:00.230: E/AndroidRuntime(835): FATAL EXCEPTION: main
10-21 04:39:00.230: E/AndroidRuntime(835): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aspeage.quikw/com.aspeage.quikw.FragmentLayout}: java.lang.NullPointerException
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.os.Handler.dispatchMessage(Handler.java:99)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.os.Looper.loop(Looper.java:137)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-21 04:39:00.230: E/AndroidRuntime(835): at java.lang.reflect.Method.invokeNative(Native Method)
10-21 04:39:00.230: E/AndroidRuntime(835): at java.lang.reflect.Method.invoke(Method.java:511)
10-21 04:39:00.230: E/AndroidRuntime(835): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-21 04:39:00.230: E/AndroidRuntime(835): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-21 04:39:00.230: E/AndroidRuntime(835): at dalvik.system.NativeStart.main(Native Method)
10-21 04:39:00.230: E/AndroidRuntime(835): Caused by: java.lang.NullPointerException
10-21 04:39:00.230: E/AndroidRuntime(835): at com.aspeage.quikw.FragmentLayout.onCreate(FragmentLayout.java:79)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.Activity.performCreate(Activity.java:5104)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-21 04:39:00.230: E/AndroidRuntime(835): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
10-21 04:39:00.230: E/AndroidRuntime(835): ... 11 more
10-21 04:39:07.090: I/Process(835): Sending signal. PID: 835 SIG: 9
10-21 04:39:13.050: E/Trace(866): error opening trace file: No such file or directory (2)
The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate() method, in which you can execute a SQLite command to create tables in the database. For example:
public class DictionaryOpenHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DICTIONARY_TABLE_NAME = "dictionary";
private static final String DICTIONARY_TABLE_CREATE =
"CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +
KEY_WORD + " TEXT, " +
KEY_DEFINITION + " TEXT);";
DictionaryOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DICTIONARY_TABLE_CREATE);
}
}
Here are instructions. http://developer.android.com/guide/topics/data/data-storage.html#db

Fatal Exception when viewing/ writing database SQLite?

I get an error when I run my emulator, and try to start reading or viewing the database..
Please see my logcat at the bottum of this page!
I have a Database activity, a SQLView activity, and an SQLite activity.
The database activity is to run the database, the SQLView activity to view the database, and the last one, my SQLite activity is to wrie to my database.
I use SQLiteAssetHelper, and my .rar file is in my assets/databases/Voedsel.rar .
This are my activities:
My database activity:
package com.jacob.eindproject;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import java.sql.*;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class Database extends SQLiteAssetHelper {
public static final String KEY_PRODUCT = "Product";
public static final String KEY_EENHEID = "Eenheid";
public static final String KEY_KCAL = "Kcal";
private static final String DATABASE_NAME = "Voedsel";
private static final String DATABASE_TABLE = "Voeding";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private Context Context;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteAssetHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, context.getExternalFilesDir(null).getAbsolutePath(), null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
}
#Override
public void onUpgrade(SQLiteDatabase Voedsel, int oldVersion, int newVersion) {
Voedsel.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(Voedsel);
}
public Database(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public Database open() throws SQLException{
ourHelper = new DbHelper(Context);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String product, String kcal, String eenheid) {
ContentValues cv = new ContentValues();
cv.put(KEY_PRODUCT, product);
cv.put(KEY_EENHEID, eenheid);
cv.put(KEY_KCAL, kcal);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_PRODUCT, KEY_EENHEID, KEY_KCAL};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iProduct = c.getColumnIndex(KEY_PRODUCT);
int iEenheid = c.getColumnIndex(KEY_EENHEID);
int iKcal = c.getColumnIndex(KEY_KCAL);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iProduct) + " " + c.getString(iEenheid) + " " + c.getString(iKcal) + "\n";
}
return result;
}
public void close(Database database) {
// TODO Auto-generated method stub
}
}
My SQLite activity:
public class SQLite extends Activity implements View.OnClickListener {
Button sqlUpdate, sqlView;
EditText sqlVoeding, sqlKcal, sqlEenheid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqllite);
sqlUpdate = (Button) findViewById(R.id.bSQLUpdate);
sqlVoeding = (EditText) findViewById(R.id.etSQLVoeding);
sqlEenheid = (EditText) findViewById(R.id.etSQLEenheid);
sqlKcal = (EditText) findViewById(R.id.etSQLKcal);
sqlView = (Button) findViewById(R.id.bSQLopenView);
sqlView.setOnClickListener((android.view.View.OnClickListener) this);
sqlUpdate.setOnClickListener((android.view.View.OnClickListener) this);
}
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bSQLUpdate:
boolean didItWork = true;
try{
String voeding = sqlVoeding.getText().toString();
String Kcal = sqlKcal.getText().toString();
String eenheid = sqlEenheid.getText().toString();
Database entry = new Database(SQLite.this);
entry.open();
entry.createEntry(voeding, Kcal, eenheid);
entry.close();
}catch (Exception e ){
didItWork = false;
}finally{
if (didItWork){
Dialog d = new Dialog(this);
d.setTitle("Heak Yeay");
TextView tv = new TextView(this);
tv.setText("Succes");
d.setContentView(tv);
d.show();
}
}
break;
case R.id.bSQLopenView:
Intent i = new Intent(this, SQLView.class);
startActivity(i);
}
}
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
And the SQLView activity:
public class SQLView extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlview);
TextView tv = (TextView) findViewById(R.id.tvSQLinfo);
Database info = new Database(this);
info.open();
String data = info.getData();
info.close();
tv.setText(data);
}
}
This is my logcat error when I click the SQLView activity:
12-16 14:28:26.883: E/AndroidRuntime(1170): FATAL EXCEPTION: main
12-16 14:28:26.883: E/AndroidRuntime(1170): java.lang.NoClassDefFoundError: com.jacob.eindproject.Database
12-16 14:28:26.883: E/AndroidRuntime(1170): at com.jacob.eindproject.SQLView.onCreate(SQLView.java:14)
12-16 14:28:26.883: E/AndroidRuntime(1170): at android.app.Activity.performCreate(Activity.java:5133)
12-16 14:28:26.883: E/AndroidRuntime(1170): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-16 14:28:26.883: E/AndroidRuntime(1170): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
12-16 14:28:26.883: E/AndroidRuntime(1170): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
12-16 14:28:26.883: E/AndroidRuntime(1170): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-16 14:28:26.883: E/AndroidRuntime(1170): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
12-16 14:28:26.883: E/AndroidRuntime(1170): at android.os.Handler.dispatchMessage(Handler.java:99)
12-16 14:28:26.883: E/AndroidRuntime(1170): at android.os.Looper.loop(Looper.java:137)
12-16 14:28:26.883: E/AndroidRuntime(1170): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-16 14:28:26.883: E/AndroidRuntime(1170): at java.lang.reflect.Method.invokeNative(Native Method)
12-16 14:28:26.883: E/AndroidRuntime(1170): at java.lang.reflect.Method.invoke(Method.java:525)
12-16 14:28:26.883: E/AndroidRuntime(1170): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-16 14:28:26.883: E/AndroidRuntime(1170): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-16 14:28:26.883: E/AndroidRuntime(1170): at dalvik.system.NativeStart.main(Native Method)
And this is my error when I click my 'write' activity:
12-16 14:27:35.913: E/AndroidRuntime(999): FATAL EXCEPTION: main
12-16 14:27:35.913: E/AndroidRuntime(999): java.lang.NoClassDefFoundError: com.jacob.eindproject.Database
12-16 14:27:35.913: E/AndroidRuntime(999): at com.jacob.eindproject.SQLite.onClick(SQLite.java:45)
12-16 14:27:35.913: E/AndroidRuntime(999): at android.view.View.performClick(View.java:4240)
12-16 14:27:35.913: E/AndroidRuntime(999): at android.view.View$PerformClick.run(View.java:17721)
12-16 14:27:35.913: E/AndroidRuntime(999): at android.os.Handler.handleCallback(Handler.java:730)
12-16 14:27:35.913: E/AndroidRuntime(999): at android.os.Handler.dispatchMessage(Handler.java:92)
12-16 14:27:35.913: E/AndroidRuntime(999): at android.os.Looper.loop(Looper.java:137)
12-16 14:27:35.913: E/AndroidRuntime(999): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-16 14:27:35.913: E/AndroidRuntime(999): at java.lang.reflect.Method.invokeNative(Native Method)
12-16 14:27:35.913: E/AndroidRuntime(999): at java.lang.reflect.Method.invoke(Method.java:525)
12-16 14:27:35.913: E/AndroidRuntime(999): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-16 14:27:35.913: E/AndroidRuntime(999): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-16 14:27:35.913: E/AndroidRuntime(999): at dalvik.system.NativeStart.main(Native Method)
Hopefully someone can help me fix my error. Thank you all in advance for taking your time.
Jacob.
I don't think you've added the SQLiteAssetHelper library to your project correctly.
You must ensure that the build path for your project is correct, and all referenced libraries are selected.
Right click on your project and select 'Properties'
Click on 'Android'
Make sure your SQLiteAssetHelper library is selected

Getting error while inserting the data in data base in android

I am inserting the data from data base using sqlite but I am getting an error .Here is my code and error.I just enter one entry and want to display that entry ?
package com.example.database_example;
public class Information {
String name;
public Information(String name) {
// TODO Auto-generated constructor stub
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Data Base.java class
package com.example.database_example;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Information inf=new Information("naveen");
DataBaseExample dbx=new DataBaseExample(MainActivity.this);
if(dbx.insertname(inf)){
Log.v("checkdbx.insertname(inf);", "save ok.");
}else{
Log.v("checkdbx.insertname(inf);", "save failed.");
}
}
}
package com.example.database_example;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseExample extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "information";
// Contacts table name
private static final String TABLE_Name= "Name";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
public DataBaseExample(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String createTable= "CREATE TABLE " + TABLE_Name+"("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
+ ")";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Name);
// Create tables again
onCreate(db);
}
public boolean insertname(Information information) {
boolean createSuccessful = false;
ContentValues values = new ContentValues();
// values.put(KEY_ID, information.getId());
values.put(KEY_NAME, information.getName());
SQLiteDatabase db = this.getWritableDatabase();
createSuccessful = db.insert(TABLE_Name, null, values) > 0;
db.close();
return createSuccessful;
}
}
Here is my error
09-24 07:25:07.138: I/Database(392): sqlite returned: error code = 1, msg = near ")": syntax error
09-24 07:25:07.138: E/Database(392): Failure 1 (near ")": syntax error) on 0x2a7080 when preparing 'CREATE TABLE Name(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,)'.
09-24 07:25:07.148: D/AndroidRuntime(392): Shutting down VM
09-24 07:25:07.148: W/dalvikvm(392): threadid=1: thread exiting with uncaught exception (group=0x40015560)
09-24 07:25:07.158: E/AndroidRuntime(392): FATAL EXCEPTION: main
09-24 07:25:07.158: E/AndroidRuntime(392): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.database_example/com.example.database_example.MainActivity}: android.database.sqlite.SQLiteException: near ")": syntax error: CREATE TABLE Name(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.os.Handler.dispatchMessage(Handler.java:99)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.os.Looper.loop(Looper.java:123)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.main(ActivityThread.java:3683)
09-24 07:25:07.158: E/AndroidRuntime(392): at java.lang.reflect.Method.invokeNative(Native Method)
09-24 07:25:07.158: E/AndroidRuntime(392): at java.lang.reflect.Method.invoke(Method.java:507)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
09-24 07:25:07.158: E/AndroidRuntime(392): at dalvik.system.NativeStart.main(Native Method)
09-24 07:25:07.158: E/AndroidRuntime(392): Caused by: android.database.sqlite.SQLiteException: near ")": syntax error: CREATE TABLE Name(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.database.sqlite.SQLiteDatabase.native_execSQL(Native Method)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1763)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.example.database_example.DataBaseExample.onCreate(DataBaseExample.java:34)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:126)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.example.database_example.DataBaseExample.insertname(DataBaseExample.java:55)
09-24 07:25:07.158: E/AndroidRuntime(392): at com.example.database_example.MainActivity.onCreate(MainActivity.java:18)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-24 07:25:07.158: E/AndroidRuntime(392): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
09-24 07:25:07.158: E/AndroidRuntime(392): ... 11 more
Change
String createTable= "CREATE TABLE " + TABLE_Name+"("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
+ ")";
to
String createTable= "CREATE TABLE " + TABLE_Name+"("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT"
+ ")";
removing the comma after TEXT
EDIT
To read all the values from the database, you can add the following method to your class DataBaseExample:
private List<Information> getAllItems()
List<Information> itemsList = new ArrayList<Information>();
Cursor cursor = null;
try {
//get all rows
cursor = mDatabase.query(TABLE_Name, null, null, null, null,
null, null);
if (cursor.moveToFirst()) {
do {
Information c = new Information();
c.setName(cursor.getString(KEY_NAME));
itemsList.add(c);
} while (cursor.moveToNext());
}
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
cursor.close();
}
return itemsList;
}

Saving sql database entry created date

I want to save and display the created date for an sql entry. But my app keeps crashing with this code.
Any help would be appreciated!
Here is the Save State Method for saving the note:
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
String color = mColor;
String date=(DateUtils.formatDateTime(this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NUMERIC_DATE ));
//String date = FastDateFormat.getInstance("dd-MM-yyyy").format(System.currentTimeMillis( ));
if(title != null && !title.isEmpty() || body != null && !body.isEmpty()){
if (mRowId == null) {
long id = mDbHelper.createNote(title, body, color, date);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateNote(mRowId, title, body, color, date);
}
}
And here is the Database adapter:
public class NotesDbAdapter {
public static final String KEY_TITLE = "title";
public static final String KEY_BODY = "body";
public static final String KEY_ROWID = "_id";
public static final String KEY_COLOR = "color";
public static final String KEY_DATE = "date";
private static final String TAG = "NotesDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
/**
* Database creation sql statement
*/
private static final String DATABASE_CREATE =
"create table notes (_id integer primary key autoincrement, "
+ "title text not null, body text not null, color text not null, date text not null);";
private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "notes";
private static final int DATABASE_VERSION = 4;
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
public NotesDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public NotesDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long createNote(String title, String body, String color, String date) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_BODY, body);
initialValues.put(KEY_COLOR, color);
initialValues.put(KEY_DATE, date);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteNote(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor fetchAllNotes() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE,
KEY_BODY, KEY_COLOR, KEY_DATE}, null, null, null, null, null);
}
public Cursor fetchNote(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_BODY, KEY_COLOR, KEY_DATE}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateNote(long rowId, String title, String body, String color, String date) {
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_BODY, body);
args.put(KEY_COLOR, color);
args.put(KEY_DATE, date);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
UPDATE
Okay after running it, this was the error log i got:
08-03 16:15:52.816: I/Process(29938): Sending signal. PID: 29938 SIG: 9
08-03 16:15:53.046: E/SQLiteLog(30048): (1) no such column: date
08-03 16:15:53.046: D/AndroidRuntime(30048): Shutting down VM
08-03 16:15:53.046: W/dalvikvm(30048): threadid=1: thread exiting with uncaught exception (group=0x40d23a08)
08-03 16:15:53.056: E/AndroidRuntime(30048): FATAL EXCEPTION: main
08-03 16:15:53.056: E/AndroidRuntime(30048): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.demo.notepad2/com.android.demo.notepad2.Notepadv2}: android.database.sqlite.SQLiteException: no such column: date (code 1): , while compiling: SELECT _id, title, body, color, date FROM notes
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2312)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.app.ActivityThread.access$600(ActivityThread.java:156)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1250)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.os.Handler.dispatchMessage(Handler.java:99)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.os.Looper.loop(Looper.java:137)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.app.ActivityThread.main(ActivityThread.java:5234)
08-03 16:15:53.056: E/AndroidRuntime(30048): at java.lang.reflect.Method.invokeNative(Native Method)
08-03 16:15:53.056: E/AndroidRuntime(30048): at java.lang.reflect.Method.invoke(Method.java:525)
08-03 16:15:53.056: E/AndroidRuntime(30048): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:799)
08-03 16:15:53.056: E/AndroidRuntime(30048): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
08-03 16:15:53.056: E/AndroidRuntime(30048): at dalvik.system.NativeStart.main(Native Method)
08-03 16:15:53.056: E/AndroidRuntime(30048): Caused by: android.database.sqlite.SQLiteException: no such column: date (code 1): , while compiling: SELECT _id, title, body, color, date FROM notes
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
08-03 16:15:53.056: E/AndroidRuntime(30048): at com.android.demo.notepad2.NotesDbAdapter.fetchAllNotes(NotesDbAdapter.java:134)
08-03 16:15:53.056: E/AndroidRuntime(30048): at com.android.demo.notepad2.Notepadv2.fillData(Notepadv2.java:64)
08-03 16:15:53.056: E/AndroidRuntime(30048): at com.android.demo.notepad2.Notepadv2.onCreate(Notepadv2.java:58)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.app.Activity.performCreate(Activity.java:5108)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-03 16:15:53.056: E/AndroidRuntime(30048): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2266)
08-03 16:15:53.056: E/AndroidRuntime(30048): ... 11 more
Error is in your query: change date (and _id too) with another name; usually date is a reserved keyword.
I would have put this in the comment, but my rep is not high enough.
I am pretty sure that there is a way to make the SQL table automatically put the current date and time whenever a new entry is created. Perhaps you could try that? It's been a while since I have worked with SQL though so I might be wrong.

NullPointer with SQLite creation - Android (java)

I am getting a NullPointerException in my SQLite database. I am calling the DatabaseHelper class in Results.java by doing this:
public class Results extends Activity {
...
DatabaseHelper dh;
public void onCreate(Bundle savedInstanceState) {
...
dh = new DatabaseHelper(this);
}
public void showResults() {
...
dh.insert(1, score, percentage);
}
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DB_NAME = "test1";
private static final String DB_PATH = "/data/data/com.example.test/databases/";
private static final String TABLE = "HighscoresList";
// Table columns names.
private static final String RANK = "rank";
private static final String SCORE = "score";
private static final String PERCENTAGE = "percentage";
private SQLiteDatabase myDB;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
myDB = getWritableDatabase(); //Line 25
}
//Insert new record.
public long insert(int rank, long score, int percentage) {
ContentValues values = new ContentValues();
values.put(RANK, rank);
values.put(SCORE, score);
values.put(PERCENTAGE, percentage);
return myDB.insert(TABLE, null, values);
}
//Delete record.
public boolean delete(long score) {
//Need this?
return true;
}
public void openDatabase() throws SQLException {
//Open the database.
String myPath = DB_PATH + DB_NAME;
myDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
public SQLiteDatabase getDatabase(){
return this.myDB;
}
public synchronized void close() {
if(myDB != null) {
myDB.close();
}
super.close();
}
public void onCreate(SQLiteDatabase db) {
myDB.execSQL("CREATE TABLE " + TABLE + " (" //Line 62
+ RANK + " INTEGER,"
+ SCORE + " LONG,"
+ PERCENTAGE + " INTEGER"
+ ");");
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
}
LogCat output
12-18 22:01:53.210: E/AndroidRuntime(6313): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.Results}: java.lang.NullPointerException
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.app.ActivityThread.access$600(ActivityThread.java:130)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.os.Handler.dispatchMessage(Handler.java:99)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.os.Looper.loop(Looper.java:137)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.app.ActivityThread.main(ActivityThread.java:4745)
12-18 22:01:53.210: E/AndroidRuntime(6313): at java.lang.reflect.Method.invokeNative(Native Method)
12-18 22:01:53.210: E/AndroidRuntime(6313): at java.lang.reflect.Method.invoke(Method.java:511)
12-18 22:01:53.210: E/AndroidRuntime(6313): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
12-18 22:01:53.210: E/AndroidRuntime(6313): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-18 22:01:53.210: E/AndroidRuntime(6313): at dalvik.system.NativeStart.main(Native Method)
12-18 22:01:53.210: E/AndroidRuntime(6313): Caused by: java.lang.NullPointerException
12-18 22:01:53.210: E/AndroidRuntime(6313): at com.example.test.DatabaseHelper.onCreate(DatabaseHelper.java:62)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
12-18 22:01:53.210: E/AndroidRuntime(6313): at com.example.test.DatabaseHelper.<init>(DatabaseHelper.java:25)
12-18 22:01:53.210: E/AndroidRuntime(6313): at com.example.test.Results.onCreate(Results.java:33)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.app.Activity.performCreate(Activity.java:5008)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
12-18 22:01:53.210: E/AndroidRuntime(6313): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
12-18 22:01:53.210: E/AndroidRuntime(6313): ... 11 more
What is causing the NPE?
Also, any help on code structure for this SQLite highscores I am trying to implement would be helpful as well.

Categories