Android database SQLite date may not be null - java

I am attempting to update my SQLite database with a date field, using a DatePicker. for simplicties sake (on my part) I decided to just take the date and pass it to a String to update the database using just Strings (I have no desire to perform any DATETIME functions in this instance.
The datbase works (at least, via a dialog I set up) however when the data is cast to a TextView nothing appears, also eclipse stacktrace reports the following:
05-09 22:47:30.164: E/SQLiteDatabase(3112): Error inserting chest=100 arms=android.widget.TextView#4125c110 legs=100 waist=100 weight=100
05-09 22:47:30.164: E/SQLiteDatabase(3112): android.database.sqlite.SQLiteConstraintException: personalStats.date may not be NULL (code 19)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:775)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at com.uhi.fatfighter.Stats.createEntry(Stats.java:86)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at com.uhi.fatfighter.MainActivity.onClick(MainActivity.java:250)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.view.View.performClick(View.java:4084)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.view.View$PerformClick.run(View.java:16966)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.os.Handler.handleCallback(Handler.java:615)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.os.Handler.dispatchMessage(Handler.java:92)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.os.Looper.loop(Looper.java:137)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at android.app.ActivityThread.main(ActivityThread.java:4928)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at java.lang.reflect.Method.invokeNative(Native Method)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at java.lang.reflect.Method.invoke(Method.java:511)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
05-09 22:47:30.164: E/SQLiteDatabase(3112): at dalvik.system.NativeStart.main(Native Method)
Below is the class where the SQL is handled:
public class Stats {
public static final String KEY_ROWID = "_id";
public static final String KEY_WEIGHT = "weight";
public static final String KEY_WAIST = "waist";
public static final String KEY_CHEST = "chest";
public static final String KEY_LEGS = "legs";
public static final String KEY_ARMS = "arms";
public static final String KEY_DATE = "date";
private static final String DATABASE_NAME = "statsDB";
private static final String DATABASE_TABLE = "personalStats";
private static final int DATABASE_VERSION = 4;
private DbHelper ffHelper;
private final Context ffContext;
private SQLiteDatabase ffDatabase;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_WEIGHT
+ " TEXT NOT NULL, " + KEY_WAIST + " TEXT NOT NULL, "
+ KEY_CHEST + " TEXT NOT NULL, " + KEY_LEGS
+ " TEXT NOT NULL, " + KEY_ARMS + " TEXT NOT NULL,"
+ KEY_DATE + " TEXT NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Stats(Context c) {
ffContext = c;
}
public Stats open() throws SQLException {
ffHelper = new DbHelper(ffContext);
ffDatabase = ffHelper.getWritableDatabase();
return this;
}
public void close() {
ffHelper.close();
}
public long createEntry(String weight, String waist, String chest, String legs, String arms, String date) {
ContentValues cv = new ContentValues();
cv.put(KEY_WEIGHT, weight);
cv.put(KEY_WAIST, waist);
cv.put(KEY_CHEST, chest);
cv.put(KEY_LEGS, legs);
cv.put(KEY_ARMS, arms);
cv.put(KEY_ARMS, date);
return ffDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
String[] columns = new String[] { KEY_ROWID, KEY_WEIGHT, KEY_WAIST, KEY_CHEST, KEY_LEGS, KEY_ARMS, KEY_DATE};
Cursor c = ffDatabase.query(DATABASE_TABLE, columns, null, null, null,
null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iWeight = c.getColumnIndex(KEY_WEIGHT);
int iWaist = c.getColumnIndex(KEY_WAIST);
int iChest = c.getColumnIndex(KEY_CHEST);
int iLegs = c.getColumnIndex(KEY_LEGS);
int iArms = c.getColumnIndex(KEY_ARMS);
int iDate = c.getColumnIndex(KEY_DATE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " " + c.getString(iWeight)
+ " " + c.getString(iWaist)
+ " " + c.getString(iChest)
+ " " + c.getString(iLegs)
+ " " + c.getString(iArms)
+ " " + c.getString(iDate)+ "\n";
}
return result;
}
}
The view class:
public class DBView extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.view_stats);
TextView tv = (TextView) findViewById(R.id.tvDBInfo);
Stats dbInfo = new Stats(this);
dbInfo.open();
String data = dbInfo.getData();
dbInfo.close();
tv.setText(data);
}
The EditTexts and DatePicker are in my main_activity, i can post if it would help?

You put two times the same key in your content values.
cv.put(KEY_ARMS, arms);
cv.put(KEY_ARMS, date);
Change it with :
cv.put(KEY_ARMS, arms);
cv.put(KEY_DATE, date);

You didn't insert nothing in KEY_DATE, but KEY_DATE is not null.
Yu must put cv.put(KEY_DATE, date); before insert

