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
}
Related
This is DatabaseHelper.java class, in this class I write query for SQLite Database. I think there is not any problem in query.
package com.example.ankurnamikaze.myapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import static android.R.attr.id;
import static android.R.attr.name;
public class DatabaseHelper extends SQLiteOpenHelper {
SQLiteDatabase db;
public static final String DATABASE_NAME = "notes_db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "notes";
public static final String COL_ID = "id";
public static final String COL_NAME = "name";
public static final String COL_PASS = "pass";
This method is used for creating Database.
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (" +COL_ID + " integer autoincrement," + COL_NAME + " text," + COL_PASS+ " text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE_NAME);
onCreate(db);
}
// INSERTING ROW IN DATABASE
public void insertData(int id, String name, String pass){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_ID, id);
values.put(COL_NAME, name);
values.put(COL_PASS, pass);
db.insert(TABLE_NAME, null, values);
}
}
This is MainActivity.java class. I think I'm getting problem in defining the DatabaseHelper class because before when i defined this outside the onCreate method it make app crash then i saw some code which tell me to define it inside the onCreate method but still it didnt work for me.
package com.example.ankurnamikaze.myapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import static android.R.attr.id;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
public class MainActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
EditText name, password;
String user_name, user_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
databaseHelper = new DatabaseHelper(this);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.user_name);
password = (EditText)findViewById(R.id.user_pass);
user_name = String.valueOf(name.getText());
user_pass = String.valueOf(password.getText());
databaseHelper.insertData(id, user_name, user_pass);
}
}
This is activiy_main.xml, in this I create the attributes. And I don't think this is the source of problem.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.ankurnamikaze.myapp.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="USERNAME"
android:id="#+id/user_name"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="PASSWORD"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="sumbit"
android:id="#+id/button" />
</LinearLayout>
There are a few errors/issues.
Issue 1
You have coded " integer autoincrement," this will result in a syntax error as the AUTOINCREMENT keyword can only be used with INTEGER PRIMARY KEY (saying that it's not recommended to use it as INTEGER PRIMARY KEY is more efficient and has very much the same result, that is automatically generating a unique id (actually it only makes the id an alias of the rowid in either situation)).SQLite Autoincrement
e.g.
The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and
disk I/O overhead and should be avoided if not strictly needed. It is
usually not needed
The error would result in something along the lines of the following :-
09-19 07:32:10.040 7200-7200/? E/SQLiteLog: (1) near "autoincrement": syntax error
09-19 07:32:10.040 7200-7200/? D/AndroidRuntime: Shutting down VM
09-19 07:32:10.040 7200-7200/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa62e9288)
09-19 07:32:10.044 7200-7200/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{so52399661.so52399661/so52399661.so52399661.MainActivity}: android.database.sqlite.SQLiteException: near "autoincrement": syntax error (code 1): , while compiling: create table notes (id integer autoincrement,name text,pass text)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: near "autoincrement": syntax error (code 1): , while compiling: create table notes (id integer autoincrement,name text,pass text)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1663)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1594)
at so52399661.so52399661.DatabaseHelper.onCreate(DatabaseHelper.java:23)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at so52399661.so52399661.DatabaseHelper.insertData(DatabaseHelper.java:38)
at so52399661.so52399661.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Instead I'd suggest just coding :-
db.execSQL("create table " + TABLE_NAME + " (" +COL_ID + " INTEGER PRIMARY KEY," + COL_NAME + " TEXT," + COL_PASS+ " TEXT)");
Issue 2
You have no id user_pass defined in the layout.
Issue 3
id cannot be resolved (see below this isn't needed).
Solution
The following is the fixed code (see comments) with some additional code to list the tables in the Database :-
activity_main.xml (id user_pass added to PASSWORD EditText) :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="USERNAME"
android:id="#+id/user_name"/>
<EditText
android:id="#+id/user_pass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="PASSWORD"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="sumbit"
android:id="#+id/button" />
</LinearLayout>
DatabaseHelper.java (see comments) :-
public class DatabaseHelper extends SQLiteOpenHelper {
SQLiteDatabase db;
public static final String DATABASE_NAME = "notes_db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "notes";
public static final String COL_ID = "id";
public static final String COL_NAME = "name";
public static final String COL_PASS = "pass";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//db.execSQL("create table " + TABLE_NAME + " (" +COL_ID + " integer autoincrement," + COL_NAME + " text," + COL_PASS+ " text)"); //<<<<<<<<<< ERROR
db.execSQL("create table " + TABLE_NAME + " (" +COL_ID + " INTEGER PRIMARY KEY," + COL_NAME + " TEXT," + COL_PASS+ " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE_NAME);
onCreate(db);
}
// INSERTING ROW IN DATABASE
//<<<<<<<<<< as INTEGER PRIMARY KEY then id will be automatically generated
public void insertData(String name, String pass){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
//values.put(COL_ID, id); not needed will autogenerate
values.put(COL_NAME, name);
values.put(COL_PASS, pass);
db.insert(TABLE_NAME, null, values);
}
}
MainActivity.java (see comments) :-
public class MainActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
EditText name, password;
String user_name, user_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
databaseHelper = new DatabaseHelper(this);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.user_name);
password = (EditText)findViewById(R.id.user_pass);
user_name = String.valueOf(name.getText());
user_pass = String.valueOf(password.getText());
//databaseHelper.insertData(id, user_name, user_pass); //<<<<<<<<<< got rid of id
databaseHelper.insertData(user_name, user_pass);
//<<<<<<<<<< ADDED to List the tables
Cursor csr = databaseHelper.getWritableDatabase().query("sqlite_master",null,null,null,null,null,null );
while (csr.moveToNext()) {
Log.d("TABLES","Found table " + csr.getString(csr.getColumnIndex("name")));
}
csr.close();
}
}
Result in the Log :-
09-19 07:10:20.628 6977-6977/so52399661.so52399661 D/TABLES: Found table android_metadata
Found table notes
i.e. you notes table exists, android_metedata is a table created by the SQLiteOpenhelper class that you DatabaseHelper is a subclass of. It contains the locale.
This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 4 years ago.
hi i´m trying to create a table but it doesn´t work here is my code:
public class AnecdotasSQLiteHelper extends SQLiteOpenHelper {
static final String DATABASE_NAME = "AnecdotasDB";
static final int DATABASE_VERSION = 1;
ArrayList<Anecdota> listaAnecdotas;
static final String CREATE_TABLE_ANECDOTAS =
"CREATE TABLE "+ AnecdotasDBContract.Entry.TABLE_NAME +
"( "+ AnecdotasDBContract.Entry.COLUMN_TITULO +
" TEXT NOT NULL ,"+
AnecdotasDBContract.Entry.COLUMN_ANECDOTA +
" TEXT NOT NULL)";
public AnecdotasSQLiteHelper(Context contexto) {
super(contexto, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_ANECDOTAS);
cargaInicial(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +
AnecdotasDBContract.Entry.TABLE_NAME);
onCreate(db);
}
}
AnecdotasDBContract
public class AnecdotasDBContract {
public static abstract class Entry {
public static final String TABLE_NAME = "ANECDOTAS";
public static final String COLUMN_TITULO = "TITULO";
public static final String COLUMN_ANECDOTA = "ANECDOTA";
}
}
in other projects that i have created all run perfectly but i don´t understanda why i have this error
03-16 14:27:38.834 15171-15171/com.example.mario.especial50 E/SQLiteLog: (1) no such table: ANECDOTAS
03-16 14:27:38.835 15171-15171/com.example.mario.especial50 D/AndroidRuntime: Shutting down VM
03-16 14:27:38.837 15171-15171/com.example.mario.especial50 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mario.especial50, PID: 15171
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mario.especial50/com.example.mario.especial50.Anecdotas}: android.database.sqlite.SQLiteException: no such table: ANECDOTAS (code 1): , while compiling: SELECT * FROM ANECDOTAS
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2831)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2906)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1605)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:172)
at android.app.ActivityThread.main(ActivityThread.java:6637)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: android.database.sqlite.SQLiteException: no such table: ANECDOTAS (code 1): , while compiling: SELECT * FROM ANECDOTAS
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:1318)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1257)
at baseDatos.AnecdotasDataSource.leerAnecdotas(AnecdotasDataSource.java:49)
at com.example.mario.especial50.Anecdotas.cargarLista(Anecdotas.java:51)
at com.example.mario.especial50.Anecdotas.onCreate(Anecdotas.java:38)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2784)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2906)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1605)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:172)
at android.app.ActivityThread.main(ActivityThread.java:6637)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
try this
package com.historyplay.sanjosehills.util;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class AnecdotasSQLiteHelper extends SQLiteOpenHelper {
static final String DATABASE_NAME = "AnecdotasDB";
static final int DATABASE_VERSION = 1;
ArrayList<Anecdota> listaAnecdotas;
static final String CREATE_TABLE_ANECDOTAS =
"CREATE TABLE "+ AnecdotasDBContract.Entry.TABLE_NAME +
"( "+ AnecdotasDBContract.Entry.COLUMN_TITULO +
" TEXT NOT NULL ,"+
AnecdotasDBContract.Entry.COLUMN_ANECDOTA +
" TEXT NOT NULL)";
SQLiteDatabase db;
public AnecdotasSQLiteHelper(Context contexto) {
super(contexto, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_ANECDOTAS);
this.db = db;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +
AnecdotasDBContract.Entry.TABLE_NAME);
onCreate(db);
}
public void cargaInicial(){
// not receive db as parameter, then use this.db
.... your code
}
}
and call the class outside where execute the getWritableDatabase method
AnecdotasSQLiteHelper store = new AnecdotasSQLiteHelper(this.getContext(), "ANECDOTASDB", null, 1);
store.getWritableDatabase();
store.cargaInicial();
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
I have one database but I want to make 2 tables for separate classes. One for saving new user data and one for saving user's sessions. The one I am trying to get to work is the table consisted of the Session Title, Time, Active. The table for User Username, First, Last works but the one for the session doesn't. Ultimately, I want to put 2 tables in one database/java class which is the "ListBaseHelper". Where did I go wrong?
Here is the Java Class with the database and tables:
public class ListBaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "listBase.db";
private static final int DATABASE_VERSION = 2;
//Define a query for creating table so you don't get lost
private static final String CREATE_QUERY =
"CREATE TABLE " + ListTable.TABLE_NAME + "(" + ListDbSchema.ListTable.USERNAME + " TEXT," +
ListDbSchema.ListTable.FIRST + " TEXT," + ListDbSchema.ListTable.LAST + " TEXT);";
private static final String CREATE_QUERY2 =
"CREATE TABLE " + ListTable.TABLE_NAME2 + "(" + ListDbSchema.ListTable.TITLE + " TEXT," +
ListDbSchema.ListTable.TIME + " TEXT," + ListDbSchema.ListTable.ACTIVE + " TEXT);";
public ListBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//Log message
Log.e("DATABASE OPERATIONS", "Database created /opened...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DATABASE OPERATIONS", "Table created...");
db.execSQL(CREATE_QUERY2);
Log.e("DATABASE OPERATIONS", "Table created...");
}
public void addInformations(String username, String first, String last, SQLiteDatabase db) {
ContentValues contentValues = new ContentValues();
contentValues.put(ListTable.USERNAME, username);
contentValues.put(ListTable.FIRST, first);
contentValues.put(ListTable.LAST, last);
db.insert(ListDbSchema.ListTable.TABLE_NAME, null, contentValues);
Log.e("DATABASE OPERATIONS", "One row inserted...");
}
public void addSessionInfo(String title, String time, String active, SQLiteDatabase db) {
ContentValues contentValues = new ContentValues();
contentValues.put(ListTable.TITLE, title);
contentValues.put(ListTable.TIME, time);
contentValues.put(ListTable.ACTIVE, active);
db.insert(ListDbSchema.ListTable.TABLE_NAME2, null, contentValues);
Log.e("DATABASE OPERATIONS", "One row inserted...");
}
public Cursor getInformations(SQLiteDatabase db) {
Cursor cursor;
String[] projections = {ListTable.USERNAME, ListTable.FIRST, ListTable.LAST};
cursor = db.query(ListDbSchema.ListTable.TABLE_NAME, projections, null, null, null, null, null);
return cursor;
}
public Cursor SessionInformations(SQLiteDatabase db) {
Cursor cursor2;
String[] projections = {ListTable.TITLE, ListTable.TIME, ListTable.ACTIVE};
cursor2 = db.query(ListDbSchema.ListTable.TABLE_NAME2, projections, null, null, null, null, null);
return cursor2;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
When this java class runs, it will ask user for input.
public class NewSessionActivity extends AppCompatActivity {
EditText SessionTitle, SessionTime, SessionActive;
Context context = this;
ListBaseHelper sessionbasehelper;
SQLiteDatabase sqliteDatabase;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logoff_menu_item) {
super.onOptionsItemSelected(item);
Toast.makeText(this, "Logging You Off...", Toast.LENGTH_LONG).show();
startActivity(new Intent(NewSessionActivity.this, LaunchActivity.class));
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_session);
SessionTitle = (EditText) findViewById(R.id.title);
SessionTime = (EditText) findViewById(R.id.time);
SessionActive = (EditText) findViewById(R.id.active);
}
public void btn_submit(View view) {
{
context = this;
String title = SessionTitle.getText().toString();
String time = SessionTime.getText().toString();
String active = SessionActive.getText().toString();
sessionbasehelper= new ListBaseHelper(context);
sqliteDatabase = sessionbasehelper.getWritableDatabase();
sessionbasehelper.addSessionInfo(title,time,active,sqliteDatabase);
Toast.makeText(getBaseContext(), "New Session Saved!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(NewSessionActivity.this, ViewAllSessionsActivity.class);
startActivity(intent);
sessionbasehelper.close();
}
}
}
When java class runs, it's supposed to show the data the user entered from NewSessionActivity above.
public class ViewAllSessionsActivity extends AppCompatActivity{
//Create instance of database
ListBaseHelper myDb;
Button btn_logout;
ListView sessionlistView;
SQLiteDatabase sqLiteDatabase;
ListBaseHelper listbaseDbHelper;
Cursor cursor2;
SessionDataAdapter sessionDataAdapter;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logoff_menu_item) {
super.onOptionsItemSelected(item);
Toast.makeText(this, "Logging You Off...", Toast.LENGTH_LONG).show();
startActivity(new Intent(ViewAllSessionsActivity.this, LaunchActivity.class));
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_sessions);
sessionlistView = (ListView) findViewById(R.id.listViewSession);
sessionDataAdapter = new SessionDataAdapter(getApplicationContext(),R.layout.all_session_layout);
sessionlistView.setAdapter(sessionDataAdapter);
listbaseDbHelper = new ListBaseHelper(getApplicationContext());
sqLiteDatabase = listbaseDbHelper.getReadableDatabase();
cursor2 = listbaseDbHelper.SessionInformations(sqLiteDatabase);
if(cursor2.moveToFirst())
{
do {
String title, time, active;
title = cursor2.getString(0);
time = cursor2.getString(1);
active = cursor2.getString(2);
SessionList sessionlist = new SessionList(title, time, active);
sessionDataAdapter.add(sessionlist);
}while (cursor2.moveToNext());
}
btn_logout = (Button)findViewById(R.id.complete_button);
btn_logout.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//Use the name of this class, and the name class where you want to be taken when the button is clicked.
Intent intent = new Intent(ViewAllSessionsActivity.this, PaymentActivity.class);
startActivity(intent);
}
});
}
}
This is the LogCat when I run my app:
09-26 10:54:06.071 2712-2712/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: Database created /opened...
09-26 10:54:24.365 2712-2712/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: Database created /opened...
09-26 10:54:24.368 2712-2712/com.bignerdranch.android.assignment2 E/SQLiteLog: (1) no such table: table_name2
09-26 10:54:24.369 2712-2712/com.bignerdranch.android.assignment2 E/SQLiteDatabase: Error inserting title=Hi time=10:22 active=yes
android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: INSERT INTO table_name2(title,time,active) VALUES (?,?,?)
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.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.bignerdranch.android.assignment2.database.ListBaseHelper.addSessionInfo(ListBaseHelper.java:65)
at com.bignerdranch.android.assignment2.NewSessionActivity.btn_submit(NewSessionActivity.java:62)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-26 10:54:24.370 2712-2712/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: One row inserted...
09-26 10:54:24.919 2712-2712/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: Database created /opened...
09-26 10:54:24.941 2712-2712/com.bignerdranch.android.assignment2 E/SQLiteLog: (1) no such table: table_name2
09-26 10:54:24.951 2712-2712/com.bignerdranch.android.assignment2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bignerdranch.android.assignment2, PID: 2712
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bignerdranch.android.assignment2/com.bignerdranch.android.assignment2.ViewAllSessionsActivity}: android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: SELECT title, time, active FROM table_name2
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: SELECT title, time, active FROM table_name2
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:1316)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1163)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1034)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1202)
at com.bignerdranch.android.assignment2.database.ListBaseHelper.SessionInformations(ListBaseHelper.java:82)
at com.bignerdranch.android.assignment2.ViewAllSessionsActivity.onCreate(ViewAllSessionsActivity.java:60)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-26 10:54:38.877 3535-3535/com.bignerdranch.android.assignment2 E/DATABASE OPERATIONS: Database created /opened...
09-26 10:54:38.892 3535-3535/com.bignerdranch.android.assignment2 E/SQLiteLog: (1) no such table: table_name2
09-26 10:54:38.893 3535-3535/com.bignerdranch.android.assignment2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bignerdranch.android.assignment2, PID: 3535
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bignerdranch.android.assignment2/com.bignerdranch.android.assignment2.ViewAllSessionsActivity}: android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: SELECT title, time, active FROM table_name2
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.database.sqlite.SQLiteException: no such table: table_name2 (code 1): , while compiling: SELECT title, time, active FROM table_name2
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:1316)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1163)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1034)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1202)
at com.bignerdranch.android.assignment2.database.ListBaseHelper.SessionInformations(ListBaseHelper.java:82)
at com.bignerdranch.android.assignment2.ViewAllSessionsActivity.onCreate(ViewAllSessionsActivity.java:60)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I was writing an app using Android Studio. It's simple app for exercises.
I was sure it will work, but no. Something is wrong.
I will paste my code here:
package programowanie.android.sql;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DatabaseHelper db;
EditText editTextImie;
EditText editTextNazwisko;
EditText editTextTelefon;
EditText editTextEmail;
EditText editTextUlica;
EditText editTextKod;
Button btDodaj;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(this);
editTextImie = (EditText) findViewById(R.id.editTextImie);
editTextNazwisko = (EditText) findViewById(R.id.editTextNazwisko);
editTextTelefon = (EditText) findViewById(R.id.editTextTelefon);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextUlica = (EditText) findViewById(R.id.editTextUlica);
editTextKod = (EditText) findViewById(R.id.editTextKod);
btDodaj = (Button) findViewById(R.id.btDodaj);
btDodaj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean czysieudalo;
czysieudalo = db.wstawdane(editTextImie.getText().toString(), editTextNazwisko.getText().toString(), editTextTelefon.getText().toString(), editTextEmail.getText().toString(), editTextUlica.getText().toString(), editTextKod.getText().toString());
if(czysieudalo){
Toast.makeText(MainActivity.this, "Udało się!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Niestety nie udało się :(!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
This is my DatabaseHelper class:
package programowanie.android.sql;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Kudłaty on 2016-02-19.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String database_name ="Kontakty";
public static final String database_table ="Osoby";
public DatabaseHelper(Context context) {
super(context, database_name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table" + database_table + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, IMIE TEXT, NAZWISKO TEXT, NUMER_TELEFONU TEXT, EMAIL TEXT, ULICA TEXT, KOD_MIASTO TEXT");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST" + database_table);
onCreate(db);
}
public boolean wstawdane(String imie, String nazwisko, String nr_tel, String email, String ulica, String kod ){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("Imie", imie);
cv.put("Nazwisko", nazwisko);
cv.put("Nr telefonu", nr_tel);
cv.put("Email", email);
cv.put("Ulica", ulica);
cv.put("Kod pocztowy", kod);
if (db.insert(database_table, null, cv)==-1){
return false;
} else {
return true;
}
}
}
I have no errors, but when I'm trying to add Record app stopping and I get "SQL has stopped"
I forgot to paste Log! Here u are!
02-19 18:02:43.119 2087-2087/programowanie.android.sql I/art: Not late-enabling -Xcheck:jni (already on)
02-19 18:02:43.195 2087-2087/programowanie.android.sql W/System: ClassLoader referenced unknown path: /data/app/programowanie.android.sql-1/lib/x86
02-19 18:02:43.348 2087-2115/programowanie.android.sql D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-19 18:02:43.410 2087-2115/programowanie.android.sql I/OpenGLRenderer: Initialized EGL, version 1.4
02-19 18:02:43.544 2087-2115/programowanie.android.sql W/EGL_emulation: eglSurfaceAttrib not implemented
02-19 18:02:43.544 2087-2115/programowanie.android.sql W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xabdff300, error=EGL_SUCCESS
02-19 18:03:19.132 2087-2087/programowanie.android.sql E/SQLiteLog: (1) near "tableOsoby": syntax error
02-19 18:03:19.133 2087-2087/programowanie.android.sql D/AndroidRuntime: Shutting down VM
02-19 18:03:19.133 2087-2087/programowanie.android.sql E/AndroidRuntime: FATAL EXCEPTION: main
Process: programowanie.android.sql, PID: 2087
android.database.sqlite.SQLiteException: near "tableOsoby": syntax error (code 1): , while compiling: create tableOsoby(ID INTEGER PRIMARY KEY AUTOINCREMENT, IMIE TEXT, NAZWISKO TEXT, NUMER_TELEFONU TEXT, EMAIL TEXT, ULICA TEXT, KOD_MIASTO TEXT
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at programowanie.android.sql.DatabaseHelper.onCreate(DatabaseHelper.java:21)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at programowanie.android.sql.DatabaseHelper.wstawdane(DatabaseHelper.java:31)
at programowanie.android.sql.MainActivity$1.onClick(MainActivity.java:43)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
change this
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table" + database_table + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, IMIE TEXT, NAZWISKO TEXT, NUMER_TELEFONU TEXT, EMAIL TEXT, ULICA TEXT, KOD_MIASTO TEXT");
}
to this
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + database_table + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, IMIE TEXT, NAZWISKO TEXT, NUMER_TELEFONU TEXT, EMAIL TEXT, ULICA TEXT, KOD_MIASTO TEXT);");
}
you had no spaces between 'table and (ID' so your command would have been
"create tableOsoby(ID INTEGER PRIMARY KEY AUTOINCREMENT, IMIE TEXT, NAZWISKO TEXT, NUMER_TELEFONU TEXT, EMAIL TEXT, ULICA TEXT, KOD_MIASTO TEXT"
which wont run.
Also I noticed you forgot the ) and you have forgotten the ; at the end of the statement.You must remember the ; for security reasons
Given the error log:
android.database.sqlite.SQLiteException: near "tableOsoby": syntax error (code 1): , while compiling: create tableOsoby(ID INTEGER PRIMARY KEY AUTOINCREMENT, IMIE TEXT, NAZWISKO TEXT, NUMER_TELEFONU TEXT, EMAIL TEXT, ULICA TEXT, KOD_MIASTO TEXT
I identified here two issues that probably led the SQLite to crash:
1) On the line db.execSQL("create table" + database_table + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, IMIE TEXT, NAZWISKO TEXT, NUMER_TELEFONU TEXT, EMAIL TEXT, ULICA TEXT, KOD_MIASTO TEXT"); it is missing a space between the "create table" string and the table name variable, resulting in "create tableOsoby". Same occours with the next concatenated string.
2) The closing parenthesis is missing in the string "(ID INTEGER PRIMARY KEY AUTOINCREMENT, IMIE TEXT, NAZWISKO TEXT, NUMER_TELEFONU TEXT, EMAIL TEXT, ULICA TEXT, KOD_MIASTO TEXT".
The corrected line should be:
db.execSQL("create table " + database_table + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, IMIE TEXT, NAZWISKO TEXT, NUMER_TELEFONU TEXT, EMAIL TEXT, ULICA TEXT, KOD_MIASTO TEXT)");