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
Related
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();
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
}
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'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.....).
I am working on a small app which stores the place latitude and longitude in SQLite database. I have three classes as follows:
AddPlaceActyivity.java
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.example.rememberthislocation.R;
public class AddPlaceActivity extends Activity{
Button btn_remember,btn_maps;
Fragment fr;
Button addlocation;
EditText locationname;
String mylocationname,mylatitude,mylongitude;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Log.d("my","In oncreateview");
setContentView(R.layout.remember_fragment);
addlocation = (Button)findViewById(R.id.btn_addlocation);
locationname = (EditText)findViewById(R.id.locationname);
mylocationname = locationname.getText().toString();
Log.d("my","value 1 taken");
mylatitude = "0.0";
mylongitude = "0.0";
Log.d("my", "data values taken");
addlocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MySqliteHelper db = new MySqliteHelper(getApplicationContext());
db.addPlaces(new Place(mylocationname,mylatitude,mylongitude));
}
});
}
}
MySqliteHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySqliteHelper extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contactsManager";
private static final String KEY_ID = "id";
private static final String KEY_PLACENAME = "placename";
private static final String KEY_LATITUDE = "latitude";
private static final String KEY_LONGITUDE = "longitude";
private static final String TABLE_NAME = "places";
public MySqliteHelper(Context context) {
super(context, DATABASE_NAME,null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//actual query = create table places (id primary key autoincrement, placename taxt, latitude real, longitude real);
String query = "CREATE TABLE" +TABLE_NAME + "( " + KEY_ID+
"INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_PLACENAME+
"TEXT, "+KEY_LATITUDE+
"REAL, "+KEY_LONGITUDE+ "REAL)";
try {
db.execSQL(query);
Log.d("my", "Successfully created table: " + query);
} catch (SQLiteException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS places");
this.onCreate(db);
}
public void addPlaces(Place place)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues convalues = new ContentValues();
convalues.put(KEY_PLACENAME,place.getname());
convalues.put(KEY_LATITUDE,place.getlatitude());
convalues.put(KEY_LONGITUDE,place.getlongitude());
db.insert(TABLE_NAME, null, convalues);
Log.d("my","db.insert(TABLE_NAME, null, convalues)");
Log.d("my", "Values inserted");
db.close();
}
}
Place.java
public class Place {
String mname,mlatitude,mlongitude,mstring;
public Place(String name, String latitude, String longitude)
{
mname = name;
mlatitude = latitude;
mlongitude = longitude;
}
public Place() {
// TODO Auto-generated constructor stub
}
public void setname(String placename)
{
mname = placename;
}
public String getname()
{
return mname;
}
public void setlatitude(String latitude)
{
mlatitude=latitude;
}
public String getlatitude()
{
return mlatitude;
}
public void setlongitude(String longitude)
{
mlongitude = longitude;
}
public String getlongitude()
{
return mlongitude;
}
}
And my logcat log:
11-20 17:40:02.770: D/my(10604): In oncreateview
11-20 17:40:02.890: D/my(10604): acivity layout initialized
11-20 17:40:02.950: I/PGA(10604): New SOCKET connection: berthislocation (pid 10604, tid 10604)
11-20 17:40:16.510: D/my(11196): in remember's onclick
11-20 17:40:16.540: D/my(11196): intent started
11-20 17:40:16.560: D/my(11196): In oncreateview
11-20 17:40:16.560: D/my(11196): value 1 taken
11-20 17:40:16.560: D/my(11196): data values taken
11-20 17:40:27.290: I/SqliteDatabaseCpp(11196): sqlite returned: error code = 1, msg = no such table: places, db=/data/data/com.example.rememberthislocation/databases/contactsManager
11-20 17:40:27.290: E/SQLiteDatabase(11196): Error inserting longitude=0.0 latitude=0.0 placename=
11-20 17:40:27.290: E/SQLiteDatabase(11196): android.database.sqlite.SQLiteException: no such table: places: , while compiling: INSERT INTO places(longitude,latitude,placename) VALUES (?,?,?)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteStatement.acquireAndLock(SQLiteStatement.java:260)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:112)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1718)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1591)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at com.example.rememberthisplace.MySqliteHelper.addPlaces(MySqliteHelper.java:74)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at com.example.rememberthisplace.AddPlaceActivity$1.onClick(AddPlaceActivity.java:52)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.view.View.performClick(View.java:3511)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.view.View$PerformClick.run(View.java:14105)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.os.Handler.handleCallback(Handler.java:605)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.os.Handler.dispatchMessage(Handler.java:92)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.os.Looper.loop(Looper.java:137)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at android.app.ActivityThread.main(ActivityThread.java:4424)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at java.lang.reflect.Method.invokeNative(Native Method)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at java.lang.reflect.Method.invoke(Method.java:511)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
11-20 17:40:27.290: E/SQLiteDatabase(11196): at dalvik.system.NativeStart.main(Native Method)
Clearly the error is in MySqliteHelper.java
Error: sqlite returned: error code = 1, msg = no such table: places
So, my MySqliteHelper class's oncreate() isn't called. I tried for hours..but can't find the solution. Can anyone help me?
You have bugs in your onCreate() that are hidden by the catch:
String query = "CREATE TABLE" +TABLE_NAME + "( " + KEY_ID+
"INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_PLACENAME+
"TEXT, "+KEY_LATITUDE+
"REAL, "+KEY_LONGITUDE+ "REAL)";
Missing whitespace, change to:
String query = "CREATE TABLE " +TABLE_NAME + "( " + KEY_ID+
" INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_PLACENAME+
" TEXT, "+KEY_LATITUDE+
" REAL, "+KEY_LONGITUDE+ " REAL)";
Remove the try-catch. If there's a problem, the framework should be thrown an exception. If onCreate() returns normally, the framework thinks the database was set up successfully. onCreate() is only called once when the database is first set up.
Uninstall your app or clear its data to get rid of the old empty database file and to get onCreate() rerun.
Further reading: When is SQLiteOpenHelper onCreate() / onUpgrade() run?