RuntimeError while retriving data from sqlite database in android - java

I'm trying to insert and retrieve data from database in eclipse using sqlite, but it shows a RuntimeError. I create a layout with three edit texts and one button to create simple information from but nothing is created. I create java database with the following code:
package com.example.databasetest;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBHelper extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "teacher";
private static final String TABLE_NAME = "teacher_table";
private static final String NAME = "teacher_name";
private static final String FATHER_NAME = "father_name";
private static final String MOTHER_NAME = "mother_name";
SQLiteDatabase data=this.getWritableDatabase();
Context ctx;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
ctx=context;
Log.d("DATABASE OPERATION", "DATABASE CREATED");
}
#Override
public void onCreate(SQLiteDatabase db) {
data=db;
db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
+ NAME + " TEXT,"
+ FATHER_NAME + " TEXT,"
+ MOTHER_NAME + " INTEGER,"
+ ");");
Log.d("DATABASE OPERATION", "TABLE CREATED");
}
public void open() throws SQLException
{
DBHelper db1 = new DBHelper(ctx);
data = db1.getWritableDatabase();
}
public void close()
{
data.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXCEPTION EXISTS");
onCreate(db);
}
public void onInsert(DBHelper db,String name,String f_name, String m_name)
{
SQLiteDatabase sql= db.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put("teacher_name",name);
cv.put("father_name", f_name);
cv.put("mother_name", m_name);
sql.insert(TABLE_NAME, null, cv);
Log.d("DATABASE OPERATION", "ONE ROW INSERTED.....");
}
}
AND java file as...
package com.example.databasetest;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText NAME,FATHER,MOTHER,ID;
String name,father,mother,id;
int i=1;
Button save;
Context ctxx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NAME=(EditText)findViewById(R.id.name);
FATHER=(EditText)findViewById(R.id.father_name);
MOTHER=(EditText)findViewById(R.id.mother_name);
ID=(EditText)findViewById(R.id.emp_id);
save=(Button)findViewById(R.id.submit);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
id=ID.getText().toString();
name=NAME.getText().toString();
father=FATHER.getText().toString();
mother=MOTHER.getText().toString();
if(id.equals(i))
{
Toast.makeText(getBaseContext(), "not allow insertion", Toast.LENGTH_LONG).show();
}
else
{
DBHelper DB=new DBHelper(ctxx);
DB.open();
DB.onInsert(DB, name, father, mother);
Toast.makeText(getBaseContext(), "insertion sucessful", Toast.LENGTH_LONG).show();
finish();
}
}
});
}
}
and its show run time error when i click on button as in log cat..
05-08 02:54:05.932: D/AndroidRuntime(922): Shutting down VM
05-08 02:54:05.999: W/dalvikvm(922): threadid=1: thread exiting with uncaught exception (group=0x41465700)
05-08 02:54:06.189: E/AndroidRuntime(922): FATAL EXCEPTION: main
05-08 02:54:06.189: E/AndroidRuntime(922): java.lang.NullPointerException
05-08 02:54:06.189: E/AndroidRuntime(922): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
05-08 02:54:06.189: E/AndroidRuntime(922): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
05-08 02:54:06.189: E/AndroidRuntime(922): at com.example.databasetest.DBHelper.<init>(DBHelper.java:22)
05-08 02:54:06.189: E/AndroidRuntime(922): at com.example.databasetest.MainActivity$1.onClick(MainActivity.java:49)
05-08 02:54:06.189: E/AndroidRuntime(922): at android.view.View.performClick(View.java:4240)
05-08 02:54:06.189: E/AndroidRuntime(922): at android.view.View$PerformClick.run(View.java:17721)
05-08 02:54:06.189: E/AndroidRuntime(922): at android.os.Handler.handleCallback(Handler.java:730)
05-08 02:54:06.189: E/AndroidRuntime(922): at android.os.Handler.dispatchMessage(Handler.java:92)
05-08 02:54:06.189: E/AndroidRuntime(922): at android.os.Looper.loop(Looper.java:137)
05-08 02:54:06.189: E/AndroidRuntime(922): at android.app.ActivityThread.main(ActivityThread.java:5103)
05-08 02:54:06.189: E/AndroidRuntime(922): at java.lang.reflect.Method.invokeNative(Native Method)
05-08 02:54:06.189: E/AndroidRuntime(922): at java.lang.reflect.Method.invoke(Method.java:525)
05-08 02:54:06.189: E/AndroidRuntime(922): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
05-08 02:54:06.189: E/AndroidRuntime(922): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-08 02:54:06.189: E/AndroidRuntime(922): at dalvik.system.NativeStart.main(Native Method)
05-08 02:54:09.589: I/Process(922): Sending signal. PID: 922 SIG: 9