Instead of having your KEY_DATE column set to "TEXT NOT NULL", Just set it to plain "TEXT". You can also do that with any other columns where you may be inserting a null or empty value.

Related

android view inflate exception error and java null pointer exception

I am creating a landscape layout using fragment class. But now my code is showing error in my listMovieActivity file. I tried following some answers from stackoverflow but that didnt help me on it.
This is my listMovieActivity code:
package com.example.moviemanager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
public class listMovieActivity extends FragmentActivity {
private MovieDetailFragment detailFragment = null;
private MovieListFragment listFragment = null;
private FragmentManager manager;
private int selectedItemIndex = -1;
private String title=null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listmovie);
manager = getSupportFragmentManager();
detailFragment = (MovieDetailFragment) manager.findFragmentById(R.id.detailmovie_fragment);
listFragment = (MovieListFragment) manager.findFragmentById(R.id.listmovie_fragment);
}
public boolean onCreateOptionsMenu(android.view.Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
protected void onResume() {
super.onResume();
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE)
showDetails(selectedItemIndex,title);
}
public void showDetails(int selectedItem, String ttl) {
//Log.d("FRAGMENT", "Selected item " + selectedItem);
selectedItemIndex = selectedItem;
title = ttl;
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (detailFragment != null) {
// update entry
detailFragment.updateDetails(selectedItem,ttl);
}
} else {
// show DetailsActivity
Intent intent = new Intent(this, DetailMovie.class);
intent.putExtra("POSITION", selectedItem);
intent.putExtra("TITLE", ttl);
startActivity(intent);
}
}
}
This is my DatabaseHandler code:
public class DatabaseHandler {
String cmd;
private static final String DBTAG = "DatabaseHandler";
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_KEY = "key";
public static final String KEY_TITLE = "title";
public static final String KEY_TYPE = "type";
public static final String KEY_STORY = "story";
public static final String KEY_RATING = "rating";
public static final String KEY_LANGUAGE = "language";
public static final String KEY_RUNTIME = "runtime";
public static final int COL_KEY = 1;
public static final int COL_TITLE = 2;
public static final int COL_TYPE = 3;
public static final int COL_STORY = 4;
public static final int COL_RATING = 5;
public static final int COL_LANGUAGE = 6;
public static final int COL_RUNTIME = 7;
public static final String[] ALL_KEYS = new String[] {
KEY_ROWID, KEY_KEY, KEY_TITLE, KEY_TYPE, KEY_STORY,
KEY_RATING, KEY_LANGUAGE, KEY_RUNTIME};
public static final String DATABASE_NAME = "movieDb";
public static final String DATABASE_TABLE = "movieTable";
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement,"
+ KEY_KEY + " text not null,"
+ KEY_TITLE + " text not null,"
+ KEY_TYPE + " text not null,"
+ KEY_STORY + " text not null,"
+ KEY_RATING + " text not null,"
+ KEY_LANGUAGE + " text not null,"
+ KEY_RUNTIME + " integer not null"
+ ");";
private final Context context;
private DatabaseHelper dbHelper;
private SQLiteDatabase db;
public DatabaseHandler(Context ctx){
this.context = ctx;
dbHelper = new DatabaseHelper(context);
}
public DatabaseHandler open(){
db = dbHelper.getWritableDatabase();
return this;
}
public void close(){
dbHelper.close();
}
public void insertRow(String mvkey, String mvtitle, String mvtype,
String mvstory, String mvrating, String mvlanguage, int mvruntime){
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_KEY, mvkey);
initialValues.put(KEY_TITLE, mvtitle);
initialValues.put(KEY_TYPE, mvtype);
initialValues.put(KEY_STORY, mvstory);
initialValues.put(KEY_RATING, mvrating);
initialValues.put(KEY_LANGUAGE, mvlanguage);
initialValues.put(KEY_RUNTIME, mvruntime);
open();
db.insert(DATABASE_TABLE, null, initialValues);
close();
}
public void deleteRow(long rowId){
open();
cmd = new String ("DELETE FROM " + DATABASE_TABLE + " WHERE ( "+KEY_ROWID+" =" + rowId + " );");
db.execSQL(cmd);
close();
// String where = KEY_ROWID + "=" + rowId;
// return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll(){
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if(c.moveToFirst()){
do{
deleteRow(c.getLong((int)rowId));
}while(c.moveToNext());
}
c.close();
}
public Cursor getAllRows(){
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
if(c!= null){
c.moveToFirst();
}
return c;
}
public Cursor getRow(long rowId){
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
if(c!= null){
c.moveToFirst();
}
return c;
}
public boolean updateRow(long rowId, String mvkey, String mvtitle,
String mvtype, String mvstory, String mvrating,
String mvlanguage, int mvruntime){
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_KEY, mvkey);
newValues.put(KEY_TITLE, mvtitle);
newValues.put(KEY_TYPE, mvtype);
newValues.put(KEY_STORY, mvstory);
newValues.put(KEY_RATING, mvrating);
newValues.put(KEY_LANGUAGE, mvlanguage);
newValues.put(KEY_RUNTIME, mvruntime);
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
public Cursor listMovieTitle(){
return db.rawQuery("SELECT "+ KEY_TITLE + " FROM " + DATABASE_TABLE,null);
}
public Cursor get_id(String ttl){
return db.rawQuery("SELECT "+ KEY_ROWID + " FROM " + DATABASE_TABLE + " WHERE (" + KEY_TITLE + " = " + ttl + " );",null);
}
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_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(DBTAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
This is the error stack trace i am receiving each time i click on my display button:
04-04 01:00:15.314 811-811/com.example.moviemanager E/Trace﹕ error opening trace file: No such file or directory (2)
04-04 01:01:15.098 859-859/com.example.moviemanager E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.moviemanager/com.example.moviemanager.listMovieActivity}: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:270)
at android.app.Activity.setContentView(Activity.java:1881)
at com.example.moviemanager.listMovieActivity.onCreate(listMovieActivity.java:20)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5041)
            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:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.example.moviemanager.DatabaseHandler.open(DatabaseHandler.java:65)
