I have a local database in my app for storing user profiles from input fields. I have created the database using SQLiteOpenHelper class but after running my app, this error appears. I have been through the DatabaseHelper class but can't find what's wrong with it. I hope someone points out my mistake. Thanks.
my db class file here:
public class DBHelper {
private static final String DATABASE_NAME = "UsersDemo.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "profileInfo";
private static final String COL_ID = "databaseId";
public static final String COL_USER_ID = "userId";
public static final String COL_FULL_NAME = "fullName";
public static final String COL_GENDER = "gender";
public static final String COL_DOB = "DOB";
public static final String COL_MOBILE_NUM = "mobileNum";
public static final String COL_OCCUPATION = "occupation";
public static final String COL_ORGANIZATION = "organization";
//private static final String COL_PROFILE_PHOTO = "profilePhoto";
private Context mCtx;
private DatabaseManager databaseManager;
private SQLiteDatabase db;
public DBHelper(Context context){
this.mCtx = context;
databaseManager = new DatabaseManager(mCtx);
}
public DBHelper open() throws SQLException{
db = databaseManager.getWritableDatabase();
return this;
}
public void close(){
databaseManager.close();
}
public boolean saveInputField(TingTingUser user){
SQLiteDatabase userDb = databaseManager.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_FULL_NAME, user.getDisplayName());
values.put(COL_USER_ID, user.getUserId());
values.put(COL_GENDER, user.getGender());
values.put(COL_DOB, user.getDob());
values.put(COL_MOBILE_NUM, user.getMobileNumber());
values.put(COL_ORGANIZATION, user.getOrganization());
values.put(COL_OCCUPATION, user.getOccupation());
long result = userDb.insert(TABLE_NAME, null, values);
userDb.close();
if (result == -1){
return false;
} else {
return true;
}
}
public TingTingUser getCurrentUser(int id){
SQLiteDatabase currDB = databaseManager.getWritableDatabase();
Cursor cursor = currDB.query(true, TABLE_NAME, new String[]{COL_ID, COL_USER_ID, COL_FULL_NAME, COL_GENDER, COL_DOB, COL_MOBILE_NUM, COL_OCCUPATION, COL_ORGANIZATION}, COL_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null && cursor.moveToFirst()){
TingTingUser user = new TingTingUser(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7));
return user;
}
return null;
}
public void saveCameraImage(byte[] imageBytes){
SQLiteDatabase camDb = databaseManager.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put(COL_PROFILE_PHOTO, imageBytes);
camDb.insert(TABLE_NAME, null, contentValues);
}
public void saveGalleryImage(byte[] imageBytes){
ContentValues contentValues = new ContentValues();
//contentValues.put(COL_PROFILE_PHOTO, imageBytes);
db.insert(TABLE_NAME, null, contentValues);
}
public class DatabaseManager extends SQLiteOpenHelper {
public DatabaseManager(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String db_create = "Create Table " + TABLE_NAME + " ("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_USER_ID + " TEXT, "
+ COL_FULL_NAME + " TEXT, "
+ COL_GENDER + " TEXT, "
+ COL_DOB + " TEXT, "
+ COL_MOBILE_NUM + " TEXT, "
+ COL_OCCUPATION + " TEXT, "
+ COL_ORGANIZATION + " TEXT, ";
//+ COL_PROFILE_PHOTO + " BLOB NOT NULL );";
sqLiteDatabase.execSQL(db_create);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(sqLiteDatabase);
}
}
}
The error occurs in my MainActivity when I call saveInputField() method of DBHelper, shown below:
JsonObjectRequest otpObjectRequest = new JsonObjectRequest(Request.Method.POST, Constants.TING_VERIFY_OTP_ENDPOINT, verifyOTPObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("OTPDialogFragment", "OTP Verification Response is: \t" + response.toString());
Log.d("OTPDialogFragment", "OTP Verified Successfully");
try {
JSONObject verifyObject = new JSONObject(response.toString());
JSONObject userObject = verifyObject.getJSONObject("user");
userId = userObject.getString("_id");
Log.d(TAG, "Retrieved user id is:\t" + userId);
TingTingUser user = new TingTingUser();
user.setDisplayName(fullName);
user.setMobileNumber(num);
user.setGender(genderVal);
user.setDob(dob);
user.setOccupation("default");
user.setOrganization("default");
user.setUserId(userId);
if (!TextUtils.isEmpty(fullName) && !TextUtils.isEmpty(genderVal) && !TextUtils.isEmpty(dob) && !TextUtils.isEmpty(userId)){
if (dbHelper.saveInputField(user) == true){ // error occurs here
Toast.makeText(getContext(), "Saved User", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Save Failed", Toast.LENGTH_SHORT).show(); // Toast shows cos save failed, dont know why
}
}
Sorry guys, my mainactivity is too long, only showed what is necessary.
Error message in logcat:
android.database.sqlite.SQLiteException: near ",": syntax error (code 1): , while compiling: Create Table profileInfo (databaseId INTEGER PRIMARY KEY AUTOINCREMENT, userId TEXT, fullName TEXT, gender TEXT, DOB TEXT, mobileNum TEXT, occupation TEXT, organization TEXT,
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.billionusers.tingting.db.DBHelper$DatabaseManager.onCreate(DBHelper.java:131)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.billionusers.tingting.db.DBHelper.saveInputField(DBHelper.java:53)
at com.billionusers.tingting.activities.SignUpActivity$OTPDialogFragment$6.onResponse(SignUpActivity.java:466)
at com.billionusers.tingting.activities.SignUpActivity$OTPDialogFragment$6.onResponse(SignUpActivity.java:443)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
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)
From the logcat
near ",": syntax error (code 1): , while compiling: Create Table profileInfo (databaseId INTEGER PRIMARY KEY AUTOINCREMENT, userId TEXT, fullName TEXT, gender TEXT, DOB TEXT, mobileNum TEXT, occupation TEXT, organization TEXT,
and DBHelper.onCreate
String db_create = "Create Table " + TABLE_NAME + " ("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COL_USER_ID + " TEXT, "
+ COL_FULL_NAME + " TEXT, "
+ COL_GENDER + " TEXT, "
+ COL_DOB + " TEXT, "
+ COL_MOBILE_NUM + " TEXT, "
+ COL_OCCUPATION + " TEXT, "
+ COL_ORGANIZATION + " TEXT, ";
//+ COL_PROFILE_PHOTO + " BLOB NOT NULL );";
sqLiteDatabase.execSQL(db_create);
Your create statement is invalid because you have put into comments the last line so it terminates in + COL_ORGANIZATION + " TEXT, "; which is not correct. The ending should be:
+ COL_ORGANIZATION + " TEXT ); ";
Related
I implemented forgot password but i am getting an error. My db contains data.
Here is the logcat:
"E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.myapplication, PID: 8265
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Boolean com.example.admin.myapplication.DatabaseHelper.updatepwd(java.lang.String, java.lang.String)' on a null object reference
at com.example.admin.myapplication.Reset$1.onClick(Reset.java:39)
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)"
Below is the following code i have used:
Reset.java
public class Reset extends AppCompatActivity {
TextView phone;
EditText pwd,cpwd;
Button resetbtn;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reset);
phone = (TextView)findViewById(R.id.Phonenumber);
pwd = (EditText) findViewById(R.id.pssword);
cpwd = (EditText) findViewById(R.id.pwdreenter);
resetbtn = (Button) findViewById(R.id.btnReset);
Intent intent = getIntent();
phone.setText(intent.getStringExtra("phone"));
resetbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String user = phone.getText().toString();
String pswd = pwd.getText().toString();
String repswd = cpwd.getText().toString();
if (pswd.equals(repswd)) {
Boolean pwd = db.updatepwd(user, pswd);
if (pwd) {
Intent intent1 = new Intent(getApplicationContext(), Login.class);
startActivity(intent1);
Toast.makeText(Reset.this, "Password Updated Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Reset.this, "Password NotUpdated Successfully", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(getApplicationContext(), "Password Don't Match", Toast.LENGTH_SHORT).show();
}
}
});
//new code
public class MyTestDatabaseInstanceHolder {
public MyTestDBHandler DBHelper;
public static SQLiteDatabase m_ObjDataBase;
public static void createDBInstance(Context pContext){
if(DBHelper == null) {
DBHelper = new WLDBHandler(pContext);
m_cObjDataBase = DBHelper.openAndCreateDataBase();
}
}
}
Db.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "application.db";
public static final String TABLE_SIGNUP = "Signup";
public static final String COL_ID = "USER_ID";
public static final String COL_NAME = "NAME";
public static final String COL_PHONE = "PHONE_NUMBER";
public static final String COL_EMAIL = "EMAIL";
public static final String COL_PASSWORD = "PASSWORD";
public static final String COL_CONFIRMPASSWORD = "CONFIRMPASSWORD";
public static final String COL_NAMEone_CON = "NAMEONE";
public static final String COL_NUMBERone_CON = "NUMBERONE";
public static final String COL_NAMEtwo_CON = "NAMETWO";
public static final String COL_NUMBERtwo_CON = "NUMBERTWO";
public static final String COL_NAMEthree_CON = "NAMETHREE";
public static final String COL_NUMBERthree_CON = "NUMBERTHREE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 3);
// SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_SIGNUP + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT , "
+ COL_NAME + " VARCHAR(255) , " + COL_PHONE + " VARCHAR (255) UNIQUE ," + COL_EMAIL + " VARCHAR (255) UNIQUE," + COL_PASSWORD + " VARCHAR (255), "
+ COL_CONFIRMPASSWORD + " VARCHAR (255)," + COL_NAMEone_CON + " VARCHAR (255), "
+ COL_NUMBERone_CON + " VARCHAR (255) UNIQUE ," + COL_NAMEtwo_CON + " VARCHAR (255)," + COL_NUMBERtwo_CON + " VARCHAR (255) UNIQUE , "
+ COL_NAMEthree_CON + " VARCHAR (255)," + COL_NUMBERthree_CON + " VARCHAR (255) UNIQUE " + ")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SIGNUP);
onCreate(db);
}
Boolean updatepwd(String PHONE_NUMBER, String PASSWORD) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("PASSWORD", PASSWORD);
long res= db.update("Signup", contentValues, "PHONE_NUMBER = ?", new String[]{PHONE_NUMBER});
db.close();
if(res == -1)
return false;
else
return true;
}
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.
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;
}
}
Can anyone see what is wrong with this code please, this is the error given:
Caused by: android.database.sqlite.SQLiteException: near ")": syntax error (code 1): , while compiling: CREATE TABLE scores(_id INTEGER PRIMARY KEY AUTOINCREMENT , scoreName TEXT , );
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "scores.db";
public static final String TABLE_SCORES = "scores";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_SCORENAME = "scoreName";
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_SCORES + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT " +
COLUMN_SCORENAME + " TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_SCORES);
onCreate(db);
}
public void addScore(Scores score) {
ContentValues values = new ContentValues();
values.put(COLUMN_SCORENAME, score.get_scoreName());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_SCORES, null, values);
db.close();
}
public void deleteScore(String scoreName) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_SCORES + "WHERE " + COLUMN_SCORENAME + "=\"" + scoreName + "\";");
}
public String databaseToString() {
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_SCORES + "WHERE 1";
//Cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
//move to first row in your results
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("scoreName")) != null) {
dbString += c.getString(c.getColumnIndex("scoreName"));
dbString += "\n";
}
}
db.close();
return dbString;
}
}
Seems problem in Query for creating table (comma is missing after AUTOINCREMENT). Try this
db.execSQL("CREATE TABLE " + TABLE_SCORES + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_SCORENAME + " TEXT" + ");");
this is my database, can you please help me with it? i think there is nothing wrong i tried reinstalling the app to update the database initially but still doesnt work. it says that there is no such column _url.
This is my class that creates the database:
MySQLiteHelper.java
public class MySQLiteHelper extends SQLiteOpenHelper {
/**
* table for locations
* | _id | _latitude | _longitude | _time | _provider
*/
public static final String TABLE_LOCATION = "location";
public static final String COLUMN_LOCID = "_id";
public static final String COLUMN_LATITUDE = "_latitude";
public static final String COLUMN_LONGITUDE = "_longitude";
public static final String COLUMN_TIME = "_time";
public static final String COLUMN_ACCURACY = "_accuracy";
public static final String COLUMN_PROVIDER = "_provider";
/**
* table for pictures
* | _id | _url | _latitude | _longitude | _time
*/
public static final String TABLE_PICTURE = "picture";
public static final String COLUMN_PIC_ID = "_id";
public static final String COLUMN_PIC_URL = "_url";
public static final String COLUMN_PIC_LATITUDE = "_latitude";
public static final String COLUMN_PIC_LONGITUDE = "_longitude";
public static final String COLUMN_PIC_TIME = "_time";
public static final String COLUMN_PIC_ACCURACY = "_accuracy";
/**
* table for Accelerometer
* | _id | _x | _y | _z | _time
*/
public static final String TABLE_ACCELEROMETER = "accelerometer";
public static final String COLUMN_ACCELEROMETER_ID = "_id";
public static final String COLUMN_ACCELEROMETER_X = "_x";
public static final String COLUMN_ACCELEROMETER_Y = "_y";
public static final String COLUMN_ACCELEROMETER_Z = "_z";
public static final String COLUMN_ACCELEROMETER_TIME = "_time";
/**
* table for Sound
* | _id | _amplitude | _time
*/
public static final String TABLE_AMPLITUDE = "sound";
public static final String COLUMN_AMPLITUDE_ID = "_id";
public static final String COLUMN_AMPLITUDE_AMPLITUDE = "_amplitude";
public static final String COLUMN_AMPLITUDE_TIME = "_time";
private static final String DATABASE_NAME = "memory.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement for location
private static final String DATABASE_CREATE_LOC = "create table "
+ TABLE_LOCATION + "(" + COLUMN_LOCID
+ " integer primary key autoincrement, " + COLUMN_LATITUDE
+ " double not null, "+ COLUMN_LONGITUDE + " double not null, "
+ COLUMN_TIME + " text not null, " + COLUMN_ACCURACY + " text not null, " +
COLUMN_PROVIDER + " text not null " +");";
// Database creation sql statement for picture
private static final String DATABASE_CREATE_PIC = "create table "
+ TABLE_PICTURE + "(" + COLUMN_PIC_ID
+ " integer primary key autoincrement, " + COLUMN_PIC_URL
+ " text not null, " + COLUMN_LATITUDE
+ " double, "+ COLUMN_LONGITUDE + " double, "
+ COLUMN_TIME + " text, " + COLUMN_PIC_ACCURACY + " text " + ");";
// Database creation sql statement for accelerometer
private static final String DATABASE_CREATE_ACCELEROMETER = "create table "
+ TABLE_ACCELEROMETER + "(" + COLUMN_ACCELEROMETER_ID
+ " integer primary key autoincrement, " + COLUMN_ACCELEROMETER_X
+ " float not null, " + COLUMN_ACCELEROMETER_Y
+ " float not null, "+ COLUMN_ACCELEROMETER_Z + " float not null, "
+ COLUMN_ACCELEROMETER_TIME + " text " +");";
// Database creation sql statement for sound
private static final String DATABASE_CREATE_AMPLITUDE = "create table "
+ TABLE_AMPLITUDE + "(" + COLUMN_AMPLITUDE_ID
+ " integer primary key autoincrement, " + COLUMN_AMPLITUDE_AMPLITUDE
+ " double not null, "
+ COLUMN_AMPLITUDE_TIME + " text " +");";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE_LOC);
database.execSQL(DATABASE_CREATE_PIC);
database.execSQL(DATABASE_CREATE_ACCELEROMETER);
database.execSQL(DATABASE_CREATE_AMPLITUDE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOCATION);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PICTURE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ACCELEROMETER);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_AMPLITUDE);
onCreate(db);
}
}
I dont find anything wrong in my tables. i checked for spaces.
The error i get is:
03-24 17:51:39.851: E/SQLiteLog(18574): (1) no such column: _url
03-24 17:51:39.855: W/dalvikvm(18574): threadid=11: thread exiting with uncaught exception (group=0x40eb0300)
03-24 17:51:39.863: E/AndroidRuntime(18574): FATAL EXCEPTION: Thread-799
03-24 17:51:39.863: E/AndroidRuntime(18574): android.database.sqlite.SQLiteException: no such column: _url (code 1): , while compiling: SELECT _id, _url, _latitude, _longitude, _time, _accuracy FROM picture
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
03-24 17:51:39.863: E/AndroidRuntime(18574): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
03-24 17:51:39.863: E/AndroidRuntime(18574): at data.DatabaseInteraction.getAllPictures(DatabaseInteraction.java:191)
03-24 17:51:39.863: E/AndroidRuntime(18574): at main.inSituApp.InSituApp$3.run(InSituApp.java:327)
I have a class that uses the database class to insert and query data to and from the database.
DatabaseInteraction.java
public class DatabaseInteraction {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] locColumns = { MySQLiteHelper.COLUMN_LOCID,
MySQLiteHelper.COLUMN_LATITUDE, MySQLiteHelper.COLUMN_LONGITUDE,
MySQLiteHelper.COLUMN_TIME, MySQLiteHelper.COLUMN_ACCURACY,
MySQLiteHelper.COLUMN_PROVIDER};
private String[] picColumns = { MySQLiteHelper.COLUMN_PIC_ID,
MySQLiteHelper.COLUMN_PIC_URL, MySQLiteHelper.COLUMN_PIC_LATITUDE,
MySQLiteHelper.COLUMN_PIC_LONGITUDE,
MySQLiteHelper.COLUMN_PIC_TIME, MySQLiteHelper.COLUMN_PIC_ACCURACY };
private String[] accColumns = { MySQLiteHelper.COLUMN_ACCELEROMETER_ID,
MySQLiteHelper.COLUMN_ACCELEROMETER_X, MySQLiteHelper.COLUMN_ACCELEROMETER_Y,
MySQLiteHelper.COLUMN_ACCELEROMETER_Z,
MySQLiteHelper.COLUMN_ACCELEROMETER_TIME };
private String[] amplitudeColumns = { MySQLiteHelper.COLUMN_AMPLITUDE_ID,
MySQLiteHelper.COLUMN_AMPLITUDE_AMPLITUDE,
MySQLiteHelper.COLUMN_AMPLITUDE_TIME };
public DatabaseInteraction(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public /*Loc*/ long createLocation(double latitude, double longitude, long time,
double accuracy, String provider) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_LATITUDE, latitude);
values.put(MySQLiteHelper.COLUMN_LONGITUDE, longitude);
values.put(MySQLiteHelper.COLUMN_TIME, time);
values.put(MySQLiteHelper.COLUMN_ACCURACY, accuracy);
values.put(MySQLiteHelper.COLUMN_PROVIDER, provider);
open();
long insertId = database.insert(MySQLiteHelper.TABLE_LOCATION, null,
values);
close();
return insertId;
/*Cursor cursor = database.query(MySQLiteHelper.TABLE_LOCATION,
locColumns,
MySQLiteHelper.COLUMN_LOCID + " = " + insertId, null, null,
null, null);
cursor.moveToFirst();
Loc newLoc = cursorToLocation(cursor);
cursor.close();
return newLoc;*/
}
public long createPic(String url, double latitude, double longitude,
long time) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_PIC_URL, url);
values.put(MySQLiteHelper.COLUMN_LATITUDE, latitude);
values.put(MySQLiteHelper.COLUMN_LONGITUDE, longitude);
values.put(MySQLiteHelper.COLUMN_TIME, time);
open();
long insertId = database.insert(MySQLiteHelper.TABLE_PICTURE, null,
values);
close();
return insertId;
/*Cursor cursor = database.query(MySQLiteHelper.TABLE_PICTURE,
picColumns, MySQLiteHelper.COLUMN_PIC_ID + " = " + insertId,
null, null, null, null);
cursor.moveToFirst();
Pic newPic = cursorToPicture(cursor);
cursor.close();
return newPic;*/
}
public long createAccelerometer(float x, float y, float z,
long time) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_ACCELEROMETER_X, x);
values.put(MySQLiteHelper.COLUMN_ACCELEROMETER_Y, y);
values.put(MySQLiteHelper.COLUMN_ACCELEROMETER_Z, z);
values.put(MySQLiteHelper.COLUMN_ACCELEROMETER_TIME, time);
open();
long insertId = database.insert(MySQLiteHelper.TABLE_ACCELEROMETER, null,
values);
close();
return insertId;
}
public long createSound(double amplitude, long time) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_AMPLITUDE_AMPLITUDE, amplitude);
values.put(MySQLiteHelper.COLUMN_AMPLITUDE_TIME, time);
open();
long insertId = database.insert(MySQLiteHelper.TABLE_AMPLITUDE, null,
values);
close();
return insertId;
}
public int deleteLocation(long id) {
System.out.println("Location deleted with id: " + id);
open();
int value = database.delete(MySQLiteHelper.TABLE_LOCATION,
MySQLiteHelper.COLUMN_LOCID + " = " + id, null);
close();
return value;
}
public int deletePic(long id){
System.out.println("Picture deleted with id: " + id);
open();
int value = database.delete(MySQLiteHelper.TABLE_PICTURE,
MySQLiteHelper.COLUMN_PIC_ID + " = " + id, null);
close();
return value;
}
public int deleteAccelerometer(long id){
System.out.println("Accelerometer deleted with id: " + id);
open();
int value = database.delete(MySQLiteHelper.TABLE_ACCELEROMETER,
MySQLiteHelper.COLUMN_ACCELEROMETER_ID + " = " + id, null);
return value;
}
public int deleteSound(long id){
System.out.println("Sound deleted with id: " + id);
open();
int value = database.delete(MySQLiteHelper.TABLE_AMPLITUDE,
MySQLiteHelper.COLUMN_AMPLITUDE_ID + " = " + id, null);
close();
return value;
}
public List<Loc> getAllLocations() {
List<Loc> allLocations = new ArrayList<Loc>();
open();
Cursor cursor = database.query(MySQLiteHelper.TABLE_LOCATION,
locColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Loc oneLoc = cursorToLocation(cursor);
allLocations.add(oneLoc);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
close();
return allLocations;
}
public List<Pic> getAllPictures() {
List<Pic> allPictures = new ArrayList<Pic>();
open();
Cursor cursor = database.query(MySQLiteHelper.TABLE_PICTURE,
picColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Pic onePic = cursorToPicture(cursor);
allPictures.add(onePic);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
close();
return allPictures;
}
public List<Accelerometer> getAllAccelerometerValues() {
List<Accelerometer> allAccelerometerValues = new ArrayList<Accelerometer>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_ACCELEROMETER,
accColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Accelerometer oneAcc = cursorToAccelerometer(cursor);
allAccelerometerValues.add(oneAcc);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return allAccelerometerValues;
}
public List<Amplitude> getAllSoundAmpitudes() {
List<Amplitude> allSoundAmplitudes = new ArrayList<Amplitude>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_AMPLITUDE,
amplitudeColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Amplitude oneSound = cursorToAmplitude(cursor);
allSoundAmplitudes.add(oneSound);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return allSoundAmplitudes;
}
private Loc cursorToLocation(Cursor cursor) {
Loc location = new Loc();
location.setLatitude(cursor.getDouble(1));
location.setLongitude(cursor.getDouble(2));
location.setTime(cursor.getLong(3));
location.setAccuracy(cursor.getDouble(4));
return location;
}
private Pic cursorToPicture(Cursor cursor) {
Pic picture = new Pic();
picture.setLatitude(cursor.getDouble(1));
picture.setLongitude(cursor.getDouble(2));
picture.setTime(cursor.getLong(3));
return picture;
}
private Accelerometer cursorToAccelerometer(Cursor cursor) {
Accelerometer acc = new Accelerometer();
acc.setX(cursor.getFloat(1));
acc.setY(cursor.getFloat(2));
acc.setZ(cursor.getFloat(3));
acc.setTime(cursor.getLong(4));
return acc;
}
private Amplitude cursorToAmplitude(Cursor cursor) {
Amplitude sound = new Amplitude();
sound.setAmplitude(cursor.getDouble(1));
sound.setTime(cursor.getLong(2));
return sound;
}
}
Please any hint is appreciated. ty very much in advance.
Probably you have a different "picture" table structure, try deleting the current application,
then the onCreate(SQLiteDatabase database) method will create the correct structure.