ctxx is never initialzed, and this probably the cause of the crash. Generally speaking, when you deal with Activity and Fragment subclass, you almost never need to keep a reference to the Context. Activity is a subclass of Context, and usually this is enough. In a Fragment you can retrieve the context of the Activity hosting the Fragment with getActivity()
Chante
DBHelper DB=new DBHelper(ctxx);
with
DBHelper DB=new DBHelper(MainActivity.this);
As #DerGolem pointed out, you are using the type INTEGER for the column MOTHER_NAME. Probably you want to use TEXT, instead, and you will also need a the primary key "_id"
db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME + " TEXT,"
+ FATHER_NAME + " TEXT,"
+ MOTHER_NAME + " TEXT"
+ ");");

In your activity initialize the ctxx in onCreate:
ctxx=this;
or
DBHelper DB=new DBHelper(MainActivity.this);
whenever you will initialize database object will null you will get sqlite locked exception.

Also fixe this
public void onCreate(SQLiteDatabase db) {
data=db;
db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
+ NAME + " TEXT,"
+ FATHER_NAME + " TEXT,"
+ MOTHER_NAME + " TEXT"
+ ");");
Log.d("DATABASE OPERATION", "TABLE CREATED");
}
for "INTEGER," remove ,.
and intialise it like this DBHelper.
DBHelper DB=new DBHelper(MainActivity.this);

You need init ctxx in onCreate() method:
ctxx = this;
If you want to know more about sqlite on android -> ok. But if you want to less code you can try some SqliteLibrary for android. (example ActiveAndroid, GreenDAO.....).

Related

I created app for local sqlite database but it not running. Please tell me the solution