at com.example.moviemanager.MovieListFragment.onCreateView(MovieListFragment.java:29)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1478)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:900)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1082)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1184)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:285)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:676)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:270)
            at android.app.Activity.setContentView(Activity.java:1881)
            at com.example.moviemanager.listMovieActivity.onCreate(listMovieActivity.java:20)
            at android.app.Activity.performCreate(Activity.java:5104)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5041)
            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:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)
04-04 01:01:19.447 879-879/com.example.moviemanager E/Trace﹕ error opening trace file: No such file or directory (2)
Previously, I had the same problem error inflating class fragment, but then I solved it by changing my android listview id to android custome list id. But now the problem is appearing again but this time its worst my databasehandler also is showing error it seems. Can any help me on this.
In DatabaseHandler:
private final Context context;
This makes no sense, the final field cannot be assigned.And how can you make it pass the check?
Put up MovieListFragment code, please.

SQLite Database crashes on open

I need to use a SQLite Database on my android app but when I try and open it, it crashes and I cannot figure out why. I have had a look online for the past hour and a bit but cannot find any help.
Here is the code:
public class PrivDB {
public static final String KEY_ROWID = "_id";
public static final String KEY_LEVEL = "level";
public static final String KEY_LOCKED = "locked";
public static final String KEY_SEQUENCE = "sequence";
public static final String KEY_TRIES = "tries";
private static final String DATABASE_NAME = "patdb";
private static final String DATABASE_TABLE = "tablename";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
arg0.execSQL("CREATE TABLE " + DATABASE_TABLE + " ("+
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
KEY_LEVEL + " STRING NOT NULL, " +
KEY_LOCKED + " INTEGER NOT NULL, " +
KEY_SEQUENCE + " INTEGER NOT NULL, "+
KEY_TRIES + " INTEGER NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
arg0.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(arg0);
}
}
public PrivDB (Context c) {
ourContext = c;
}
public PrivDB open() throws SQLException {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry (String level, int locked, int sequence, int tries){
ContentValues cv = new ContentValues();
cv.put(KEY_LEVEL, level);
cv.put(KEY_LOCKED, locked);
cv.put(KEY_SEQUENCE, sequence);
cv.put(KEY_TRIES, tries);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
String[] columns = new String[]{KEY_ROWID, KEY_LEVEL, KEY_LOCKED, KEY_SEQUENCE, KEY_TRIES};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iLevel = c.getColumnIndex(KEY_LEVEL);
int iLocked = c.getColumnIndex(KEY_LOCKED);
int iSequence = c.getColumnIndex(KEY_SEQUENCE);
int iTries = c.getColumnIndex(KEY_TRIES);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iLevel) + " " + c.getString(iLocked) + " "
+ c.getString(iSequence) + c.getString(iTries) + "\n";
}
return result;
}
public int getLocked(String s) throws SQLException {
String[] columns = new String[]{KEY_ROWID, KEY_LEVEL, KEY_LOCKED, KEY_SEQUENCE, KEY_TRIES};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_LEVEL + "=" + s, null, null, null, null);
if(c != null){
c.moveToFirst();
int locked = c.getInt(2);
return locked;
}
return (Integer) null;
}
public void updateEntry(String s, int locked, int tries) throws SQLException {
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_LOCKED, locked);
cvUpdate.put(KEY_TRIES, tries);
ourDatabase.update(DATABASE_TABLE, cvUpdate, KEY_LEVEL + "=" + s, null);
}
}
and how I am calling the database:
public class Stats extends Activity {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
tv = (TextView) findViewById(R.id.tvStats);
PrivDB info = new PrivDB(this);
info.open();
String data = info.getData();
info.close();
tv.setText(data);
}
}
When I open the Stats class, the app crashes, but if I comment out the info.open() until the info.close() then it works fine (but obviously nothing happens).
UPDATE
here is the log cat output:
01-09 13:16:32.786: E/AndroidRuntime(517): FATAL EXCEPTION: main
01-09 13:16:32.786: E/AndroidRuntime(517): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.docime.vamoose.patternz/com.docime.vamoose.patternz.Stats}: java.lang.StringIndexOutOfBoundsException
01-09 13:16:32.786: E/AndroidRuntime(517): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.os.Handler.dispatchMessage(Handler.java:99)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.os.Looper.loop(Looper.java:123)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-09 13:16:32.786: E/AndroidRuntime(517): at java.lang.reflect.Method.invokeNative(Native Method)
01-09 13:16:32.786: E/AndroidRuntime(517): at java.lang.reflect.Method.invoke(Method.java:521)
01-09 13:16:32.786: E/AndroidRuntime(517): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-09 13:16:32.786: E/AndroidRuntime(517): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-09 13:16:32.786: E/AndroidRuntime(517): at dalvik.system.NativeStart.main(Native Method)
01-09 13:16:32.786: E/AndroidRuntime(517): Caused by: java.lang.StringIndexOutOfBoundsException
01-09 13:16:32.786: E/AndroidRuntime(517): at android.app.ContextImpl.validateFilePath(ContextImpl.java:1579)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:539)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:203)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:98)
01-09 13:16:32.786: E/AndroidRuntime(517): at com.docime.vamoose.patternz.PrivDB.open(PrivDB.java:60)
01-09 13:16:32.786: E/AndroidRuntime(517): at com.docime.vamoose.patternz.Stats.onCreate(Stats.java:18)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-09 13:16:32.786: E/AndroidRuntime(517): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-09 13:16:32.786: E/AndroidRuntime(517): ... 11 more
You never pass DATABASE_TABLE name or assign it in you code. that's why it's crashing.
private static final String DATABASE_TABLE = "TABLE_NAME";
Update: do update your onCreate(). SQLite suport TEXT instedOf String
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
arg0.execSQL("CREATE TABLE " + DATABASE_TABLE + " ( "+
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
KEY_LEVEL + " TEXT NOT NULL, " +
KEY_LOCKED + " INTEGER NOT NULL, " +
KEY_SEQUENCE + " INTEGER NOT NULL, "+
KEY_TRIES + " INTEGER NOT NULL);");
}
Another important things you are passing the context but not saving it using static variable.
You should use like following
private static Context ourContext;
public PrivDB (Context c) {
this.ourContext = c;
}
But above all, as you are facing the error/ exception
Caused by: java.lang.StringIndexOutOfBoundsException ,
This Thrown when the a string is indexed with a value less than zero, or greater than or equal to the size of the array
I would request you to check the following so- java.lang.StringIndexOutOfBoundsException: index=0 length=0 in get sqlite database
change STRING to TEXT in below
arg0.execSQL("CREATE TABLE " + DATABASE_TABLE + " ("+
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
KEY_LEVEL + " STRING NOT NULL, " +
KEY_LOCKED + " INTEGER NOT NULL, " +
KEY_SEQUENCE + " INTEGER NOT NULL, "+
KEY_TRIES + " INTEGER NOT NULL);");
NOTE :After change please add one to your database version
I think your info is pointing to null
Try this code :
if (null != info)
{
info.open();
String data = info.getData();
info.close();
}else
Log.d("App Name", "Info is null");
One more thing for getData() function you are reading the database
so u should open the database in read mode.
ourDatabase = ourHelper.getWritableDatabase(); To
ourDatabase = ourHelper.getReadableDatabase();
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
arg0.execSQL("CREATE TABLE " + DATABASE_TABLE + " ("+
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
KEY_LEVEL + " STRING NOT NULL, " +
KEY_LOCKED + " INTEGER NOT NULL, " +
KEY_SEQUENCE + " INTEGER NOT NULL, "+
KEY_TRIES + " INTEGER NOT NULL);");
}
This line KEY_TRIES + " INTEGER NOT NULL);"); has two ;.Does your table get created/populated?

