This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 6 years ago.
Where I made mistake?
When I try to insert data into database, I get Toast message that I inserter,but in LOG file i see error:
no such table: reservation (code 1): , while compiling: INSERT INTO reservation(phone,address,surname,name,start,destination) VALUES (?,?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
DBHelper.java
package com.example.demir.carsharing;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.TextView;
public class DbHelper extends SQLiteOpenHelper {
public static final String TAG = DbHelper.class.getSimpleName();
public static final String DB_NAME = "carsharing.db";
public static final int DB_VERSION = 1;
public static final String USER_TABLE = "users";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_PASS = "password";
public static final String RES_TABLE="reservation";
public static final String COLUMN_NAME="name";
public static final String COLUMN_SURNAME="surname";
public static final String COLUMN_ADDRESS="address";
public static final String COLUMN_PHONE="phone";
public static final String COLUMN_START="start";
public static final String COLUMN_DESTINATION="destination";
/*
create table users(
id integer primary key autoincrement,
email text,
password text);
*/
public static final String CREATE_TABLE_USERS = "CREATE TABLE " + USER_TABLE + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_EMAIL + " TEXT,"
+ COLUMN_PASS + " TEXT);";
public static final String CREATE_TABLE_RESERVATION = "CREATE TABLE " + RES_TABLE + "("
+ COLUMN_NAME + " TEXT,"
+ COLUMN_SURNAME + " TEXT,"
+ COLUMN_ADDRESS + " TEXT,"
+ COLUMN_PHONE + " TEXT,"
+ COLUMN_START + " TEXT,"
+ COLUMN_DESTINATION + " TEXT);";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USERS);
db.execSQL(CREATE_TABLE_RESERVATION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST" + USER_TABLE);
onCreate(db);
db.execSQL("DROP TABLE IF EXIST" + RES_TABLE);
onCreate(db);
}
public void addUser(String email, String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_EMAIL, email);
values.put(COLUMN_PASS, password);
long id = db.insert(USER_TABLE, null, values);
db.close();
Log.d(TAG, "user inserted" + id);
}
public boolean getUser(String email, String pass) {
//HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "select * from " + USER_TABLE + " where " +
COLUMN_EMAIL + " = " + "'" + email + "'" + " and " + COLUMN_PASS + " = " + "'" + pass + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
return true;
}
cursor.close();
db.close();
return false;
}
// method for inserting data from method reservation
public void addReservation(String name, String surname, String address, String phone, String start, String destination) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, name);
values.put(COLUMN_SURNAME, surname);
values.put(COLUMN_ADDRESS, address);
values.put(COLUMN_PHONE, phone);
values.put(COLUMN_START, start);
values.put(COLUMN_DESTINATION, destination);
long a = db.insert(RES_TABLE, null, values);
db.close();
Log.e(TAG, "Data insetred" + a);
}
//Get data from Reservation
public boolean getData(String name, String surname, String address, String phone, String start, String destination) {
String query = "select * from " + RES_TABLE + " where " +
COLUMN_NAME + " = " + "'" + name + "'" + " , " + COLUMN_SURNAME + " = " + "'" + surname + "'" +
COLUMN_ADDRESS + " = " + "'" + address + "'" + " , " + COLUMN_PHONE + " = " + "'" + phone + "'" +
COLUMN_START + " = " + "'" + start + "'" + " , " + COLUMN_DESTINATION + " = " + "'" + destination + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
return true;
}
cursor.close();
db.close();
return false;
}
//insert data iinto Reservation
public boolean insertReservation(String name, String surname, String address, String phone, String start, String destination) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name",name);
contentValues.put("surname",surname);
contentValues.put("address",address);
contentValues.put("phone",phone);
contentValues.put("start",start);
contentValues.put("destination",destination);
db.insert("reservation",null,contentValues);
return true;
}
}
Reservation.java
package com.example.demir.carsharing;
import android.content.Intent;
import android.database.SQLException;
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 com.example.demir.carsharing.R.id.etName;
public class ReservationActivity extends AppCompatActivity {
private Button save;
private EditText name, surname, address, phone, start, destination;
private DbHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reservation);
db = new DbHelper(this);
name = (EditText) findViewById(etName);
surname = (EditText) findViewById(R.id.etSurname);
address = (EditText) findViewById(R.id.etAddress);
phone = (EditText) findViewById(R.id.etPhone);
start = (EditText) findViewById(R.id.etStart);
destination = (EditText) findViewById(R.id.etDestination);
save = (Button) findViewById(R.id.btnSave);
AddData();
}
public void AddData(){
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = db.insertReservation(name.getText().toString(),
surname.getText().toString(),
address.getText().toString(),
phone.getText().toString(),
start.getText().toString(),
destination.getText().toString());
if(isInserted==true)
Toast.makeText(ReservationActivity.this,"Data inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(ReservationActivity.this,"Data not inserted",Toast.LENGTH_LONG).show();
}
});
}
}
You might have made changes to your helper class after creating the tables for the first time, in which case you must clear your app's data before you rerun, in your device/emulator go to App Info and the Clear Data "for >= Marshmallow go to App Info -> Storage -> Clear Data"
You don't have to delete and reinstall the whole app. that would be a waste of time.
Related
I want to modify a field of a determinate id, in my case the field is notify_datetime.
But when I run the app and try to do that, the app crashes giving this error.
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.msnma.movienotifier, PID: 4047
android.database.sqlite.SQLiteException: no such column: notify_datetime (Sqlite code 1): , while compiling: UPDATE MovieTypeTable SET notify_datetime=? WHERE notify_datetime = ?, (OS error - 2:No such file or directory)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:910)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:521)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:603)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:63)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.updateWithOnConflict(SQLiteDatabase.java:1856)
at android.database.sqlite.SQLiteDatabase.update(SQLiteDatabase.java:1799)
at com.example.msnma.movienotifier.database.MovieDatabase.updateNotifyDate(MovieDatabase.java:299)
at com.example.msnma.movienotifier.adapter.MoviesAdapter$9.onClick(MoviesAdapter.java:445)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
The method is called updateNotifyDate and should modify notify_datetime.
MovieDatabase.java
package com.example.msnma.movienotifier.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.msnma.movienotifier.MainActivity;
import com.example.msnma.movienotifier.databaseModel.MovieDBModel;
import com.example.msnma.movienotifier.databaseModel.TypeDBModel;
import com.example.msnma.movienotifier.mapper.MovieMapper;
import com.example.msnma.movienotifier.model.Movie;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class MovieDatabase extends SQLiteOpenHelper {
private static final String LOG = "DatabaseHelper";
private static final String DATABASE_NAME = "movieDatabase";
private static final int DATABASE_VERSION = 1;
//Table Names
private static final String TABLE_MOVIE = "MovieTable";
private static final String TABLE_TYPE = "TypeTable";
private static final String TABLE_MOVIE_TYPE = "MovieTypeTable";
//Table Fields
private static final String MOVIE_ID ="movie_id";
public static final String TITLE ="title";
private static final String OVERVIEW = "overview";
private static final String POSTER_URL = "posterUrl";
private static final String BACKDROP_URL = "backdropUrl";
private static final String TRAILER_URL = "trailerUrl";
private static final String RELEASE_DATE = "releaseDate";
private static final String RATING = "rating";
private static final String ADULT = "adult";
private static final String TYPE_ID = "type_id";
private static final String TYPE_DESCR = "type_descr";
private static final String MOVIE_TYPE_ID = "movie_type_id";
private static final String M_ID = "movie_id";
private static final String T_ID = "type_id";
private static final String notify_datetime = "notify_datetime";
// Table Create Statements
private static final String CREATE_TABLE_MOVIE = "CREATE TABLE "
+ TABLE_MOVIE + "(" + MOVIE_ID + " INTEGER PRIMARY KEY," + TITLE + " TEXT,"
+ OVERVIEW + " TEXT," + POSTER_URL + " TEXT," + BACKDROP_URL + " TEXT," + TRAILER_URL + " TEXT,"
+ RATING + " REAL," + ADULT + " INTEGER," + RELEASE_DATE + " DATETIME," + notify_datetime + " DATETIME" + ")";
// Tag table create statement
private static final String CREATE_TABLE_TYPE = "CREATE TABLE " + TABLE_TYPE
+ "(" + TYPE_ID + " INTEGER PRIMARY KEY," + TYPE_DESCR + " TEXT" + ")";
// todo_tag table create statement
private static final String CREATE_TABLE_MOVIE_TYPE = "CREATE TABLE "
+ TABLE_MOVIE_TYPE + "(" + MOVIE_TYPE_ID + " INTEGER PRIMARY KEY,"
+ M_ID + " INTEGER," + T_ID + " INTEGER" + ")";
static SQLiteDatabase database;
public MovieDatabase(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
database = getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating required tables
db.execSQL(CREATE_TABLE_MOVIE);
db.execSQL(CREATE_TABLE_TYPE);
db.execSQL(CREATE_TABLE_MOVIE_TYPE);
insertType(db); //NOTA: questo va chiamato solo la prima volta che instanziamo il DB, AGGIUNGERE CONTROLLO!
//in teoria onCreate verrà chiamato solo la prima volta...
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MOVIE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TYPE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MOVIE_TYPE);
// create new tables
onCreate(db);
}
//questa funzione serve solo per inserire casualmente dai suggested movies, alcuni notify e watched movies
public static void saveMoviesOnDB(List<Movie> movies, String type){
MovieDatabase db = MainActivity.getMovieDatabase();
MovieMapper mapper = new MovieMapper();
List<MovieDBModel> moviesDB = mapper.toMovieDBModelList(movies);
Integer typeId = 0;
int index = 0;
if(type.equals("notify")){
typeId = 1;
}else if(type.equals("watched")){
typeId = 2;
index = index+5;
}else{
//todo catch invalid type Id exception
}
for(int a = index; a<index+5; a++){
insertMovie(moviesDB.get(a), typeId, db);
}
}
//open the database, maybe not useful...
public MovieDatabase open() throws SQLException
{
database = getWritableDatabase();
return this;
}
// closing database
public void closeDB() {
SQLiteDatabase db = this.getReadableDatabase();
if (db != null && db.isOpen())
db.close();
}
//CRUDs
public static void insertMovie(MovieDBModel movie, Integer typeId, MovieDatabase db) {
SQLiteDatabase database = db.getWritableDatabase();
if(checkMovieUniqueness(movie.getTitle(), db)) { //NON VOGLIO INSERIRE PIù VOLTE LO STESSO FILM
ContentValues values = new ContentValues();
values.put(TITLE, movie.getTitle());
values.put(OVERVIEW, movie.getOverview());
values.put(POSTER_URL, movie.getPosterUrl());
values.put(BACKDROP_URL, movie.getBackdropUrl());
values.put(TRAILER_URL, movie.getTrailerUrl());
values.put(RELEASE_DATE, movie.getReleaseDate().toString());
values.put(RATING, movie.getRating());
values.put(ADULT, movie.isAdult());
//inizio nuovo codice
if(typeId == 1) {
values.put(notify_datetime, movie.getNotifyDate().toString());
Log.i("TYPEID", "Siamo dentro");
}
//else values.putNull(NOTIFY_TIME_DATE);
//fine nuovo codice
// insert row
long movieId = database.insert(TABLE_MOVIE, null, values);
insertMovieType(movieId, typeId, db);
}
}
public static void insertMovieType(Long movieId, Integer typeId, MovieDatabase db){
SQLiteDatabase database = db.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(M_ID, movieId.intValue());
values.put(T_ID, typeId);
database.insert(TABLE_MOVIE_TYPE, null, values);
}
private void insertType(SQLiteDatabase db){
ContentValues descr1 = new ContentValues();
descr1.put(TYPE_DESCR, "NOTIFY");
ContentValues descr2 = new ContentValues();
descr2.put(TYPE_DESCR, "WATCHED");
// insert row
db.insert(TABLE_TYPE, null, descr1);
db.insert(TABLE_TYPE, null, descr2);
}
private TypeDBModel getTypeByTypeDescr(String typeDescr) {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_TYPE + " WHERE "
+ TYPE_DESCR + " = " + typeDescr;
Log.e(LOG, selectQuery);
Cursor c = db.rawQuery(selectQuery, null);
if (c != null)
c.moveToFirst();
TypeDBModel td = new TypeDBModel();
td.setId(c.getInt(c.getColumnIndex(TYPE_ID)));
td.setDescription((c.getString(c.getColumnIndex(TYPE_DESCR))));
return td;
}
private static boolean checkMovieUniqueness(String movieTitle, MovieDatabase db) {
SQLiteDatabase database = db.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_MOVIE + " WHERE "
+ TITLE + " = " + "'"+ movieTitle + "'";
Log.e(LOG, selectQuery);
Cursor c = database.rawQuery(selectQuery, null);
if(c.moveToFirst()){
c.close();
return false;
}else{
c.close();
return true;
}
}
public List<MovieDBModel> getAllMovieByType(String typeDescr) throws ParseException {
List<MovieDBModel> movies = new ArrayList<MovieDBModel>();
String selectQuery = "SELECT * FROM " + TABLE_MOVIE + " mv, "
+ TABLE_TYPE + " type, " + TABLE_MOVIE_TYPE + " tmt WHERE type."
+ TYPE_DESCR + " = '" + typeDescr + "'" + " AND type." + TYPE_ID
+ " = " + "tmt." + T_ID + " AND mv." + MOVIE_ID + " = "
+ "tmt." + M_ID;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
MovieDBModel td = new MovieDBModel();
td.setId(c.getInt((c.getColumnIndex(MOVIE_ID))));
td.setTitle((c.getString(c.getColumnIndex(TITLE))));
td.setOverview(c.getString(c.getColumnIndex(OVERVIEW)));
td.setPosterUrl(c.getString((c.getColumnIndex(POSTER_URL))));
td.setBackdropUrl((c.getString(c.getColumnIndex(BACKDROP_URL))));
td.setTrailerUrl(c.getString(c.getColumnIndex(TRAILER_URL)));
String dateString =c.getString((c.getColumnIndex(RELEASE_DATE)));
Date date = sdf3.parse(dateString);
td.setReleaseDate(date);
td.setRating((c.getFloat(c.getColumnIndex(RATING))));
int adult = c.getInt(c.getColumnIndex(ADULT));
if(adult == 0){
td.setAdult(true); //NOT sure if is the contrary
}else{
td.setAdult(false);
}
//nuovo codice
String datenotifyString = c.getString(c.getColumnIndex(notify_datetime));
if(datenotifyString != null)
{
Date datenotify = sdf3.parse(datenotifyString);
td.setNotifyDate(datenotify);
}
//fine nuovo codice
movies.add(td);
} while (c.moveToNext());
}
return movies;
}
public void deleteMovie(long tado_id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_MOVIE, MOVIE_ID + " = ?",
new String[] { String.valueOf(tado_id) });
}
public void deleteMovieType(long tado_id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_MOVIE_TYPE, M_ID + " = ?",
new String[] { String.valueOf(tado_id) });
}
public int updateMovieType(long id, long tag_id) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(T_ID, tag_id);
// updating row
return db.update(TABLE_MOVIE_TYPE, values, M_ID + " = ?",
new String[] { String.valueOf(id) });
}
//da sistemare.
public int updateNotifyDate(long id, Date datetime ) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(notify_datetime,datetime.toString());
// updating row
return db.update(TABLE_MOVIE_TYPE, values, notify_datetime + " = ?",
new String[] { String.valueOf(id) });
}
public boolean isEmpty() throws ParseException {
boolean isEmpty = false;
List<MovieDBModel> movie1 = getAllMovieByType("NOTIFY");
List<MovieDBModel> movie2 = getAllMovieByType("WATCHED");
if(movie1.isEmpty() && movie2.isEmpty()){
isEmpty = true;
}
return isEmpty;
}
public static List<MovieDBModel> getAllMovies() throws ParseException {
List<MovieDBModel> movies = new ArrayList<MovieDBModel>();
String selectQuery = "SELECT * FROM " + TABLE_MOVIE;
Log.e(LOG, selectQuery);
SQLiteDatabase db = database;
Cursor c = db.rawQuery(selectQuery, null);
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
MovieDBModel td = new MovieDBModel();
td.setId(c.getInt((c.getColumnIndex(MOVIE_ID))));
td.setTitle((c.getString(c.getColumnIndex(TITLE))));
td.setOverview(c.getString(c.getColumnIndex(OVERVIEW)));
td.setPosterUrl(c.getString((c.getColumnIndex(POSTER_URL))));
td.setBackdropUrl((c.getString(c.getColumnIndex(BACKDROP_URL))));
td.setTrailerUrl(c.getString(c.getColumnIndex(TRAILER_URL)));
String dateString =c.getString((c.getColumnIndex(RELEASE_DATE)));
Date date = sdf3.parse(dateString);
td.setReleaseDate(date);
td.setRating((c.getFloat(c.getColumnIndex(RATING))));
int adult = c.getInt(c.getColumnIndex(ADULT));
if(adult == 0){
td.setAdult(true); //NOT sure if is the contrary
}else{
td.setAdult(false);
}
movies.add(td);
} while (c.moveToNext());
}
return movies;
}
}
In MoviesAdapter.java only piece that call updateNotifyDate:
MovieDatabase md = new MovieDatabase(context);
Log.i("IDMOVIE","ID:"+movies.get(position).getId());
md.updateNotifyDate(movies.get(position).getId(),datatime);
}
Why it doesn't work? What am I wrong?
You're attempting to update MovieTypeTable but your image suggests the notify_datetime is in MovieTable so it's throwing SQLiteException: no such column.
I have created 2 tables in a db. 1 is working fine. TABLE_NAME2 is giving error while inserting data in it saying Column Email is not found.
DatabaseHelper.java:
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME2 + "("
+ USER_NAME + "TEXT,"
+ USER_EMAIL + "TEXT,"
+ USER_MOBILE + "TEXT, "
+ USER_PASS + "TEXT)");
db.execSQL("CREATE Table " + TABLE_NAME1 + "("// + COL1 + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COL2 + " TEXT,"
+ COL3 + " TEXT,"
+ COL4 + " TEXT,"
+ COL5 + " TEXT,"
+ COL6 + " TEXT,"
+ COL7 + " TEXT)");
}
public boolean insertSignupDataDB(String name, String email, String mobile, String pass){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(USER_NAME, name);
contentValues.put(USER_EMAIL, email);
contentValues.put(USER_MOBILE, mobile);
contentValues.put(USER_PASS, pass);
long result = db.insert(TABLE_NAME2, null, contentValues);
if (result==-1){
return false;
}
else
return true;
}
Log:
(1) table signup has no column named EMAIL
06-08 21:00:51.306 15019-15019/com.mgm.manish.trekcompanion E/SQLiteDatabase: Error inserting EMAIL=abc NAME=abc PASSWORD=abc MOBILE=abc
android.database.sqlite.SQLiteException: table signup has no column named EMAIL (code 1): , while compiling: INSERT INTO signup(EMAIL,NAME,PASSWORD,MOBILE) VALUES (?,?,?,?)
Please solve this
From this page I am sending data to DatabaseHelper Class to insert data.
It shows the toast "successful signup", but is showing error in Logs, and also it is not navigating to LoginActivity class. it is navigating to MainActivity.
Even else part is not working. when i put different passwords it gives error app stopped.
if(etSignPass.getText().toString().equals(etSignConPass.getText().toString())){
boolean queryResult = dbHelper.insertSignupDataDB(etSignName.getText().toString(),
etSignEmail.getText().toString(), etSignMobile.getText().toString(), etSignPass.getText().toString());
if(queryResult=true){
Toast.makeText(SignUp.this, "Successfully Signed up", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
navigateUpTo(new Intent(SignUp.this,LoginActivity.class));
}
}
else{
Toast.makeText(SignUp.this, "Error", Toast.LENGTH_SHORT).show();
}
}
else{
etSignConPass.setBackgroundColor(Color.RED);
onClicSignUp();
}
}
This is complete code of DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "abc.db";
public static final String TABLE_NAME1 = "table1";
public static final String COL2 = "col1";
public static final String COL3 = "Date";
public static final String COL4 = "Cost";
public static final String COL5 = "loc1";
public static final String COL6 = "loc2";
public static final String COL7 = "Description";
public static final String TABLE_NAME2 = "signup";
public static final String USER_NAME = "NAME";
public static final String USER_EMAIL = "EMAIL";
public static final String USER_MOBILE = "MOBILE";
public static final String USER_PASS = "PASSWORD";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME2 + "("
+ USER_NAME + "TEXT,"
+ USER_EMAIL + "TEXT,"
+ USER_MOBILE + "TEXT, "
+ USER_PASS + "TEXT)");
db.execSQL("CREATE Table " + TABLE_NAME1 + "("// + COL1 + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COL2 + " TEXT,"
+ COL3 + " TEXT,"
+ COL4 + " TEXT,"
+ COL5 + " TEXT,"
+ COL6 + " TEXT,"
+ COL7 + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME1);
db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME2);
onCreate(db);
}
public boolean insertHomeDataDB(String locName, String date, String cost, String startLoc, String endLoc, String description){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, locName);
contentValues.put(COL3, date);
contentValues.put(COL4, cost);
contentValues.put(COL5, startLoc);
contentValues.put(COL6, endLoc);
contentValues.put(COL7, description);
//contentValues.put(COL8, userId);
long result = db.insert(TABLE_NAME1, null, contentValues);
if (result==-1){
return false;
}
else
return true;
}
public boolean insertSignupDataDB(String name, String email, String mobile, String pass){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(USER_NAME, name);
contentValues.put(USER_EMAIL, email);
contentValues.put(USER_MOBILE, mobile);
contentValues.put(USER_PASS, pass);
long result = db.insert(TABLE_NAME2, null, contentValues);
if (result==-1){
return false;
}
else
return true;
}
public Cursor getAllHomeData(SQLiteDatabase db){
Cursor res;
String[] projection = {COL2,COL3,COL4};
res = db.query(TABLE_NAME1,projection,null,null,null,null,null);
return res;
}
public Cursor getAllProfileData(SQLiteDatabase db){
Cursor res;
String[] projection={USER_NAME,USER_EMAIL,USER_MOBILE,USER_PASS};
res = db.query(TABLE_NAME2, projection,null,null,null,null,null);
return res;
}
}
Hi i am trying to make give connection with SQLlite database. Code is looking fine but database table is not created.App is running well but database is not created. Any suggestions?? My codes:
DatabaseManager.java
package com.step2rock.www.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
import com.step2rock.www.model.User;
/**
* Created by Sushimz on 5/15/2016.
*/
public class DatabaseManager extends SQLiteOpenHelper {
Context context;
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "photography";
// Users table name
private static final String TABLE_USERS = "users";
//blog table name
private static final String TABLE_BLOG = "blog";
// Users Table Columns names
private static final String KEY_USER_ID = "id";
private static final String KEY_USER_first_NAME = "f_name";
private static final String KEY_USER_last_NAME = "l_name";
private static final String KEY_USER_PASS = "password";
private static final String KEY_USER_PIC = "profilepic";
private static final String KEY_USER_Address = "address";
private static final String KEY_USER_Exp = "exp_level";
private static final String KEY_USER_link = "link";
private static final String KEY_USER_TYPE = "type";
// Blog Table Columns names
private static final String KEY_Blog_ID = "id";
private static final String KEY_Blog_Title = "blog_tilte";
private static final String KEY_Blog_Desc = "blog_desc";
private static final String KEY_Blog_Image = "blog_image";
private static final String KEY_Blog_Link = "blog_link";
public DatabaseManager(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d("users",TABLE_USERS);
Log.d("blog",TABLE_BLOG);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_USERS_TABLE = "CREATE TABLE " + TABLE_USERS
+ "("
+ KEY_USER_ID + " INTEGER PRIMARY KEY,"
+ KEY_USER_first_NAME + " TEXT,"
+ KEY_USER_last_NAME + " TEXT,"
+ KEY_USER_PASS + " TEXT,"
+ KEY_USER_PIC + " TEXT,"
+ KEY_USER_Address + " TEXT,"
+ KEY_USER_Exp + " TEXT,"
+ KEY_USER_link + " TEXT,"
+ KEY_USER_TYPE + " TEXT,"
+ ")";
db.execSQL(CREATE_USERS_TABLE);
String CREATE_BLOG_TABLE = "CREATE TABLE " + TABLE_BLOG
+ "("
+ KEY_Blog_ID + " INTEGER PRIMARY KEY,"
+ KEY_Blog_Title + " TEXT,"
+ KEY_Blog_Desc + " TEXT,"
+ KEY_Blog_Image + " TEXT,"
+ KEY_Blog_Link + " TEXT ,"
+ " FOREIGN KEY(" + KEY_USER_ID + ") REFERENCES Users(id) ON DELETE CASCADE "
+ ")";
db.execSQL(CREATE_BLOG_TABLE);
Toast.makeText(this.context, "AAA", Toast.LENGTH_SHORT).show();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BLOG);
// Create tables again
onCreate(db);
}
public void resetDB() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BLOG);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new USER
public int addUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_USER_ID, user.get_user_id());
values.put(KEY_USER_first_NAME, user.get_first_name());
values.put(KEY_USER_last_NAME, user.get_last_name());
values.put(KEY_USER_PASS, user.get_user_pass());
values.put(KEY_USER_PIC, user.get_user_pic());
values.put(KEY_USER_Address, user.get_user_address());
values.put(KEY_USER_Exp, user.get_user_exp());
values.put(KEY_USER_link, user.get_user_link());
values.put(KEY_USER_TYPE, user.get_user_type());
// Inserting Row
int last_id = (int) db.insert(TABLE_USERS, null, values);
db.close(); // Closing database connection
return last_id;
}
// Updating single User
public int updateUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_USER_ID, user.get_user_id());
values.put(KEY_USER_first_NAME, user.get_first_name());
values.put(KEY_USER_last_NAME, user.get_last_name());
values.put(KEY_USER_PASS, user.get_user_pass());
values.put(KEY_USER_PIC, user.get_user_pic());
values.put(KEY_USER_Address, user.get_user_address());
values.put(KEY_USER_Exp, user.get_user_exp());
values.put(KEY_USER_link, user.get_user_link());
values.put(KEY_USER_TYPE, user.get_user_type());
// updating row
return db.update(TABLE_USERS, values, KEY_USER_ID + " = ?",
new String[]{String.valueOf(user.get_user_id())});
}
}
RegistrationActivity.java
package com.step2rock.www.crudproject;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.step2rock.www.database.DatabaseManager;
/**
* Created by Sushimz on 5/15/2016.
*/
public class RegistrationActivity extends AppCompatActivity {
Button btnSaveRecord;
DatabaseManager databaseManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration_activity);
btnSaveRecord = (Button) findViewById(R.id.btnSaveRecord);
databaseManager = new DatabaseManager(RegistrationActivity.this);
btnSaveRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast toast = Toast.makeText(RegistrationActivity.this,"welcome",Toast.LENGTH_SHORT);
toast.show();
}
});
}
}
The SQLiteOpenHelper you have there looks quite good.
Confusingly onCreate(...) is never called because it does not have the same behavior as an Activity.onCreate(...).
From the documentation:
Called when the database is created for the first time. This is where the creation of tables and the initial population of the tables should happen.
As far as I understand your code, the database is never created (unless you did it elsewhere). To create it you need to try to execute something on the database. For example, try to add a User on your button click. This will call getWriteableDdatabase() and should invoke onCreate(...):
btnSaveRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int id = databaseManager.addUser(new User(...));
Toast toast = Toast.makeText(RegistrationActivity.this,"Welcome User #" + id,Toast.LENGTH_SHORT);
toast.show();
}
});
Check if this calls your onCreate(...) method.
I'd also suggest you to add IF NOT EXISTS to your createTable Strings like so:"CREATE TABLE IF NOT EXISTS " + TABLE_USERS. This way, if you ever add a table, the others will not throw an error or be overwritten when the new table is created.
I have encountered a problem while I was developing my Android application. I am trying to retrieve all the data from my Android application, but I don't exactly know how. Here is my DBAdapter.java class:
package com.example.foodsaver2;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.AvoidXfermode;
import android.util.Log;
import com.example.*;
public class DBAdapter {
public static final String KEY_ROWID = "rowid";
public static final String KEY_CUSTOMER = "customer";
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_ADDRESS1 = "address1";
public static final String KEY_ADDRESS2 = "address2";
public static final String KEY_CITY = "city";
public static final String KEY_STATE = "state";
public static final String KEY_ZIP = "zipCode";
public static final String KEY_SEARCH = "searchData";
public static final String TOTAL_CARB = "carb";
public static final String FIBER = "fiber";
public static final String SUGAR = "sugar";
public static final String PROTEIN = "protein";
public static final String SODIUM = "salt";
public static final String TOTALCALORIES = "calories";
public static Context contextOfApplication;
private static final String TAG = "DBAdapter";
private DatabaseHelper mDbHelper;
public SQLiteDatabase mDb;
private static final String DATABASE_NAME = "Data";
private static final String FTS_VIRTUAL_TABLE = "Info";
private static final int DATABASE_VERSION = 7;
private static final String DATABASE_CREATE1 =
"CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE + " USING fts3(" +
KEY_CUSTOMER + /*"INTEGER," + */ "," +
KEY_NAME + "," +
KEY_ADDRESS1 + "," +
KEY_ADDRESS2 + "," +
KEY_CITY + "," +
KEY_STATE + "," +
KEY_ZIP + "," +
KEY_SEARCH + "," +
TOTAL_CARB + "," +
FIBER + "," +
SUGAR + "," +
PROTEIN + "," +
SODIUM + "," +
TOTALCALORIES + "," +
" UNIQUE (" + KEY_CUSTOMER + "));";
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE1);
db.execSQL(DATABASE_CREATE1);
}
public static Context getContextOfApplication(){
return contextOfApplication;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
onCreate(db);
}
}
public DBAdapter(Context ctx) {
this.mCtx = ctx;
}
public DBAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createCustomer(String customer, String name, String address1, String address2, String city, String state, String zipCode, String carb, String fiber, String sugar, String protein, String sodium, String calories) {
ContentValues initialValues = new ContentValues();
String searchValue = customer + " " +
name + " " +
address1 + " " +
city + " " +
state + " " +
zipCode;
initialValues.put(KEY_CUSTOMER, customer);
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_ADDRESS1, address1);
initialValues.put(KEY_ADDRESS2, address2);
initialValues.put(KEY_CITY, city);
initialValues.put(KEY_STATE, state);
initialValues.put(KEY_ZIP, zipCode);
initialValues.put(KEY_SEARCH, searchValue);
initialValues.put(TOTAL_CARB, carb);
initialValues.put(FIBER, fiber);
initialValues.put(SUGAR, sugar);
initialValues.put(PROTEIN, protein);
initialValues.put(SODIUM, sodium);
initialValues.put(TOTALCALORIES, calories);
return mDb.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}
public Cursor searchCustomer(String inputText) throws SQLException {
Log.w(TAG, inputText);
String query = "SELECT docid as _id," +
KEY_CUSTOMER + "," +
KEY_NAME + "," +
"(" + KEY_ADDRESS1 + "||" +
"(case when " + KEY_ADDRESS2 + "> '' then '\n' || " + KEY_ADDRESS2 + " else '' end)) as " + KEY_ADDRESS +"," +
KEY_ADDRESS1 + "," +
KEY_ADDRESS2 + "," +
KEY_CITY + "," +
KEY_STATE + "," +
KEY_ZIP + "," +
TOTAL_CARB + "," +
FIBER + "," +
SUGAR + "," +
PROTEIN + "," +
SODIUM + "," +
TOTALCALORIES +
" from " + FTS_VIRTUAL_TABLE +
" where " + KEY_SEARCH + " MATCH '" + inputText + "';";
Log.w(TAG, query);
Cursor mCursor = mDb.rawQuery(query,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean deleteAllCustomers() {
int doneDelete = 0;
doneDelete = mDb.delete(FTS_VIRTUAL_TABLE, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
}
Here is my SendFeedback.java class, where I try to retrieve the data.
package com.example.foodsaver2;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
/**
* Created by mother on 2/7/14.
*/
public class SendFeedback extends Activity {
private DBAdapter mDbHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_feedback);
mDbHelper = new DBAdapter(this);
mDbHelper.open();
}
public void send (View v) {
Cursor c = mDbHelper.getData();
GmailSender sender = new GmailSender("omitted for privacy", "omitted for privacy");
try {
sender.sendMail("This is Subject",
"This is Body",
"omitted for privacy",
"omitted for privacy");
Toast.makeText(getApplicationContext(), "Sent!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Cannot send message!", Toast.LENGTH_SHORT).show();
}
}
}
I don't know how to do this. I have searched the internet and SO for a while, but I can't find a solution. I don't have any experience with SQLiteDatabases either. Any help regarding this problem is appreciated.
This is a good tutorial on sqlite databases on android:
http://www.vogella.com/tutorials/AndroidSQLite/article.html
take a look a this extract:
public List<Comment> getAllComments() {
List<Comment> comments = new ArrayList<Comment>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS, allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Comment comment = cursorToComment(cursor);
comments.add(comment);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return comments;
}
And
private Comment cursorToComment(Cursor cursor) {
Comment comment = new Comment();
comment.setId(cursor.getLong(0));
comment.setComment(cursor.getString(1));
return comment;
}
so for your app you could have:
public List getAllComments() {
List customers = new ArrayList();
Cursor cursor = database.query(FTS_VIRTUAL_TABLE, new String[]{"KEY_CUSTOMER", "KEY_NAME " , etc..}, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Customer customer = cursorToCustomer(cursor);
customers.add(comment);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return customers;
}
And
private Customer cursorToCustomer(Cursor cursor) {
Customer customer = new Customer();
customer.setCustomer(cursor.getString(0));
customer.setName(cursor.getString(1));
customer.setAddress1(cursor.getString(2));
customer.setAddress2(cursor.getString(3));
customer.setCity(cursor.getString(4));
customer.setState(cursor.getString(5));
customer.setZipCode(cursor.getString(6));
customer.setSearchValue(cursor.getString(7));
customer.setCarb(cursor.getString(8));
customer.setFiber(cursor.getString(9));
customer.setSugar(cursor.getString(10));
customer.setProtein(cursor.getString(11));
customer.setSodium(cursor.getString(12));
customer.setCalories(cursor.getString(13));
return comment;
}
PS: You need to create your own class "Customer" to hold the data shown here
I am trying to insert rows into my database, but nothing gets persisted. Here is my helper class:
package com.android.cancertrials;
import java.util.Calendar;
import java.util.GregorianCalendar;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHelper extends SQLiteOpenHelper{
public DataBaseHelper(Context context, String name) {
super(context, name, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
System.out.println("the database in onCreate: "+db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
#Override
public void onOpen(SQLiteDatabase db) {
System.out.println("the database: "+db);
this.db=db;
super.onOpen(db);
}
public void insertRecordBean(RecordBean recordbean){
ContentValues content=new ContentValues();
content.put("TrialPhase", AdvanceSearchTab2.phaseOptions.toString());
content.put("TrialStatus", AdvanceSearchTab2.typeOptions.toString());
content.put("StudyType", AdvanceSearchTab2.statusOptions.toString());
content.put("ContactType", AdvanceSearchTab2.contactSpinner.toString());
content.put("MileRange", AdvanceSearchTab2.rangeSpinner.toString());
content.put("Location", AdvanceSearchTab2.locationSpinner.toString());
db.insert("tblClinicalTrial", null, content);
}
/*public void insertRecordResult(RecordBean recordbean){
ContentValues content1=new ContentValues();
content1.put("NCTID", recordbean.getNctId());
content1.put("Title", recordbean.getTitle());
content1.put("TrialPhase", recordbean.getTrialPhase());
content1.put("TrialStaus", recordbean.getTrialStatus());
content1.put("Summary", recordbean.getSummary());
content1.put("Conditions", recordbean.getConditions());
content1.put("Interventions", recordbean.getIntervention());
content1.put("Description", recordbean.getDescription());
content1.put("SponserName", recordbean.getSponsor());
content1.put("Inclusion", recordbean.getInclusionCriteria());
content1.put("Exclusion", recordbean.getExclusionCriteria());
content1.put("StudyPop", recordbean.getStudyPop());
content1.put("MinAge", recordbean.getMinimumAge());
content1.put("MaxAge", recordbean.getMaximumAge());
content1.put("Gender", recordbean.getGender());
content1.put("Hvolunteer", recordbean.getHealthyVolunteers());
content1.put("EnrollmentType", recordbean.getEnrollment());
content1.put("EnrollmentNum", recordbean.getEnrollment());
content1.put("VerifiedOn", recordbean.getVerifiedOn());
db.insert("tblResultItem", null, content1);
}*/
public void insertRecordBookmark(RecordBean recordbean){
ContentValues content2=new ContentValues();
content2.put("NCTID", recordbean.getNctId());
content2.put("Title", recordbean.getTitle());
content2.put("TrialPhase", recordbean.getTrialPhase());
content2.put("TrialStatus", recordbean.getTrialStatus());
content2.put("Summary", recordbean.getSummary());
content2.put("Conditions", recordbean.getConditions());
content2.put("Interventions", recordbean.getIntervention());
content2.put("Description", recordbean.getDescription());
content2.put("SponserName", recordbean.getSponsor());
content2.put("Inclusion", recordbean.getInclusionCriteria());
content2.put("Exclusion", recordbean.getExclusionCriteria());
content2.put("StudyPop", recordbean.getStudyPop());
content2.put("MinAge", recordbean.getMinimumAge());
content2.put("MaxAge", recordbean.getMaximumAge());
content2.put("Gender", recordbean.getGender());
content2.put("Hvolunteer", recordbean.getHealthyVolunteers());
content2.put("EnrollmentType", recordbean.getEnrollment());
content2.put("EnrollmentNum", recordbean.getEnrollment());
content2.put("VerifiedOn", recordbean.getVerifiedOn());
content2.put("UpdatedOn", recordbean.getUpdatedOn());
content2.put("LocationName", recordbean.getLocationName());
content2.put("LocationStatus", recordbean.getLocationStatus());
content2.put("City", recordbean.getCity());
content2.put("State", recordbean.getState());
content2.put("Country", recordbean.getCountry());
content2.put("Distance", recordbean.getLocationDist());
content2.put("Long", recordbean.getLongitude());
content2.put("lat", recordbean.getLatitude());
content2.put("Url", recordbean.getSourceUrl());
content2.put("Location_id", recordbean.getLocationId());
content2.put("Zip_code", recordbean.getZip());
db.insert("tblBookMarkItem", null, content2);
}
public Cursor getBookMarks(){
String[] columns={"_id","Title","Gender","TrialPhase","Zip_code","Location_id","NCTID"};
return db.query("tblBookMarkItem", columns, null, null, null, null, null);
}
public Cursor getRecent(){
String[] columns={"SearchString","ProfileDate","_id","years","Gender","TrialPhase","StudyType","TrialStatus","ContactType","MileRange","LocationZip","UrlParameter"};
return db.query("tblProfile", columns, null, null, null, null, null);
}
public void insertRecordProfile(String search,String url){
ContentValues content4=new ContentValues();
GregorianCalendar c=new GregorianCalendar();
content4.put("ProfileDate",c.get(GregorianCalendar.DATE)+"/"+(c.get(GregorianCalendar.MONTH)+1)+"/"+ c.get(GregorianCalendar.YEAR));
// content4.put("years", age);
//content3.put("ProfileType", AdvanceSearchTab2.typeOptions.toString());
//content4.put("months", AdvanceSearchTab1.ageEdit.getText().toString());
content4.put("SearchString", search);
// content4.put("Gender", gender);
// content4.put("TrialPhase", phase);
// content4.put("StudyType", study);
// content4.put("TrialStatus", status);
// content4.put("ContactType", contact);
// content4.put("MileRange", mile);
// content4.put("LocationZip", zip);
// //content4.put("searchString", AdvanceSearchTab1.edit_se.toString());
content4.put("UrlParameter", url);
db.insert("tblProfile", null, content4);
}
public void insertRecordMedical(RecordBean recordbean){
ContentValues content3=new ContentValues();
content3.put("years", AdvanceSearchTab1.ageEdit.toString());
content3.put("months", AdvanceSearchTab1.ageEdit.toString());
content3.put("searchString", AdvanceSearchTab1.edit_se.toString());
content3.put("Gender", AdvanceSearchTab1.hubSpinner.toString());
db.insert("tblMedicalProfile", null, content3);
}
public void deleteRecord(int id){
//_id=1;
db.delete("tblBookMarkItem", "_id="+id, null);
}
public void deleteRecent(int id){
//_id=1;
db.delete("tblProfile", "_id="+id, null);
}
private SQLiteDatabase db;
}
When I display it in my ListAdapter, it appears fine. As soon as I kill my application. My changes are not persisted. Why is this?
Where do you make your database? Also, you should be referencing aspects of your database with defined constants.
I don't see in your post where it is that you create your database. For example, in an app I have (link to the full file: http://code.devminded.com/score-it/src/56ac2292cfa3/src/com/devminded/scoreit/ScoreDbAdapter.java ) you can see my database class as such:
public class ScoreDbAdapter {
public static final String TAG = "com.devminded.scoreit.ScoreDbAdapter";
/**
* Keys for the player table. ID is incrementing value to
* reference the players.
*/
public static final String KEY_PLAYERS_ID = "_id";
public static final String KEY_PLAYERS_NAME = "name";
public static final String KEY_PLAYERS_ICON = "icon";
public static final String KEY_PLAYERS_SCORE = "score";
public static final String KEY_PLAYERS_ORDER = "turn";
/**
* Keys for the History table. Sequence is an increase value. Their order
* is the order the transactions were made.
*/
public static final String KEY_HISTORY_ID = "_id";
public static final String KEY_HISTORY_PLAYER = "player";
public static final String KEY_HISTORY_VALUE = "value";
public static final String KEY_HISTORY_NOTE = "note";
public static final String DATABASE_NAME = "scoreitdb";
public static final String TABLE_PLAYERS = "players";
public static final String TABLE_HISTORY = "history";
public static final String TRIGGER_UPDATE_NEW_SCORE = "update_new_score";
public static final String TRIGGER_UPDATE_SCORE = "update_score";
public static final String TRIGGER_DELETE_SCORE = "delete_score";
public static final String TRIGGER_DELETE_HISTORY = "delete_history";
public static final int DATABASE_VERSION = 25;
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private final Context mCtx;
private int mNumPlayers;
private static final String CREATE_TABLE_PLAYERS =
"create table " + TABLE_PLAYERS + " (" + KEY_PLAYERS_ID + " integer primary key autoincrement, "
+ KEY_PLAYERS_NAME + " text not null, " + KEY_PLAYERS_ICON + " long not null, " + KEY_PLAYERS_SCORE + " long not null, "
+ KEY_PLAYERS_ORDER + " long not null);";
private static final String CREATE_TABLE_HISTORY =
"create table " + TABLE_HISTORY + " (" + KEY_HISTORY_ID + " integer primary key autoincrement, "
+ KEY_HISTORY_PLAYER + " integer not null, " + KEY_HISTORY_NOTE + " text not null, "
+ KEY_HISTORY_VALUE + " integer not null);";
private static final String CREATE_TRIGGER_NEW_SCORE =
"create trigger " + TRIGGER_UPDATE_NEW_SCORE + " after insert on " + TABLE_HISTORY
+ " begin"
+ " update " + TABLE_PLAYERS + " set " + KEY_PLAYERS_SCORE + " = " + KEY_PLAYERS_SCORE + " + new." + KEY_HISTORY_VALUE + " where " + KEY_PLAYERS_ID + " = new. " + KEY_HISTORY_PLAYER + ";"
+ " end;";
private static final String CREATE_TRIGGER_UPDATE_SCORE =
"create trigger " + TRIGGER_UPDATE_SCORE + " after update on " + TABLE_HISTORY
+ " begin"
+ " update " + TABLE_PLAYERS + " set " + KEY_PLAYERS_SCORE + " = " + KEY_PLAYERS_SCORE + " + (new." + KEY_HISTORY_VALUE + " - old." + KEY_HISTORY_VALUE + ")"
+ " where " + KEY_PLAYERS_ID + " = new. " + KEY_HISTORY_PLAYER + ";"
+ " end;";
private static final String CREATE_TRIGGER_DELETE_SCORE =
"create trigger " + TRIGGER_DELETE_SCORE + " after delete on " + TABLE_HISTORY
+ " begin"
+ " update " + TABLE_PLAYERS + " set " + KEY_PLAYERS_SCORE + " = " + KEY_PLAYERS_SCORE + " - old." + KEY_HISTORY_VALUE
+ " where " + KEY_PLAYERS_ID + " = old." + KEY_HISTORY_PLAYER + ";"
+ " end;";
private static final String CREATE_TRIGGER_DELETE_HISTORY =
"create trigger " + TRIGGER_DELETE_HISTORY + " delete on " + TABLE_PLAYERS
+ " begin"
+ " delete from " + TABLE_HISTORY + " where " + KEY_HISTORY_PLAYER + " = old." + KEY_PLAYERS_ID + ";"
+ " end;";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_PLAYERS);
db.execSQL(CREATE_TABLE_HISTORY);
db.execSQL(CREATE_TRIGGER_NEW_SCORE);
db.execSQL(CREATE_TRIGGER_DELETE_HISTORY);
db.execSQL(CREATE_TRIGGER_UPDATE_SCORE);
db.execSQL(CREATE_TRIGGER_DELETE_SCORE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TRIGGER IF EXISTS " + TRIGGER_DELETE_HISTORY);
db.execSQL("DROP TRIGGER IF EXISTS " + TRIGGER_UPDATE_NEW_SCORE);
db.execSQL("DROP TRIGGER IF EXISTS " + TRIGGER_UPDATE_SCORE);
db.execSQL("DROP TRIGGER IF EXISTS " + TRIGGER_DELETE_SCORE);
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_PLAYERS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HISTORY);
onCreate(db);
}
}
public ScoreDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public ScoreDbAdapter open() throws SQLException {
if (mDbHelper == null) {
mDbHelper = new DatabaseHelper(mCtx);
}
mDb = mDbHelper.getWritableDatabase();
countPlayers();
return this;
}
public void close() {
mDbHelper.close();
}
public long createPlayer(String name, int icon, long score) {
countPlayers();
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_PLAYERS_NAME, name);
initialValues.put(KEY_PLAYERS_ICON, icon);
initialValues.put(KEY_PLAYERS_SCORE, score);
initialValues.put(KEY_PLAYERS_ORDER, mNumPlayers);
return mDb.insert(TABLE_PLAYERS, null, initialValues);
}
In create player you can see I am using the same functionality for adding that you are. I do not however see where you are creating the database. Can you present to us that similar functionality? Something is obviously amiss and we seem to be missing some aspect of the required information still.
Edit: Sorry, apparently my source somehow got a mixture of tabs and spaces in it, I guess I messed up an eclipse setting.