This is DatabaseHelper.java class, in this class I write query for SQLite Database. I think there is not any problem in query.
package com.example.ankurnamikaze.myapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import static android.R.attr.id;
import static android.R.attr.name;
public class DatabaseHelper extends SQLiteOpenHelper {
SQLiteDatabase db;
public static final String DATABASE_NAME = "notes_db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "notes";
public static final String COL_ID = "id";
public static final String COL_NAME = "name";
public static final String COL_PASS = "pass";
This method is used for creating Database.
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (" +COL_ID + " integer autoincrement," + COL_NAME + " text," + COL_PASS+ " text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE_NAME);
onCreate(db);
}
// INSERTING ROW IN DATABASE
public void insertData(int id, String name, String pass){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_ID, id);
values.put(COL_NAME, name);
values.put(COL_PASS, pass);
db.insert(TABLE_NAME, null, values);
}
}
This is MainActivity.java class. I think I'm getting problem in defining the DatabaseHelper class because before when i defined this outside the onCreate method it make app crash then i saw some code which tell me to define it inside the onCreate method but still it didnt work for me.
package com.example.ankurnamikaze.myapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import static android.R.attr.id;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
public class MainActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
EditText name, password;
String user_name, user_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
databaseHelper = new DatabaseHelper(this);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.user_name);
password = (EditText)findViewById(R.id.user_pass);
user_name = String.valueOf(name.getText());
user_pass = String.valueOf(password.getText());
databaseHelper.insertData(id, user_name, user_pass);
}
}
This is activiy_main.xml, in this I create the attributes. And I don't think this is the source of problem.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.ankurnamikaze.myapp.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="USERNAME"
android:id="#+id/user_name"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="PASSWORD"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="sumbit"
android:id="#+id/button" />
</LinearLayout>
There are a few errors/issues.
Issue 1
You have coded " integer autoincrement," this will result in a syntax error as the AUTOINCREMENT keyword can only be used with INTEGER PRIMARY KEY (saying that it's not recommended to use it as INTEGER PRIMARY KEY is more efficient and has very much the same result, that is automatically generating a unique id (actually it only makes the id an alias of the rowid in either situation)).SQLite Autoincrement
e.g.
The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and
disk I/O overhead and should be avoided if not strictly needed. It is
usually not needed
The error would result in something along the lines of the following :-
09-19 07:32:10.040 7200-7200/? E/SQLiteLog: (1) near "autoincrement": syntax error
09-19 07:32:10.040 7200-7200/? D/AndroidRuntime: Shutting down VM
09-19 07:32:10.040 7200-7200/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa62e9288)
09-19 07:32:10.044 7200-7200/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{so52399661.so52399661/so52399661.so52399661.MainActivity}: android.database.sqlite.SQLiteException: near "autoincrement": syntax error (code 1): , while compiling: create table notes (id integer autoincrement,name text,pass text)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: near "autoincrement": syntax error (code 1): , while compiling: create table notes (id integer autoincrement,name text,pass text)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1663)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1594)
at so52399661.so52399661.DatabaseHelper.onCreate(DatabaseHelper.java:23)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at so52399661.so52399661.DatabaseHelper.insertData(DatabaseHelper.java:38)
at so52399661.so52399661.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
at android.app.ActivityThread.access$600(ActivityThread.java:130) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
Instead I'd suggest just coding :-
db.execSQL("create table " + TABLE_NAME + " (" +COL_ID + " INTEGER PRIMARY KEY," + COL_NAME + " TEXT," + COL_PASS+ " TEXT)");
Issue 2
You have no id user_pass defined in the layout.
Issue 3
id cannot be resolved (see below this isn't needed).
Solution
The following is the fixed code (see comments) with some additional code to list the tables in the Database :-
activity_main.xml (id user_pass added to PASSWORD EditText) :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="USERNAME"
android:id="#+id/user_name"/>
<EditText
android:id="#+id/user_pass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="PASSWORD"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="sumbit"
android:id="#+id/button" />
</LinearLayout>
DatabaseHelper.java (see comments) :-
public class DatabaseHelper extends SQLiteOpenHelper {
SQLiteDatabase db;
public static final String DATABASE_NAME = "notes_db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "notes";
public static final String COL_ID = "id";
public static final String COL_NAME = "name";
public static final String COL_PASS = "pass";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//db.execSQL("create table " + TABLE_NAME + " (" +COL_ID + " integer autoincrement," + COL_NAME + " text," + COL_PASS+ " text)"); //<<<<<<<<<< ERROR
db.execSQL("create table " + TABLE_NAME + " (" +COL_ID + " INTEGER PRIMARY KEY," + COL_NAME + " TEXT," + COL_PASS+ " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE_NAME);
onCreate(db);
}
// INSERTING ROW IN DATABASE
//<<<<<<<<<< as INTEGER PRIMARY KEY then id will be automatically generated
public void insertData(String name, String pass){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
//values.put(COL_ID, id); not needed will autogenerate
values.put(COL_NAME, name);
values.put(COL_PASS, pass);
db.insert(TABLE_NAME, null, values);
}
}
MainActivity.java (see comments) :-
public class MainActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
EditText name, password;
String user_name, user_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
databaseHelper = new DatabaseHelper(this);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.user_name);
password = (EditText)findViewById(R.id.user_pass);
user_name = String.valueOf(name.getText());
user_pass = String.valueOf(password.getText());
//databaseHelper.insertData(id, user_name, user_pass); //<<<<<<<<<< got rid of id
databaseHelper.insertData(user_name, user_pass);
//<<<<<<<<<< ADDED to List the tables
Cursor csr = databaseHelper.getWritableDatabase().query("sqlite_master",null,null,null,null,null,null );
while (csr.moveToNext()) {
Log.d("TABLES","Found table " + csr.getString(csr.getColumnIndex("name")));
}
csr.close();
}
}
Result in the Log :-
09-19 07:10:20.628 6977-6977/so52399661.so52399661 D/TABLES: Found table android_metadata
Found table notes
i.e. you notes table exists, android_metedata is a table created by the SQLiteOpenhelper class that you DatabaseHelper is a subclass of. It contains the locale.

SQLite Database Error Newbie