No column named in sqlite java

I have seen many times that I can't find the solution of no column named. Can anyone please help me?
Thank you very much in advance :)
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LUGGAGE_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" +
KEY_NAME + " TEXT NOT NULL," +
KEY_CODE + " TEXT NOT NULL," +
KEY_NUMBER + " TEXT NOT NULL," +")";
db.execSQL(CREATE_LUGGAGE_TABLE);
}
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "LuggageDataCenter";
// Contacts table name
private static final String TABLE_CONTACTS = "luggage";
// Contacts Table Columns names
private static final String KEY_NAME = "name";
private static final String KEY_CODE = "code";
private static final String KEY_NUMBER = "number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LUGGAGE_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_NAME + " TEXT NOT NULL," + KEY_CODE + " TEXT NOT NULL," + KEY_NUMBER + " TEXT NOT NULL );";
db.execSQL(CREATE_LUGGAGE_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Luggage luggage) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, luggage.getName()); // Contact Name
values.put(KEY_CODE, luggage.getCode()); // Contact Phone
// values.put(KEY_NUMBER, luggage.getNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting All Contacts
public List<Luggage> getAllContacts() {
List<Luggage> contactList = new ArrayList<Luggage>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Luggage luggage = new Luggage();
luggage.setName(cursor.getString(0));
// luggage.setCode(cursor.getString(1));
// luggage.setNumber(cursor.getString(2));
// Adding contact to list
contactList.add(luggage);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
}
Stacktrace
01-07 18:45:43.070: I/Adreno200-EGL(16078): Reconstruct Branch: NOTHING
01-07 18:45:51.950: W/IInputConnectionWrapper(16078): showStatusIcon on inactive InputConnection
01-07 18:45:53.600: E/SQLiteDatabase(16078): Error inserting code=100000HKG name=Lee Chung Ming
01-07 18:45:53.600: E/SQLiteDatabase(16078): android.database.sqlite.SQLiteConstraintException: luggage.number may not be NULL (code 19)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:787)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at com.airportapplication.app.DatabaseHandler.addContact(DatabaseHandler.java:64)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at com.airportapplication.app.LuggageVer.onActivityResult(LuggageVer.java:87)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at android.app.Activity.dispatchActivityResult(Activity.java:5197)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at android.app.ActivityThread.deliverResults(ActivityThread.java:3160)
01-07 18:45:53.600: E/SQLiteDatabase(16078): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3207)
I have already reinstalled the app, but still not work.
you added extra , & + at the end so please format it properly like below:
String CREATE_LUGGAGE_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_NAME + " TEXT NOT NULL," + KEY_CODE + " TEXT NOT NULL," + KEY_NUMBER + " TEXT NOT NULL);";

