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?
Related
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.
Android app crashes when saving data to database
This is the class where I am capturing data from the user. The first button is working as expected but the second causes crash.
public class ActualSalesTracker extends Activity implements OnClickListener {
DbAdapter db = new DbAdapter(this);
Button BtnSalesCal, BtnAddRecordDB, BtnViewRecordsDB;
EditText item_name, item_cost, item_price_value, item_postage, actual_pl;
SalesProfitLossCal actSalesCal = new SalesProfitLossCal();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actual_sales_tracker);
Button salesCalBtn = (Button) findViewById(R.id.BtnSalesCal);
// register the click event with the sales calculating profit/loss button
salesCalBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// get EditText by id to represent the value of the item stock
// cost and store it as a double
EditText itemCostString = (EditText) findViewById(R.id.item_cost);
String ic = itemCostString.getText().toString();
double itemCost = Double.valueOf(ic).doubleValue();
// get EditText by id to represent the value of the post and
// packaging cost and store it as a double
EditText itemPostageString = (EditText) findViewById(R.id.item_postage);
String ipapc = itemPostageString.getText().toString();
double itemPostage = Double.valueOf(ipapc).doubleValue();
// get EditText by id to represent the value of the selling
// price and store it as a double
EditText itemPriceValueString = (EditText) findViewById(R.id.item_price_value);
String sp = itemPriceValueString.getText().toString();
double itemPriceValue = Double.valueOf(sp).doubleValue();
double actTotalCost = actSalesCal.ActTotalCostCal(itemCost,
itemPostage, itemPriceValue);
double actualProfitLoss = actSalesCal
.calculateProfitLossGenerated(itemPriceValue,
actTotalCost);
String ActualProfitLossString = String.format(
"You made £ %.2f", actualProfitLoss);
TextView ActualProfitLossView = (TextView) findViewById(R.id.yourActualPL);
ActualProfitLossView.setText(ActualProfitLossString);
}
});
//activate the add record button
Button addRecordDB = (Button) findViewById(R.id.BtnAddRecordDB);
// register the click event with the add record button
addRecordDB.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText nameText= (EditText)findViewById(R.id.item_name);
String name = nameText.getText().toString();
EditText costText=(EditText)findViewById(R.id.item_cost);
String cost=costText.getText().toString();
EditText priceText=(EditText)findViewById(R.id.item_price_value);
String price=priceText.getText().toString();
EditText postageText=(EditText)findViewById(R.id.item_postage);
String postage=postageText.getText().toString();
TextView profitlossText=(TextView)findViewById(R.id.actual_pl);
String profitloss=profitlossText.getText().toString();
db.open();
long id=db.insertRecord(name, cost, price, postage, profitloss);
db.close();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
This is my database adapter.
public class DbAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_ITEM_NAME = "name";
public static final String KEY_ITEM_COST = "cost";
public static final String KEY_ITEM_PRICE_VALUE = "price";
public static final String KEY_ITEM_POSTAGE = "postage";
public static final String KEY_ACTUAL_PL = "profitloss";
private static final String TAG = "DbAdapter";
private static final String DATABASE_NAME = "eBaySalesDB";
private static final String DATABASE_TABLE = "actualSales";
private static final int DATABASE_VERSION = 1;
private DatabaseHelper mDbHelper;
private SQLiteDatabase db;
private static final String DATABASE_CREATE = "create table if not exists"
+ DATABASE_TABLE + "(" + KEY_ROWID
+ "integer primary key autoincrement, " + KEY_ITEM_NAME
+ "text not null," + KEY_ITEM_COST + "text not null,"
+ KEY_ITEM_PRICE_VALUE + "text not null," + KEY_ITEM_POSTAGE
+ "text not null," + KEY_ACTUAL_PL + "text not null);";
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 " + DATABASE_TABLE);
onCreate(db);
}
}
/**
* constructor - takes the context to allow the database to be opened /
* created
*
* #param ctx
*/
public DbAdapter(Context ctx) {
this.mCtx = ctx;
}
/**
* open up the database. If it cannot be opened it will try to create a new
* instance of the database. if this can't be created it will throw an
* exception
*
* #return this (self reference)
* #throws SQLException
* (if the database can't be opened or closed.
*/
public DbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
db = mDbHelper.getWritableDatabase();
return this;
}
/**
* Method to close the code off to others
*/
public void close() {
mDbHelper.close();
}
/**
* method to insert a record into the database
*/
public long insertRecord(String name, String cost, String price,
String postage, String profitloss) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ITEM_NAME, name);
initialValues.put(KEY_ITEM_COST, cost);
initialValues.put(KEY_ITEM_PRICE_VALUE, price);
initialValues.put(KEY_ITEM_POSTAGE, postage);
initialValues.put(KEY_ACTUAL_PL, profitloss);
return db.insert(DATABASE_TABLE, null, initialValues);
}
/**
* method to delete a record from the database
*/
public boolean deleteRecord(long id) {
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + id, null) > 0;
}
/**
* method to retrieve all the records
*/
public Cursor getAllRecords() {
return db.query(DATABASE_TABLE, new String[] { KEY_ROWID,
KEY_ITEM_NAME, KEY_ITEM_COST, KEY_ITEM_PRICE_VALUE,
KEY_ITEM_POSTAGE, KEY_ACTUAL_PL }, null, null, null, null,
null, null);
}
/**
* method to retrieve a particular record
*/
public Cursor getRecord(long id) throws SQLException {
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID, KEY_ITEM_NAME, KEY_ITEM_COST, KEY_ITEM_PRICE_VALUE,
KEY_ITEM_POSTAGE, KEY_ACTUAL_PL }, KEY_ROWID + "=" + id, null,
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
/**
* method to update a record
*/
public boolean updateRecord(long id, String name, String cost,
String price, String postage, String profitloss) {
ContentValues args = new ContentValues();
args.put(KEY_ITEM_NAME, name);
args.put(KEY_ITEM_COST, cost);
args.put(KEY_ITEM_PRICE_VALUE, price);
args.put(KEY_ITEM_POSTAGE, postage);
args.put(KEY_ACTUAL_PL, profitloss);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + id, null) > 0;
}
}
Logcat error log:
05-06 03:55:58.690: E/AndroidRuntime(1251): FATAL EXCEPTION: main
05-06 03:55:58.690: E/AndroidRuntime(1251): Process: com.example.eventbuilder, PID: 1251
05-06 03:55:58.690: E/AndroidRuntime(1251): android.database.sqlite.SQLiteException: near "existsactualSales": syntax error (code 1): , while compiling: create table if not existsactualSales(idinteger primary key autoincrement, nametext not null,costtext not null,pricetext not null,postagetext not null,profitlosstext not null);
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1672)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1603)
05-06 03:55:58.690: E/AndroidRuntime(1251): at com.example.eventbuilder.DbAdapter$DatabaseHelper.onCreate(DbAdapter.java:51)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
05-06 03:55:58.690: E/AndroidRuntime(1251): at com.example.eventbuilder.DbAdapter.open(DbAdapter.java:85)
05-06 03:55:58.690: E/AndroidRuntime(1251): at com.example.eventbuilder.ActualSalesTracker$2.onClick(ActualSalesTracker.java:92)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.view.View.performClick(View.java:4438)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.view.View$PerformClick.run(View.java:18422)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.os.Handler.handleCallback(Handler.java:733)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.os.Handler.dispatchMessage(Handler.java:95)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.os.Looper.loop(Looper.java:136)
05-06 03:55:58.690: E/AndroidRuntime(1251): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-06 03:55:58.690: E/AndroidRuntime(1251): at java.lang.reflect.Method.invokeNative(Native Method)
05-06 03:55:58.690: E/AndroidRuntime(1251): at java.lang.reflect.Method.invoke(Method.java:515)
05-06 03:55:58.690: E/AndroidRuntime(1251): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-06 03:55:58.690: E/AndroidRuntime(1251): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-06 03:55:58.690: E/AndroidRuntime(1251): at dalvik.system.NativeStart.main(Native Method)
You need whitespace between identifiers and keywords here:
private static final String DATABASE_CREATE = "create table if not exists"
+ DATABASE_TABLE + "(" + KEY_ROWID
+ "integer primary key autoincrement, " + KEY_ITEM_NAME
+ "text not null," + KEY_ITEM_COST + "text not null,"
+ KEY_ITEM_PRICE_VALUE + "text not null," + KEY_ITEM_POSTAGE
+ "text not null," + KEY_ACTUAL_PL + "text not null);";
Change to
private static final String DATABASE_CREATE = "create table if not exists "
+ DATABASE_TABLE + "(" + KEY_ROWID
+ " integer primary key autoincrement, " + KEY_ITEM_NAME
+ " text not null," + KEY_ITEM_COST + " text not null,"
+ KEY_ITEM_PRICE_VALUE + " text not null," + KEY_ITEM_POSTAGE
+ " text not null," + KEY_ACTUAL_PL + " text not null);";
change this line from
private static final String DATABASE_CREATE = "create table if not exists"
+ DATABASE_TABLE + "(" + KEY_ROWID
+ "integer primary key autoincrement, " + KEY_ITEM_NAME
+ "text not null," + KEY_ITEM_COST + "text not null,"
+ KEY_ITEM_PRICE_VALUE + "text not null," + KEY_ITEM_POSTAGE
+ "text not null," + KEY_ACTUAL_PL + "text not null);";
to
private static final String DATABASE_CREATE = "create table if not exists "
+ DATABASE_TABLE + "(" + KEY_ROWID
+ "integer primary key autoincrement, " + KEY_ITEM_NAME
+ "text not null," + KEY_ITEM_COST + "text not null,"
+ KEY_ITEM_PRICE_VALUE + "text not null," + KEY_ITEM_POSTAGE
+ "text not null," + KEY_ACTUAL_PL + "text not null);";
you need space between your table name and Create table name syntax
You are missing spaces in between keywords and identifiers. It should be
private static final String DATABASE_CREATE = "create table if not exists "
+ DATABASE_TABLE + "(" + KEY_ROWID
+ " integer primary key autoincrement, " + KEY_ITEM_NAME
+ " text not null," + KEY_ITEM_COST + " text not null,"
+ KEY_ITEM_PRICE_VALUE + " text not null," + KEY_ITEM_POSTAGE
+ " text not null," + KEY_ACTUAL_PL + " text not null);";
Also in future, if you get any syntax errors in SQL commands try running them in SQLite. It will help you identify any errors in syntax.
Theres a simple Firefox addon for SQLite manager
I am making app to insert data and retrieve data in list form.. but i dont get any list and get blank page. The logcat is not giving any error.
Code: Components.java
public class Components extends Activity implements OnClickListener {
Button b1,b2,b3,b4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_components);
Intent i = getIntent();
b1= (Button) findViewById(R.id.mobile);
b2= (Button) findViewById(R.id.camera);
b3= (Button) findViewById(R.id.computer);
b4= (Button) findViewById(R.id.bike);
b1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.mobile) {
Sqlite sqll = new Sqlite(this);
sqll.insertMobile();
Intent h = new Intent(Components.this, Mobile.class);
startActivity(h);
}
}
}
Code: Sqlite.java
public class Sqlite extends SQLiteOpenHelper {
public static final String DB_NAME = "Get_Price";
public static final int DB_VERSION = 1;
public static final String MTABLE_NAME = "mobile";
public static final String COLUMN_MNAME= "mname";
public static final String COLUMN_MMODEL= "model";
public static final String COLUMN_MPRICE= "mprice";
public static final String COLUMN_MCAMERA= "mcamera";
public static final String CTABLE_NAME = "camera";
public static final String COLUMN_CNAME= "cname";
public static final String COLUMN_CMODEL= "cmodel";
public static final String COLUMN_CPRICE= "cprice";
public static final String COLUMN_CCAMERA= "ccamera";
public static final String BTABLE_NAME = "bike";
public static final String COLUMN_BNAME= "bname";
public static final String COLUMN_BMODEL= "bmodel";
public static final String COLUMN_BPRICE= "bprice";
public static final String LTABLE_NAME = "laptop";
public static final String COLUMN_LNAME= "lname";
public static final String COLUMN_LMODEL= "lmodel";
public static final String COLUMN_LPRICE= "lprice";
public Sqlite(Context context) {
super(context, DB_NAME, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CreateTableMoblie = "CREATE TABLE " + MTABLE_NAME + " ( " + COLUMN_MNAME + " TEXT, " + COLUMN_MMODEL + " TEXT "
+ COLUMN_MPRICE + " TEXT, " + COLUMN_MCAMERA + " TEXT " + " ) ";
db.execSQL(CreateTableMoblie);
String CreateTableCamera = "CREATE TABLE " + CTABLE_NAME + " ( " + COLUMN_CNAME + " TEXT, " + COLUMN_CMODEL + " TEXT "
+ COLUMN_CPRICE + " TEXT, " + COLUMN_CCAMERA + " TEXT " + " ) ";
db.execSQL(CreateTableCamera);
String CreateTableBike = "CREATE TABLE " + BTABLE_NAME + " ( " + COLUMN_BNAME + " TEXT, " + COLUMN_BMODEL + " TEXT "
+ COLUMN_BPRICE + " TEXT " + " ) ";
db.execSQL(CreateTableBike);
String CreateTableLaptop = "CREATE TABLE " + LTABLE_NAME + " ( " + COLUMN_LNAME + " TEXT, " + COLUMN_LMODEL + " TEXT "
+ COLUMN_LPRICE + " TEXT " + " ) ";
db.execSQL(CreateTableLaptop);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " +MTABLE_NAME );
db.execSQL("DROP TABLE IF EXISTS " +CTABLE_NAME );
db.execSQL("DROP TABLE IF EXISTS " +BTABLE_NAME );
db.execSQL("DROP TABLE IF EXISTS " +LTABLE_NAME );
onCreate(db);
}
public long insertMobile() {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("mname","samsung" );
values.put("mmodel","samsung2s" );
values.put("mprice",5000 );
values.put("mcamera","yes" );
database.insert("mobile", null, values);
values.put("mname","nokia" );
values.put("mmodel","nokia1100" );
values.put("mprice",2000 );
values.put("mcamera","no" );
database.insert("mobile", null, values);
values.put("mname","sony xperia" );
values.put("mmodel","xperia100" );
values.put("mprice","30000" );
values.put("mcamera","yes" );
return database.insert("mobile", null, values);
}
}
Code:Mobile.java
public class Mobile extends ListActivity {
Sqlite sql = new Sqlite(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mobile);
Intent h= getIntent();
ArrayList<HashMap<String, String>> MobileList = getAllMobiles();
ListAdapter adapter = new SimpleAdapter(Mobile.this, MobileList, R.layout.mobile_names,
new String[] {Sqlite.COLUMN_MNAME}, new int[] {R.id.nameofmobile});
setListAdapter(adapter);
}
public ArrayList<HashMap<String,String>> getAllMobiles() {
ArrayList <HashMap<String,String>> wordlist;
wordlist= new ArrayList <HashMap<String, String>>();
String Query = "SELECT * FROM mobile";
SQLiteDatabase database = sql.getWritableDatabase();
Cursor cursor = database.rawQuery(Query, null);
if (cursor.moveToFirst()) {
do {
HashMap<String,String> map = new HashMap<String, String>();
map.put(Sqlite.COLUMN_MNAME, cursor.getString(0));
map.put(Sqlite.COLUMN_MMODEL, cursor.getString(1));
map.put(Sqlite.COLUMN_MPRICE, cursor.getString(2));
map.put(Sqlite.COLUMN_MCAMERA, cursor.getString(3));
wordlist.add(map);
} while (cursor.moveToNext());
}
return wordlist;
}
}
Logcat:
04-03 12:11:32.774: E/SQLiteLog(609): (1) table mobile has no column named mprice
04-03 12:11:32.804: E/SQLiteDatabase(609): Error inserting mname=samsung mcamera=yes mprice=5000 mmodel=samsung2s
04-03 12:11:32.804: E/SQLiteDatabase(609): android.database.sqlite.SQLiteException: table mobile has no column named mprice (code 1): , while compiling: INSERT INTO mobile(mname,mcamera,mprice,mmodel) VALUES (?,?,?,?)
04-03 12:11:32.804: E/SQLiteDatabase(609): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
04-03 12:11:32.804: E/SQLiteDatabase(609): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
04-03 12:11:32.804: E/SQLiteDatabase(609): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
04-03 12:11:32.804: E/SQLiteDatabase(609): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
04-03 12:11:32.804: E/SQLiteDatabase(609): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
04-03 12:11:32.804: E/SQLiteDatabase(609): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
04-03 12:11:32.804: E/SQLiteDatabase(609): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467)
04-03 12:11:32.804: E/SQLiteDatabase(609): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
04-03 12:11:32.804: E/SQLiteDatabase(609): at com.example.get_price.Sqlite.insertMobile(Sqlite.java:85)
04-03 12:11:32.804: E/SQLiteDatabase(609): at com.example.get_price.Components.onClick(Components.java:32)
04-03 12:11:32.804: E/SQLiteDatabase(609): at android.view.View.performClick(View.java:4084)
04-03 12:11:32.804: E/SQLiteDatabase(609): at android.view.View$PerformClick.run(View.java:16966)
04-03 12:11:32.804: E/SQLiteDatabase(609): at android.os.Handler.handleCallback(Handler.java:615)
04-03 12:11:32.804: E/SQLiteDatabase(609): at android.os.Handler.dispatchMessage(Handler.java:92)
04-03 12:11:32.804: E/SQLiteDatabase(609): at android.os.Looper.loop(Looper.java:137)
04-03 12:11:32.804: E/SQLiteDatabase(609): at android.app.ActivityThread.main(ActivityThread.java:4745)
04-03 12:11:32.804: E/SQLiteDatabase(609): at java.lang.reflect.Method.invokeNative(Native Method)
04-03 12:11:32.804: E/SQLiteDatabase(609): at java.lang.reflect.Method.invoke(Method.java:511)
04-03 12:11:32.804: E/SQLiteDatabase(609): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
04-03 12:11:32.804: E/SQLiteDatabase(609): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-03 12:11:32.804: E/SQLiteDatabase(609): at dalvik.system.NativeStart.main(Native Method)
I am getting this error..
table mobile has no column named mprice
You're missing a , comma here between mmodel and mprice:
String CreateTableMoblie = "CREATE TABLE " + MTABLE_NAME + " ( " + COLUMN_MNAME + " TEXT, " + COLUMN_MMODEL + " TEXT "
+ COLUMN_MPRICE + " TEXT, " + COLUMN_MCAMERA + " TEXT " + " ) ";
should be
String CreateTableMoblie = "CREATE TABLE " + MTABLE_NAME + " ( " + COLUMN_MNAME + " TEXT, " + COLUMN_MMODEL + " TEXT, "
+ COLUMN_MPRICE + " TEXT, " + COLUMN_MCAMERA + " TEXT " + " ) ";
After changing the schema here, for example uninstall your app so that the old database file is removed.
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.
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);