This is my first SQLite App and I found a lot of errors and I don't what to do.
Can anyone tell me what I need to do?
This is my log cat:
12-26 18:58:05.870 26185-26185/? I/art: Late-enabling -Xcheck:jni
12-26 18:58:05.889 26185-26185/? E/Environment: initForCurrentUser:userId= 0
12-26 18:58:05.889 26185-26185/? D/Environment: UserEnvironment current
userId IS : 0
12-26 18:58:05.889 26185-26185/? D/Environment: UserEnvironment PRIMARY
STORAGE IS : MEDIA_INTERNAL
12-26 18:58:05.982 26185-26185/com.example.acer.sqlitecrud I/LoadedApk: No
resource references to update in package com.hmct.hmcttheme
12-26 18:58:06.010 26185-26185/com.example.acer.sqlitecrud W/art: Before
Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
12-26 18:58:06.135 26185-26185/com.example.acer.sqlitecrud E/SQLiteLog: (1)
near "TABLEstudentTable": syntax error
12-26 18:58:06.136 26185-26185/com.example.acer.sqlitecrud D/AndroidRuntime:
Shutting down VM
12-26 18:58:06.138 26185-26185/com.example.acer.sqlitecrud E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.example.acer.sqlitecrud, PID: 26185
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.acer.sqlitecrud/com.example.acer.sqlitecrud.MainActivity}: android.database.sqlite.SQLiteException: near "TABLEstudentTable": syntax error (code 1): , while compiling: CREATE TABLEstudentTable(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2328)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2394)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1306)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5270)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:708)
Caused by: android.database.sqlite.SQLiteException: near "TABLEstudentTable": syntax error (code 1): , while compiling: CREATE TABLEstudentTable(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at com.example.acer.sqlitecrud.DatabaseHelper.onCreate(DatabaseHelper.java:27)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.example.acer.sqlitecrud.DatabaseHelper.<init>(DatabaseHelper.java:22)
at com.example.acer.sqlitecrud.MainActivity.onCreate(MainActivity.java:22)
at android.app.Activity.performCreate(Activity.java:6075)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2281)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2394) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1306) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5270) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:708) 
12-26 18:58:06.249 26185-26185/com.example.acer.sqlitecrud I/Process: Sending signal. PID: 26185 SIG: 9
This is my class:
DatabaseHelper.Java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String dbName = "Student.db";
public static final String tbName = "studentTable";
public static final String colID = "ID";
public static final String colName = "NAME";
public static final String colMarks = "MARKS";
public DatabaseHelper(Context context) {
super(context, dbName, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE"+tbName+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS"+tbName);
onCreate(db);
}
public boolean insertData (String Name, String Marks){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(colName,Name);
contentValues.put(colMarks,Marks);
long result = db.insert(tbName,null,contentValues);
if (result == -1){
return false;
}else {
return true;
}
}
}
MainActivity.java:
package com.example.acer.sqlitecrud;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText Name, Marks;
Button addData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
Name = (EditText)findViewById(R.id.edtNama);
Marks = (EditText)findViewById(R.id.edtNilai);
addData = (Button)findViewById(R.id.btnInsert);
InsertData();
}
private void InsertData() {
addData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.insertData(Name.getText().toString(),
Marks.getText().toString());
if (isInserted = true){
Toast.makeText(MainActivity.this,"Data Telah Di Inputkan !!",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this,"Data Gagal Di Inputkan !!",Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+tbName+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)");
}
note the space between the TABLE and tbName
Query syntax error, space is missing.
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+tbName+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)");
}
You are missing space in syntax of create table
db.execSQL("CREATE TABLE "+tbName+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)");
In drop table also you missed the space
"DROP TABLE IF EXISTS "+tbName
check below code
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+tbName+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)"); //add space after TABLE
}

android sqlite no such table error (code 1)