Couldn't read row 0, col 9 from CursorWindow

I'm getting the error Couldn't read row 0, col 9 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it. Two other people are able to run the code without error but on my machine it throws it. I'm very confused. Here is the code that deals with the SQLite:
Thanks in advance, sorry there's a lot of code
import java.util.ArrayList;
import java.util.List;
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 FeedSQLiteHelper extends SQLiteOpenHelper {
//Table Name
public static final String TABLE_POSTS = "comments";
//Table Column names
public static final String COLUMN_ID = "_id";
public static final String COLUMN_CAPTION = "caption";
public static final String COLUMN_NAME= "name";
public static final String COLUMN_LIKE="like";
public static final String COLUMN_DISLIKE="dislike";
public static final String COLUMN_COMMENTS = "columns";
public static final String COLUMN_ALL_COMMENTS = "allComments";
public static final String COLUMN_PHOTO = "photo";
public static final String COLUMN_CELEB = "celeb";
public static final String COLUMN_FID = "facebook_id";
public static final String COLUMN_TIME = "timestamp";
private static final String DATABASE_NAME = "commments.db";
private static final int DATABASE_VERSION = 6;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_POSTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_CAPTION
+ " text not null, " + COLUMN_NAME + " text not null, "
+ COLUMN_LIKE + " integer not null, " + COLUMN_DISLIKE + " integer not null, "
+ COLUMN_COMMENTS + " integer not null, " + COLUMN_ALL_COMMENTS + " text, "
+ COLUMN_PHOTO + " text, " + COLUMN_FID + " text, " + COLUMN_TIME + " long);";
public FeedSQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(FeedSQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
if(oldVersion <6) {
final String ALTER_TBL = "ALTER TABLE " + TABLE_POSTS + " ADD COLUMN " + COLUMN_TIME + " long;";
db.execSQL(ALTER_TBL);
}
}
//Adding new contact
public void addContact(FeedsModel contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, contact.getName());
values.put(COLUMN_CAPTION, contact.getDesc());
values.put(COLUMN_LIKE, contact.getUps());
values.put(COLUMN_DISLIKE, contact.getDowns());
values.put(COLUMN_COMMENTS, contact.getComments());
values.put(COLUMN_ALL_COMMENTS, contact.getAllComments());
values.put(COLUMN_PHOTO, contact.getImageId());
values.put(COLUMN_FID, contact.getFID());
values.put(COLUMN_TIME, contact.getTimestamp());
// Inserting Row
db.insert(TABLE_POSTS, null, values);
db.close(); // Closing database connection
}
//Getting single contact
public FeedsModel getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_POSTS, new String[] { COLUMN_ID,
COLUMN_CAPTION, COLUMN_NAME, COLUMN_LIKE, COLUMN_DISLIKE, COLUMN_COMMENTS, COLUMN_ALL_COMMENTS, COLUMN_PHOTO, COLUMN_FID, COLUMN_TIME }, COLUMN_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
FeedsModel contact = new FeedsModel(
Integer.parseInt(cursor.getString(0)),
cursor.getString(1),
cursor.getString(2),
Integer.parseInt(cursor.getString(3)),
Integer.parseInt(cursor.getString(4)),
Integer.parseInt(cursor.getString(5)),
cursor.getString(6),
cursor.getString(7),
cursor.getString(8),
Long.parseLong(cursor.getString(9)));
// return contact
return contact;
}
//filters the news feed for the 'Me' option
public List<FeedsModel> getMe(String me)
{
List<FeedsModel> contactList = new ArrayList<FeedsModel>();
String selectQuery = "SELECT * FROM " + TABLE_POSTS + " WHERE " + COLUMN_FID + "= "+ me;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
FeedsModel contact = new FeedsModel();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setDesc(cursor.getString(1));
contact.setName(cursor.getString(2));
contact.setUps(Integer.parseInt(cursor.getString(3)));
contact.setDowns(Integer.parseInt(cursor.getString(4)));
contact.setComments(Integer.parseInt(cursor.getString(5)));
contact.setAllComments(cursor.getString(6));
contact.setImageId(cursor.getString(7));
contact.setFID(cursor.getString(8));
contact.setTimestamp(Long.parseLong(cursor.getString(9)));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
//filters the news feed for the 'Me' option
public List<FeedsModel> getMostRecent()
{
List<FeedsModel> contactList = new ArrayList<FeedsModel>();
String selectQuery = "SELECT * FROM " + TABLE_POSTS + " ORDER BY " + COLUMN_TIME + " DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
FeedsModel contact = new FeedsModel();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setDesc(cursor.getString(1));
contact.setName(cursor.getString(2));
contact.setUps(Integer.parseInt(cursor.getString(3)));
contact.setDowns(Integer.parseInt(cursor.getString(4)));
contact.setComments(Integer.parseInt(cursor.getString(5)));
contact.setAllComments(cursor.getString(6));
contact.setImageId(cursor.getString(7));
contact.setFID(cursor.getString(8));
contact.setTimestamp(Long.parseLong(cursor.getString(9)));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
//Getting All Contacts
public List<FeedsModel> getAllContacts() {
List<FeedsModel> contactList = new ArrayList<FeedsModel>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_POSTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
FeedsModel contact = new FeedsModel();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setDesc(cursor.getString(1));
contact.setName(cursor.getString(2));
contact.setUps(Integer.parseInt(cursor.getString(3)));
contact.setDowns(Integer.parseInt(cursor.getString(4)));
contact.setComments(Integer.parseInt(cursor.getString(5)));
contact.setAllComments(cursor.getString(6));
contact.setImageId(cursor.getString(7));
contact.setFID(cursor.getString(8));
contact.setTimestamp(Long.parseLong(cursor.getString(9)));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
//Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_POSTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
//Updating single contact
public int updateContact(FeedsModel contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, contact.getName());
values.put(COLUMN_CAPTION, contact.getDesc());
values.put(COLUMN_LIKE, contact.getUps());
values.put(COLUMN_DISLIKE, contact.getDowns());
values.put(COLUMN_COMMENTS, contact.getComments());
values.put(COLUMN_ALL_COMMENTS, contact.getAllComments());
values.put(COLUMN_PHOTO, contact.getImageId());
values.put(COLUMN_FID, contact.getFID());
values.put(COLUMN_TIME, contact.getTimestamp());
// updating row
return db.update(TABLE_POSTS, values, COLUMN_ID + " = ?",
new String[] { String.valueOf(contact.getId()) });
}
//Deleting single contact
public void deleteContact(FeedsModel contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_POSTS, COLUMN_ID + " = ?",
new String[] { String.valueOf(contact.getId()) });
db.close();
}
}
Logcat:
E/CursorWindow(841): Failed to read row 0, column 9 from a CursorWindow which has 3 rows, 9 columns.
D/AndroidRuntime(841): Shutting down VM
W/dalvikvm(841): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
E/AndroidRuntime(841): FATAL EXCEPTION: main
E/AndroidRuntime(841): java.lang.RuntimeException: Unable to start activity ComponentInfo{edu.Drake.doppelganger/edu.Drake.doppelganger.MainActivity}: java.lang.IllegalStateException: Couldn't read row 0, col 9 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
E/AndroidRuntime(841): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
E/AndroidRuntime(841): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
E/AndroidRuntime(841): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime(841): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
E/AndroidRuntime(841): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(841): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(841): at android.app.ActivityThread.main(ActivityThread.java:5041)
E/AndroidRuntime(841): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(841): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(841): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(841): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(841): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(841): Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 9 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
E/AndroidRuntime(841): at android.database.CursorWindow.nativeGetString(Native Method)
E/AndroidRuntime(841): at android.database.CursorWindow.getString(CursorWindow.java:434)
E/AndroidRuntime(841): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
E/AndroidRuntime(841): at edu.Drake.doppelganger.FeedSQLiteHelper.getAllContacts(FeedSQLiteHelper.java:198)
E/AndroidRuntime(841): at edu.Drake.doppelganger.FeedFragment.onActivityCreated(FeedFragment.java:65)
E/AndroidRuntime(841): at android.app.Fragment.performActivityCreated(Fragment.java:1703)
E/AndroidRuntime(841): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:903)
E/AndroidRuntime(841): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
E/AndroidRuntime(841): at android.app.BackStackRecord.run(BackStackRecord.java:682)
E/AndroidRuntime(841): at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
E/AndroidRuntime(841): at android.app.Activity.performStart(Activity.java:5113)
E/AndroidRuntime(841): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2153)
E/AndroidRuntime(841): ... 11 more
it is because you try to get the data before checking their is data available or not.
if (cursor.moveToFirst()) {
do {
// your content
} while (cursor.moveToNext());
}
Change this block to
while (cursor.moveToNext()) {
// your content
}
Like this.
Surely this will help you.