when I press the button for list database items I get this error. where is my fault? ( when I look DDMS I see exDB file in device storage ??)
VT_baglanti3 class
public class VT_baglanti3 extends SQLiteOpenHelper {
// DataBase oluşturma
private static final String VT="exDB"; // veri tabanı adi
private static final Integer SURUM=1; // veri tabanı sürümü
public VT_baglanti3(Context c) {
super(c, VT, null, SURUM); // yukarıda tanımlanan değişkenleri parametre olarak verdik.
}
#Override
public void onCreate(SQLiteDatabase db) {
// tablo ekleme
db.execSQL("CREATE TABLE IF NOT EXISTS EMP_TABLE(_id integer primary key,E_NAME text,E_AGE text,E_DEPT text)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
F_tarif_yaz class
public class F_tarif_yaz extends Fragment {
private View root;
Context con;
private VT_baglanti3 db;
private TextView txt;
Button bt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.tarif_yaz, container, false);
con=inflater.getContext();
db=new VT_baglanti3(con);
txt=(TextView)root.findViewById(R.id.txt);
bt=(Button)root.findViewById(R.id.bt);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Listele2();
}
});
return root;
}
private void Listele2(){
String sutunlar[]={"E_NAME","E_AGE","E_DEPT"};
SQLiteDatabase sldb2=db.getReadableDatabase();
Cursor cursor1=sldb2.query("exDB",sutunlar,null,null,null,null,null);
String tumbilgi="";
while (cursor1.moveToNext()){
String adbilgi=cursor1.getString(cursor1.getColumnIndex("E_NAME"));
String soyadbilgi=cursor1.getString(cursor1.getColumnIndex("E_AGE"));
String nobilgi=cursor1.getString(cursor1.getColumnIndex("E_DEPT"));
tumbilgi += adbilgi + " " + soyadbilgi + " " + nobilgi + " " + "\n";
}
txt.setText(tumbilgi);
}
}
Error log
/com.yeni E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.yeni, PID: 1442
android.database.sqlite.SQLiteException: no such table: exDB (code 1): , while compiling: SELECT E_NAME, E_AGE, E_DEPT FROM exDB
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
at com.yeni.F_tarif_yaz.Listele2(F_tarif_yaz.java:50)
at com.yeni.F_tarif_yaz.access$000(F_tarif_yaz.java:15)
at com.yeni.F_tarif_yaz$1.onClick(F_tarif_yaz.java:39)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Error lines
com.yeni.F_tarif_yaz.Listele2(F_tarif_yaz.java:50) at Cursor cursor1=sldb2.query("exDB",sutunlar,null,null,null,null,null);
DDMS i see exDB file in device storage
There's no TABLE named exDB in your database. File name of your sqlite database is completely irrelevant.
See: https://sqlite.org/lang_createtable.html

Trouble implementing database into android project

I've been following This guide for implementing a database in an android project.
This is the code for my DBAdapter class:
package com.sab.namespace;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter
{
public static final String KEY_ROWID = "_id";
public static final String KEY_PROPERTYID = "propertyid";
public static final String KEY_ADDRESS = "propertyaddress";
public static final String KEY_JOBNO = "jobnumber";
public static final String KEY_ASSIGNED = "assignedto";
public static final String KEY_COMPANY = "company";
public static final String KEY_DATE = "datecreated";
public static final String KEY_MASTERKEY = "usemasterkey";
public static final String KEY_PHONEBEFORE = "phonebefore";
public static final String KEY_PROBLEM = "descriptionofproblem";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "SABDatabase";
private static final String DATABASE_TABLE = "jobs";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table jobs (_id integer primary key autoincrement, "
+ "propertyid text not null, propertyaddress text not null, "
+ "jobnumber text not null, assignedto text not null, "
+ "company text not null, datecreated text not null, "
+ "usemasterkey text not null, phonebefore text not null, "
+ "descriptionofproblem text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
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 jobs");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a job into the database---
public long insertJob(String propertyid, String propertyaddress, String jobnumber,
String assignedto, String company, String datecreated, String usemasterkey,
String phonebefore, String descriptionofproblem)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_PROPERTYID, propertyid);
initialValues.put(KEY_ADDRESS, propertyaddress);
initialValues.put(KEY_JOBNO, jobnumber);
initialValues.put(KEY_ASSIGNED, assignedto);
initialValues.put(KEY_COMPANY, company);
initialValues.put(KEY_DATE, datecreated);
initialValues.put(KEY_MASTERKEY, usemasterkey);
initialValues.put(KEY_PHONEBEFORE, phonebefore);
initialValues.put(KEY_PROBLEM, descriptionofproblem);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular job---
public boolean deleteJob(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
//---retrieves all the jobs---
public Cursor getAllJobs()
{
return db.query(DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_PROPERTYID,
KEY_ADDRESS,
KEY_JOBNO,
KEY_ASSIGNED,
KEY_COMPANY,
KEY_DATE,
KEY_MASTERKEY,
KEY_PHONEBEFORE,
KEY_PROBLEM},
null,
null,
null,
null,
null);
}
//---retrieves a particular job---
public Cursor getJob(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_PROPERTYID,
KEY_ADDRESS,
KEY_JOBNO,
KEY_ASSIGNED,
KEY_COMPANY,
KEY_DATE,
KEY_MASTERKEY,
KEY_PHONEBEFORE,
KEY_PROBLEM},
KEY_ROWID + "=" + rowId,
null,
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//---updates a job---
public boolean updateJob(long rowId, String propertyid, String propertyaddress, String jobnumber,
String assignedto, String company, String datecreated, String usemasterkey,
String phonebefore, String descriptionofproblem)
{
ContentValues args = new ContentValues();
args.put(KEY_PROPERTYID, propertyid);
args.put(KEY_ADDRESS, propertyaddress);
args.put(KEY_JOBNO, jobnumber);
args.put(KEY_ASSIGNED, assignedto);
args.put(KEY_COMPANY, company);
args.put(KEY_DATE, datecreated);
args.put(KEY_MASTERKEY, usemasterkey);
args.put(KEY_PHONEBEFORE, phonebefore);
args.put(KEY_PROBLEM, descriptionofproblem);
return db.update(DATABASE_TABLE, args,
KEY_ROWID + "=" + rowId, null) > 0;
}
}
And then I try to use the database in my ViewJobs.java class
DBAdapter db = new DBAdapter(this);
db.open();
long id;
id = db.insertJob(
"PROP121",
"MARK ANDREWS DRIVE",
"JOB32",
"COLIN",
"SAB",
"12/4/13",
"yes",
"yes",
"SHIT IS EVERYWHERE");
id = db.insertJob(
"PROP122",
"FAULTY CLOSE",
"JOB33",
"DAVE",
"SAB",
"13/4/13",
"yes",
"yes",
"FIX PLEASE");
db.close();
Toast.makeText(this, Long.toString(id), Toast.LENGTH_LONG).show();
Toast outputs -1 which tells me there has been an error with inputting the data but I can't find where I've gone wrong.
If I just ignore the error and continue on with the following code then my application crashes.
db.open();
Cursor c = db.getAllJobs();
db.close();
I would be very grateful if anyone could offer any advice!
-Harry
Here is the logcat code for when it crashes:
03-04 18:37:59.760: W/dalvikvm(2078): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
03-04 18:37:59.809: I/dalvikvm(2078): threadid=3: reacting to signal 3
03-04 18:37:59.958: E/AndroidRuntime(2078): FATAL EXCEPTION: main
03-04 18:37:59.958: E/AndroidRuntime(2078): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sab.namespace/com.sab.namespace.ViewJobs}: android.database.sqlite.SQLiteException: no such table: jobs: , while compiling: SELECT _id, propertyid, propertyaddress, jobnumber, assignedto, company, datecreated, usemasterkey, phonebefore, descriptionofproblem FROM jobs
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.app.ActivityThread.access$600(ActivityThread.java:123)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.os.Handler.dispatchMessage(Handler.java:99)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.os.Looper.loop(Looper.java:137)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.app.ActivityThread.main(ActivityThread.java:4424)
03-04 18:37:59.958: E/AndroidRuntime(2078): at java.lang.reflect.Method.invokeNative(Native Method)
03-04 18:37:59.958: E/AndroidRuntime(2078): at java.lang.reflect.Method.invoke(Method.java:511)
03-04 18:37:59.958: E/AndroidRuntime(2078): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-04 18:37:59.958: E/AndroidRuntime(2078): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-04 18:37:59.958: E/AndroidRuntime(2078): at dalvik.system.NativeStart.main(Native Method)
03-04 18:37:59.958: E/AndroidRuntime(2078): Caused by: android.database.sqlite.SQLiteException: no such table: jobs: , while compiling: SELECT _id, propertyid, propertyaddress, jobnumber, assignedto, company, datecreated, usemasterkey, phonebefore, descriptionofproblem FROM jobs
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:127)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:94)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:53)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1564)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1449)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1405)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1485)
03-04 18:37:59.958: E/AndroidRuntime(2078): at com.sab.namespace.DBAdapter.getAllJobs(DBAdapter.java:114)
03-04 18:37:59.958: E/AndroidRuntime(2078): at com.sab.namespace.ViewJobs.onCreate(ViewJobs.java:52)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.app.Activity.performCreate(Activity.java:4465)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
03-04 18:37:59.958: E/AndroidRuntime(2078): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
03-04 18:37:59.958: E/AndroidRuntime(2078): ... 11 more
03-04 18:37:59.969: I/dalvikvm(2078): Wrote stack traces to '/data/anr/traces.txt'
03-04 18:38:00.328: I/dalvikvm(2078): threadid=3: reacting to signal 3
03-04 18:38:00.358: I/dalvikvm(2078): Wrote stack traces to '/data/anr/traces.txt'
03-04 18:38:00.658: I/dalvikvm(2078): threadid=3: reacting to signal 3
03-04 18:38:00.799: I/dalvikvm(2078): Wrote stack traces to '/data/anr/traces.txt'
03-04 18:38:03.210: I/Process(2078): Sending signal. PID: 2078 SIG: 9
Here is the full code for ViewJobs.java
package com.sab.namespace;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class ViewJobs extends Activity {
String titles[] = {"hello","bannana","frogshehe","hello","bannana","frogshehe","hello","bannana","frogshehe","hello","bannana","frogshehe","hello","bannana","frogshehe"};
ListView vListView;
ArrayAdapter<String> lVAAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
//database stuff
DBAdapter db = new DBAdapter(this);
db.open();
long id;
id = db.insertJob(
"PROP121",
"MARK ANDREWS DRIVE",
"JOB32",
"COLIN",
"SAB",
"12/4/13",
"yes",
"yes",
"SHIT IS EVERYWHERE");
id = db.insertJob(
"PROP122",
"FAULTY CLOSE",
"JOB33",
"DAVE",
"SAB",
"13/4/13",
"yes",
"yes",
"FIX PLEASE");
db.close();
Toast.makeText(this, Long.toString(id), Toast.LENGTH_LONG).show();
db.open();
Cursor c = db.getAllJobs();
db.close();
/*
if (c.moveToFirst())
{
do {
DisplayJob(c);
} while (c.moveToNext());
}
db.close();
*/
//create list
vListView = (ListView) findViewById(R.id.vlistview);
lVAAdapter = new ArrayAdapter<String>(ViewJobs.this,
android.R.layout.simple_list_item_1, titles);
//create listener
vListView.setAdapter(lVAAdapter);
vListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> lVAAdapter, View myView,
int myItemInt, long mylng) {
String selectedFromList = (String) (vListView.getItemAtPosition(myItemInt));
if (titles[myItemInt] == "hello") {
titles[2] = "test";
vListView.invalidateViews();
}
}
});
}
public void DisplayJob(Cursor c)
{
Toast.makeText(this,
"id: " + c.getString(0) + "\n" +
"propertyid: " + c.getString(1) + "\n" +
"propertyaddress: " + c.getString(2) + "\n" +
"jobnumber: " + c.getString(3) + "\n" +
"assignedto: " + c.getString(4) + "\n" +
"company: " + c.getString(5) + "\n" +
"datecreated: " + c.getString(6) + "\n" +
"usemasterkey: " + c.getString(7) + "\n" +
"phonebefore: " + c.getString(8) + "\n" +
"descriptionofproblem: " + c.getString(9),
Toast.LENGTH_LONG).show();
}
}
You probably added the jobs table after creating the database. The onCreate would not be called. So you need to clear the data for the onCreate to be called again.