Android : Table has no column named "variable name" MySql Database error

I'm getting and error like the one showed belowe when I try to put a new entry in my database. I search trough it for hours now, but I'm not able to detect whats wrong. Any input would be superb!
Here is the error from LogCat.
02-27 23:02:51.451: E/SQLiteLog(6777): (1) table dager has no column named brutto
02-27 23:02:51.451: E/SQLiteDatabase(6777): Error inserting brutto=0 date=21.03.2013
hours=4
02-27 23:02:51.451: E/SQLiteDatabase(6777): android.database.sqlite.SQLiteException:
table dager has no column named brutto (code 1): , while compiling: INSERT INTO
dager(brutto,date,hours) VALUES (?,?,?)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at
android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at com.adev.timelonn.DatabaseHandler.addDay(DatabaseHandler.java:79)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at com.adev.timelonn.AddHours.onClick(AddHours.java:99)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.view.View.performClick(View.java:4084)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.view.View$PerformClick.run(View.java:16966)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.os.Handler.handleCallback(Handler.java:615)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.os.Handler.dispatchMessage(Handler.java:92)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.os.Looper.loop(Looper.java:137)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at android.app.ActivityThread.main(ActivityThread.java:4931)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at java.lang.reflect.Method.invokeNative(Native Method)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at java.lang.reflect.Method.invoke(Method.java:511)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
02-27 23:02:51.451: E/SQLiteDatabase(6777): at dalvik.system.NativeStart.main(Native
Method)
My database file.
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "timeliste";
// Contacts table name
private static final String TABLE_DAYS = "dager";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_DATE = "date";
private static final String KEY_HOURS = "hours";
private static final String KEY_UB = "ub";
private static final String KEY_BRUTTO = "brutto";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db)
String CREATE_DAY_TABLE = "CREATE TABLE " + TABLE_DAYS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_DATE + " TEXT," + KEY_HOURS + " INTEGER,
"
+ KEY_UB + " INTEGER," + KEY_BRUTTO + "INTEGER," + ")";
db.execSQL(CREATE_DAY_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DAYS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addDay(AddNewDay newday) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_DATE, newday.getDate()); // GetDate
values.put(KEY_BRUTTO, newday.getBrutto()); // GetBruttoLønn
values.put(KEY_HOURS, newday.getHours()); // GetHours
values.put(KEY_UB, newday.getUb()); // GetUBTillegg
// Inserting Row
db.insert(TABLE_DAYS, null, values);
db.close(); // Closing database connection
}
// Get single day
AddNewDay getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_DAYS, new String[] { KEY_ID,
KEY_DATE, KEY_HOURS, KEY_BRUTTO, KEY_UB }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
AddNewDay newday = new AddNewDay(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), Integer.parseInt(cursor.getString(2)),
Integer.parseInt(cursor.getString(3)),Integer.parseInt(cursor.getString(4)));
// return contact
return newday;
}
// Getting All Contacts
public List<AddNewDay> getAllContacts() {
List<AddNewDay> contactList = new ArrayList<AddNewDay>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_DAYS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
AddNewDay days = new AddNewDay();
days.setID(Integer.parseInt(cursor.getString(0)));
days.setDate(cursor.getString(1));
days.setHours(Integer.parseInt(cursor.getString(2)));
days.setUb(Integer.parseInt(cursor.getString(3)));
days.setBrutto(Integer.parseInt(cursor.getString(4)));
// Adding contact to list
contactList.add(days);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateDay(AddNewDay newday) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, newday.getID());
values.put(KEY_DATE, newday.getDate());
values.put(KEY_HOURS, newday.getHours());
values.put(KEY_UB, newday.getUb());
values.put(KEY_BRUTTO, newday.getUb());
// updating row
return db.update(TABLE_DAYS, values, KEY_ID + " = ?",
new String[] { String.valueOf(newday.getID()) });
}
// Deleting single contact
public void deleteDay(AddNewDay newday) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_DAYS, KEY_ID + " = ?",
new String[] { String.valueOf(newday.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_DAYS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
And then my AddNewDay file.
public class AddNewDay {
//private variables
int _id;
String _date;
int _hours;
int _ubtillegg;
int _brutto;
// Empty constructor
public AddNewDay(){
}
// constructor
public AddNewDay(int id, String date, int hours, int ubtillegg, int brutto){
this._id = id;
this._date = date;
this._hours = hours;
this._ubtillegg = ubtillegg;
this._brutto = brutto;
}
// constructor
public AddNewDay(String date, int hours, int brutto){
this._date = date;
this._hours = hours;
this._brutto = brutto;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting date
public String getDate(){
return this._date;
}
// setting date
public void setDate(String date){
this._date = date;
}
// getting hours
public int getHours(){
return this._hours;
}
// setting hours
public void setHours(int hours){
this._hours = hours;
}
// getting ubtillegg
public int getUb(){
return this._ubtillegg;
}
// setting ubtillegg
public void setUb(int ub){
this._ubtillegg = ub;
}
// getting brutto
public int getBrutto(){
return this._brutto;
}
// setting brutto
public void setBrutto(int brutto){
this._brutto = brutto;
}
public String toString() {
return _date + " jobbet du " + _hours + " timer.";
}
}
And this is how I add a new entry in the database.
// # Makes a new object of newday.
AddNewDay newday = new AddNewDay ();
newday._date = "21.03.2013";
newday._id = 1;
newday._hours = 4;
newday._ubtillegg = 1500;
// # Open databse connection and writes new day.
DatabaseHandler connect = new DatabaseHandler (this);
connect.addDay(newday);
// # Updates the dblist with entries.
GlobalVariables.dblist = connect.getAllContacts();
So basicly I found the solution. I'm still confused about how stupid it was. And clearly database work i super-sensitive material! My problem was I forgot a white-space in the last "INTEGER" value. So instead of " INTEGER" i wrote "INTEGER", and that gave me a row called "bruttoINTEGER" instead of "brutto". So a white-space was the error. I rewrote the createTable function to this :
public void onCreate(SQLiteDatabase db) {
String CREATE_DAY_TABLE = "CREATE TABLE " + TABLE_DAYS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_DATE + " TEXT," + KEY_HOURS + " INTEGER, "
+ KEY_UB + " INTEGER," + KEY_BRUTTO + " INTEGER" + ");";
db.execSQL(CREATE_DAY_TABLE);
}
private static final int VERSION = 4;
Change the version it worked fine for me
i agree with iNzzane above. this problem is mainly caused by syntax. for example, previously my code was correct. here it is:
String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_PRODUCTS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_MESSAGEADDRESS
+ " TEXT," + COLUMN_MESSAGEBODY + " TEXT " + ")";
the above code was running correct but i added another column and it started causing the mentioned error. below is the erroneous code:
String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_PRODUCTS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_MESSAGEADDRESS
+ " TEXT," + COLUMN_MESSAGEBODY + " TEXT" + COLUMN_MESSAGETIME + " LONG" + ")";
as you can see, when i added the new column i forgot to include a comma after type TEXT. this means that when this code is executed, there will be syntax error as the compiler will read the last part as:
COLUMN_MESSAGEBODY TEXTCOLUMN_MESSAGETIME LONG
as opposed to:
COLUMN_MESSAGEBODY TEXT, COLUMN_MESSAGETIME LONG
solution: ensure that your syntax is correct and you heed to spaces and commas.
I´m not sure but maybe you forgot the " , " in the query before "ub" and "brutto" fields
String CREATE_DAY_TABLE = "CREATE TABLE " + TABLE_DAYS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_DATE + " TEXT,"
+ KEY_HOURS + " INTEGER PRIMARY KEY, " + KEY_UB + " INTEGER PRIMARY KEY, " + KEY_BRUTTO + "INTEGER PRIMARY KEY" + ")";
db.execSQL(CREATE_DAY_TABLE);

Categories