SQLite Cursor crashes

i have a problem with my SQLite class. In fact, i was learning how to setting up (update and read) a database on android and I successfully wrote on the database, but when i try to read the informations and display them on the screen, my application just crashes.
I searched the problem and found that the cause of the crash is the Cursor. I commented the cursor's method, so if someone can help me with that, i would be thankful.
This my Database class.
package com.example.sqlprogramming;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseClass {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "person_name";
public static final String KEY_RATE = "person_rate";
private static final String DATABASE_NAME = "HotOrNotdb";
private static final String DATABASE_TABLE = "peopleTable";
private static final int DATABASE_VERSION = 2;
private Dhelper ourHelperdb;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class Dhelper extends SQLiteOpenHelper{
public Dhelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table if not exists " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + "VARCHAR NOT NULL, " +
KEY_RATE + "VARCHAR NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public DatabaseClass(Context c){
ourContext = c;
}
public DatabaseClass open() throws SQLException{
ourHelperdb = new Dhelper(ourContext);
ourDatabase = ourHelperdb.getWritableDatabase();
return this;
}
public void close(){
ourHelperdb.close();
}
public long addEntry(String personName, String personHotness) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, personName);
cv.put(KEY_RATE, personHotness);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
//HERE IS MY PROBLEM WITH THE CURSOR
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_RATE};
String result = "hello";
Cursor c = ourDatabase.query(true, DATABASE_TABLE, columns, null, null, null, null, null, null);
int iRowId = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iRate = c.getColumnIndex(KEY_RATE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRowId) + " " + c.getString(iName) +" " + c.getString(iRate) + "\n";
}
c.close();
return result;
}
}
And this Class call the Database Class and should take informations from database to display it on the screen.
package com.example.sqlprogramming;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class SQLview extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_sqlview);
TextView textInfo = (TextView) findViewById (R.id.tvSQLinfo);
DatabaseClass info = new DatabaseClass(this);
info.open();
String _data = info.getData();
info.close();
textInfo.setText(_data);
}
}
Thank you again.
I'll post stacktrace and logcat soon.
Here is my Logcat/Stacktrace
02-24 20:08:12.378: E/Curosr!(1221): I got an error here :
02-24 20:08:12.378: E/Curosr!(1221): android.database.sqlite.SQLiteException: no such column: person_name (code 1): , while compiling: SELECT _id AS _id, person_name, person_rate FROM peopleTable
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
02-24 20:08:12.378: E/Curosr!(1221): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
02-24 20:08:12.378: E/Curosr!(1221): at com.example.sqlprogramming.DatabaseClass.getData(DatabaseClass.java:75)
02-24 20:08:12.378: E/Curosr!(1221): at com.example.sqlprogramming.SQLview.onCreate(SQLview.java:14)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.Activity.performCreate(Activity.java:5104)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
02-24 20:08:12.378: E/Curosr!(1221): at android.os.Handler.dispatchMessage(Handler.java:99)
02-24 20:08:12.378: E/Curosr!(1221): at android.os.Looper.loop(Looper.java:137)
02-24 20:08:12.378: E/Curosr!(1221): at android.app.ActivityThread.main(ActivityThread.java:5039)
02-24 20:08:12.378: E/Curosr!(1221): at java.lang.reflect.Method.invokeNative(Native Method)
02-24 20:08:12.378: E/Curosr!(1221): at java.lang.reflect.Method.invoke(Method.java:511)
02-24 20:08:12.378: E/Curosr!(1221): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-24 20:08:12.378: E/Curosr!(1221): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-24 20:08:12.378: E/Curosr!(1221): at dalvik.system.NativeStart.main(Native Method)
Your create statement is missing a few spaces. Try using:
db.execSQL("create table if not exists " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " VARCHAR NOT NULL, " +
KEY_RATE + " VARCHAR NOT NULL);");
According to your current statement, your last two column names become person_nameVARCHAR and person_rateVARCHAR
If you're reading, you need to use:
ourDatabase = ourHelperdb.getReadableDatabase();
When you open your DB, you are setting it to write.
(That's my first guess, post stack trace).
Here's a working example from some of my code on how to read a cursor:
mDb = mDbHelper.getReadableDatabase();
Cursor c = mDb.query("Timesheets", new String[] {
KEY_TIMESHEETS_ROWID + " AS _id", KEY_TIMESHEETS_DESCRIPTION,
KEY_TIMESHEETS_TITLE, KEY_TIMESHEETS_DATE_START,
KEY_TIMESHEETS_DATE_END, KEY_TIMESHEETS_INVOICED,
KEY_TIMESHEETS_PROJECTID }, "timesheet_id = ?",
new String[] { String.valueOf(timesheetId) }, null, null, null);
c.moveToFirst();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Timesheet timesheet = new Timesheet();
while (c.isAfterLast() == false) {
timesheet.setTimesheetId(c.getInt(0));
// ...
c.moveToNext();
}
c.close();

Categories