How to correct this updating database in Android SQL - android

Im trying to update a specific user's information in SQL database when a user Login and I dont know why do I get this error. Please help :(
I check the record first. If there is none, I will add the user, and if it exist in my SQL. Not sure if im getting this correct.
public String RecordCheck(){
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser user = firebaseAuth.getCurrentUser();
userEmail = user.getEmail().toString();
String RecordHolder = "";
SQLiteDatabase db = getWritableDatabase();
String query = "" + "SELECT * FROM " + TABLE_USERINFO + " WHERE " + COLUMN_USEREMAIL + " = '" + userEmail.trim() + "'";
//Cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
if(c.equals("")){
RecordHolder = "adduser";
}
else
RecordHolder = "updateuser";
db.close();
return RecordHolder;
I have this in my Welcome Back class to know if its going to update if user exist or add if user doesnt exist.
String Record = dbHandler.RecordCheck();
if(Record.equals("adduser")){
dbHandler.addUser(userdata);
}
else {
dbHandler.updateUser(userdata);
}
if update is called
public void updateUser(Users user){
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser userf = firebaseAuth.getCurrentUser();
userEmail = userf.getEmail();
ContentValues values = new ContentValues();
values.put(MyDBHandler.COLUMN_USEREMAIL, user.get_useremail());
values.put(MyDBHandler.COLUMN_NAME, user.getName());
values.put(MyDBHandler.COLUMN_SEX, user.getSex());
values.put(MyDBHandler.COLUMN_BDAY, user.getBday());
values.put(MyDBHandler.COLUMN_HEIGHT, user.getHeight());
values.put(MyDBHandler.COLUMN_MHEIGHT, user.getMheight());
values.put(MyDBHandler.COLUMN_WEIGHT, user.getWeight());
values.put(MyDBHandler.COLUMN_MWEIGHT, user.getMweight());
values.put(MyDBHandler.COLUMN_USEREXPERIENCE, user.getUserexperience());
values.put(MyDBHandler.COLUMN_FQUESTION, user.getFquestion());
values.put(MyDBHandler.COLUMN_SQUESTION, user.getSquestion());
values.put(MyDBHandler.COLUMN_TQUESTION, user.getTquestion());
values.put(MyDBHandler.COLUMN_BODYSTATE, user.getBodystate());
values.put(MyDBHandler.COLUMN_APPARENTLYHEALTHY, user.isApparentlyhealthy());
values.put(MyDBHandler.COLUMN_HYPERTENSION, user.isHypertension());
values.put(MyDBHandler.COLUMN_DIABETES, user.isDiabetes());
values.put(MyDBHandler.COLUMN_ASTHMA, user.isAsthma());
SQLiteDatabase db = getWritableDatabase();
db.update(MyDBHandler.TABLE_USERINFO, values, userEmail, null);
db.close();
}
--------- beginning of crash
11-22 12:44:13.179 17496-17496/com.example.abad.maxfitness2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.abad.maxfitness2, PID: 17496
android.database.sqlite.SQLiteException: near "#gmail": syntax error (code 1): , while compiling: UPDATE users SET fquestion=?,mheight=?,tquestion=?,asthma=?,height=?,bodystate=?,diabetes=?,weight=?,bday=?,useremail=?,squestion=?,hypertension=?,name=?,healthy=?,mweight=?,userexp=?,sex=? WHERE testing8#gmail.com
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.updateWithOnConflict(SQLiteDatabase.java:1577)
at android.database.sqlite.SQLiteDatabase.update(SQLiteDatabase.java:1525)
at com.example.abad.maxfitness2.LocalDatabase.MyDBHandler.updateUser(MyDBHandler.java:139)
at com.example.abad.maxfitness2.WelcomeBack$1.onDataChange(WelcomeBack.java:83)
at com.google.android.gms.internal.zzbmz.zza(Unknown Source)
at com.google.android.gms.internal.zzbnz.zzYj(Unknown Source)
at com.google.android.gms.internal.zzboc$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

You have to pass the where argument in the below format
db.update(MyDBHandler.TABLE_USERINFO,values,MyDBHandler.COLUMN_USEREMAIL+"='"+userEmail+"'", null);

You need to update query from
db.update(MyDBHandler.TABLE_USERINFO, values, userEmail, null);
to:
db.update(MyDBHandler.TABLE_USERINFO, values, "columnId ='"+userEmail+"'", null);
Note: The columnId mentioned should be the id of column in table of db e.g email etc

Related

error in counting the number of a specific record in database

how can I create a query that counts the number of an Specific record in database.
I tried this code:
public int getContactsCount(String name) {
String countQuery = "SELECT count(*) FROM database_names where _name ="+name;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
return cursor.getCount();
}
but it did not work.
it says :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 26655
android.database.sqlite.SQLiteException: incomplete input (Sqlite code 1 SQLITE_ERROR): , while compiling: SELECT count(*) FROM database_names where _name =, (OS error - 2:No such file or directory)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:948)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:559)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:603)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:63)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1493)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1427)
at com.example.myapplication.database_names.getContactsCount(database_names.java:68)
at com.example.myapplication.HazineHaActivity$1.onClick(HazineHaActivity.java:62)
at android.view.View.performClick(View.java:6663)
at android.view.View.performClickInternal(View.java:6635)
at android.view.View.access$3100(View.java:794)
at android.view.View$PerformClick.run(View.java:26199)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
how can I do it?
Probably your problem is that you don't surround the parameter name in single quotes.But the correct way to do it is to use a placeholder in your query and pass name as a parameter:
Cursor c = db.rawQuery(
"SELECT COUNT(*) AS counter FROM MY TABLE WHERE _NAME = ?",
new String[] {name}
);
Replace db with your SQLiteOpenHelper object.
select COUNT(id) as count from tblstudent where name='test'

Android.database.sqlite.SQLiteException: no such column: 500.0 (code 1)

Since 2 days, I'm not able to find the mistake. I get this error if I click on a FloatingActionButton:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.pizza, PID: 32058
android.database.sqlite.SQLiteException: no such column: 500.0 (code 1): , while compiling: INSERT INTO OrderDetail(ProductId,ProductName,Quantity,Price,Discount) VALUES('26','Margarita','1','500'.'0');
#################################################################
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(no such column: 500.0 (code 1): , while compiling: INSERT INTO OrderDetail(ProductId,ProductName,Quantity,Price,Discount) VALUES('26','Margarita','1','500'.'0');)
#################################################################
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1096)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:661)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:2109)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:2039)
at de.pizza.Database.Database.addToCart(Database.java:60)
at de.pizza.FoodDetail$1.onClick(FoodDetail.java:57)
at android.view.View.performClick(View.java:6897)
at android.view.View$PerformClick.run(View.java:26101)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Application terminated.
I checked my query more than 10 times and can't find anything :(
FoodDetail.java
public List<Order> getCarts() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"ProductName", "ProductId", "Quantity", "Price", "Discount"};
String sqlTable = "OrderDetail";
qb.setTables(sqlTable);
Cursor c = qb.query(db, sqlSelect, null, null, null, null, null);
final List<Order> result = new ArrayList<>();
if (c.moveToFirst()) {
do {
result.add(new Order(c.getString(c.getColumnIndex("ProductId")),
c.getString(c.getColumnIndex("ProductName")),
c.getString(c.getColumnIndex("Quantity")),
c.getString(c.getColumnIndex("Price")),
c.getString(c.getColumnIndex("Discount"))
));
} while (c.moveToNext());
}
return result;
}
Database.java
public class Database extends SQLiteAssetHelper {
private static final String DB_NAME = "PBBANK.db";
private static int DB_VER = 1;
public Database(Context context) {
super(context, DB_NAME, null, DB_VER);
}
public List<Order> getCarts() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"ProductName", "ProductId", "Quantity", "Price", "Discount"};
String sqlTable = "OrderDetail";
qb.setTables(sqlTable);
Cursor c = qb.query(db, sqlSelect, null, null, null, null, null);
final List<Order> result = new ArrayList<>();
if (c.moveToFirst()) {
do {
result.add(new Order(c.getString(c.getColumnIndex("ProductId")),
c.getString(c.getColumnIndex("ProductName")),
c.getString(c.getColumnIndex("Quantity")),
c.getString(c.getColumnIndex("Price")),
c.getString(c.getColumnIndex("Discount"))
));
} while (c.moveToNext());
}
return result;
}
public void addToCart(Order order)
{
SQLiteDatabase db = getReadableDatabase();
String query = String.format("INSERT INTO OrderDetail(ProductId,ProductName,Quantity,Price,Discount) VALUES('%s','%s','%s','%s'.'%s');",
order.getProductId(),
order.getProductName(),
order.getQuantity(),
order.getPrice(),
order.getDiscount());
db.execSQL(query);
}
public void cleanCart()
{
SQLiteDatabase db = getReadableDatabase();
String query = String.format("DELETE FROM ORDER OrderDetail");
db.execSQL(query);
}
}
Screenshot of my SQLite Database
I hope that my information is sufficient, and somebody can help me.
Thanks!
You have a problem inside your SQL query. Your last param has not comma. Change your line to:
From
'%s','%s','%s','%s'.'%s'
To
'%s','%s','%s','%s','%s'
Hope it will help you. Let me know.
Your issue is that you have a period rather than a comma separating the values for price and discount and thus that SQLite interprets this as being a column.
The quick fix would be to change :-
String query = String.format("INSERT INTO OrderDetail(ProductId,ProductName,Quantity,Price,Discount) VALUES('%s','%s','%s','%s'.'%s');",
order.getProductId(),
order.getProductName(),
order.getQuantity(),
order.getPrice(),
order.getDiscount());
to
String query = String.format("INSERT INTO OrderDetail(ProductId,ProductName,Quantity,Price,Discount) VALUES('%s','%s','%s','%s','%s');", //<<<<<<<<<< CHANGED
order.getProductId(),
order.getProductName(),
order.getQuantity(),
order.getPrice(),
order.getDiscount());
However using the SQLiteDatabase insert method would reduce the chance of such issues, so the above could be :-
public long addToCart(Order order)
{
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("ProductId",order.getProductId());
cv.put("ProductName",order.getProductName());
cv.put("Quantity",order.getQuantity());
cv.put("Price",order.getPrice());
cv.put("Discount",order.getDiscount());
return db.insert("OrderDetail",null,cv);
}
The insert convenience method has the advantages that
the SQL is generated,
it captures and returns the result (the id of the inserted row or if the row wasn't inserted -1)
it uses INSERT OR IGNORE so will not fail (bit will return -1) if a constraint conflict (UNIQUE or NOT NULL) occurs.

android.database.sqlite.SQLiteException: no such column: UPDATE

There is something wrong with my update statement. I am trying to update an user from my database, I am sure this user is in my database, but I just can't update him. I think I have a fault with my column name because the error said:
android.database.sqlite.SQLiteException: no such column: UPDATE
But I never asked for this column, nnn isn't a column at all in my scheme. Here is the statement
public void changeprofiel(String id, Profiel p){
SQLiteDatabase db = this.getWritableDatabase();
/* ContentValues contentValues = new ContentValues();
contentValues.put(COL_2_PROFIELEN, p.getUsername());
contentValues.put(COL_3_PROFIELEN, p.getFirstname());
contentValues.put(COL_4_PROFIELEN, p.getEmail());
contentValues.put(COL_5_PROFIELEN, p.getPassword());*/
// de insert methode geeft -1 terug als het niet gelukt is en de row value als het wel gelukt is
System.out.println(getProfielWid(id).getId());
// db.update(TABLE_NAME_PROFIELEN, contentValues,COL_1_PROFIELEN ="'" + id +"'",null);
db.execSQL("UPDATE "+ TABLE_NAME_PROFIELEN + " SET "+COL_2_PROFIELEN+" = "+p.getUsername()+", " +COL_3_PROFIELEN+" = "+p.getFirstname()+", "+COL_4_PROFIELEN+" = "+p.getEmail()+", "+COL_5_PROFIELEN+" = "+p.getPassword()+
" WHERE " + COL_1_PROFIELEN + "=" + id + "");
}
I also tried this way for the where closule:
" WHERE " + COL_1_PROFIELEN + "='" + id + "'");
But they give me both this error:
I/System.out: nnnnnn
E/SQLiteLog: (1) no such column: nnn
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cedri.bcv, PID: 13908
android.database.sqlite.SQLiteException: no such column: nnn (code 1): , while compiling: UPDATE profielen SET username = nnn, firstname = nnn, email = nnn, password = xxx WHERE profile_id=nnnnnn
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:1677)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1608)
at com.example.cedri.bcv.DB.DatabaseHelper.changeprofiel(DatabaseHelper.java:82)
at com.example.cedri.bcv.Activities.MainActivity.savechanges(MainActivity.java:94)
at com.example.cedri.bcv.Fragments.AccountFragment$1.onClick(AccountFragment.java:86)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6121)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Do I need to set every value between single quotes?
You need to wrap your values with single quotes ('') if the column's type is text.
Your query should look like this:
UPDATE profielen SET username = 'nnn', firstname = 'nnn', email = 'nnn', password = 'xxx'
WHERE profile_id='nnnnnn'

Android Sqlite database not working properly

I am simply trying to create a quiz app for that I am storing the data in the database . The following code is not working, and the app crashes every time I feed the data
public class QuestionFeedMainPage extends AppCompatActivity {
Button b1;
EditText e1,e2,e3,e4,e5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question_feed_main_page);
b1 = (Button)findViewById(R.id.submitQF);
e1 = (EditText)findViewById(R.id.q);
e2 = (EditText)findViewById(R.id.o1);
e3 = (EditText)findViewById(R.id.o2);
e4 = (EditText)findViewById(R.id.o3);
e5 = (EditText)findViewById(R.id.o4);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String q = e1.getText().toString();
String o1 = e2.getText().toString();
String o2 = e3.getText().toString();
String o3 = e4.getText().toString();
String o4 = e5.getText().toString();
if(q.equals("") || o1.equals("") || o2.equals("") || o3.equals("") || o4.equals("")){
Toast.makeText(QuestionFeedMainPage.this, "Please fill all the fields", Toast.LENGTH_SHORT).show();
}
else {
SQLiteDatabase sql = openOrCreateDatabase("multip",MODE_PRIVATE,null);
sql.execSQL("create table if not exists questions (sno INTEGER PRIMARY KEY AUTOINCREMENT,question varchar,optionone varchar,optiontwo varchar,optionthree varchar,optionfour varchar)");
String s4 = "select * from questions where question='"+q+"'";
Cursor cursor = sql.rawQuery(s4,null);
if(cursor.getCount()>0){
Toast.makeText(QuestionFeedMainPage.this, "This question already exist", Toast.LENGTH_SHORT).show();
}
else{
sql.execSQL("insert into questions values ('"+q+"','"+o1+"','"+o2+"','"+o3+"','"+o4+"')");
Toast.makeText(QuestionFeedMainPage.this, "Question Added", Toast.LENGTH_SHORT).show();
e1.setText("");
e2.setText("");
e3.setText("");
e4.setText("");
e5.setText("");
}
}
}
});
}
}
Error log:
D/ActivityThreadInjector: clearCachedDrawables.
D/OpenGLRenderer: endAllStagingAnimators on 0x55596f0a20 (RippleDrawable) with handle 0x55594260c0
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#352760c
E/SQLiteLog: (1) table questions has 6 columns but 5 values were supplied
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.fridaygmail.saurabh.multip, PID: 25409
android.database.sqlite.SQLiteException: table questions has 6 columns but 5 values were supplied (code 1): , while compiling: insert into questions values ('x','x','x','x','x')
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at com.fridaygmail.saurabh.multip.QuestionFeedMainPage$1.onClick(QuestionFeedMainPage.java:48)
at android.view.View.performClick(View.java:5207)
at android.view.View$PerformClick.run(View.java:21177)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
I/Process: Sending signal. PID: 25409 SIG: 9
Application terminated.
You want to fill 5 values into a table with 6 columns. You don't want to insert the primary key sno.
Something like this should work:
sql.execSQL("insert into questions (question,optionone,optiontwo,optionthree,optionfour) values ('"+q+"','"+o1+"','"+o2+"','"+o3+"','"+o4+"')");
The error message pretty much explains what's going on:
android.database.sqlite.SQLiteException: table questions has 6 columns but 5 values were supplied (code 1): , while compiling: insert into questions values ('x','x','x','x','x')
Try something along these lines:
String sql = "INSERT INTO questions (question, optionone, optiontwo, optionthree, optionfour) VALUES (?, ?, ?, ?, ?)";
SQLiteStatement statement = db.compileStatement(sql);
String q = e1.getText().toString();
String q1 = e2.getText().toString();
String q2 = e3.getText().toString();
String q3 = e4.getText().toString();
String q4 = e5.getText().toString();
statement.bindString(1, q); // These match to the five question marks in the sql string
statement.bindString(2, q1);
statement.bindString(3, q2);
statement.bindString(4, q3);
statement.bindString(5, q4);
long rowId = statement.executeInsert();

Android Studio : E/SQLiteLog: (1) table places has no column named description_place

I keep getting this error "table places has no clumn named description_place" still pretty new to android so no clue why this happens, can anyone spot the error?
This is my Database class:
public class BDManager {
private static final String TABLE_NAME = "places";
public static final String KEY_ID_PLACE = "_id";
public static final String KEY_NOM_PLACE = "nom_place";
public static final String KEY_TYPE_PLACE = "type_place";
public static final String KEY_ADDRESS_PLACE = "address_place";
public static final String KEY_DESCRIPTION_PLACE = "description_place";
public static final String CREATE_TABLE_PLACES = "CREATE TABLE "
+ TABLE_NAME + "("
+ KEY_ID_PLACE + " INTEGER PRIMARY KEY, "
+ KEY_NOM_PLACE +" TEXT, "
+ KEY_TYPE_PLACE +" TEXT, "
+ KEY_ADDRESS_PLACE +" TEXT, "
+ KEY_DESCRIPTION_PLACE +" TEXT);";
private MySQLite maBaseSQLite;
private SQLiteDatabase db;
public BDManager(Context context){
maBaseSQLite = MySQLite.getInstance(context);
}
public void open() {
db = maBaseSQLite.getWritableDatabase();
}
public void close() {
db.close();
}
public long addPlace(BD place){
ContentValues values = new ContentValues();
values.put(KEY_NOM_PLACE, place.getNom_place());
values.put(KEY_TYPE_PLACE, place.getType_place());
values.put(KEY_ADDRESS_PLACE, place.getAddress_place());
values.put(KEY_DESCRIPTION_PLACE, place.getDescription_place());
return db.insert(TABLE_NAME,null,values);
}
public int modPlace(BD place){
ContentValues values = new ContentValues();
values.put(KEY_NOM_PLACE, place.getNom_place());
values.put(KEY_TYPE_PLACE, place.getType_place());
values.put(KEY_ADDRESS_PLACE, place.getAddress_place());
values.put(KEY_DESCRIPTION_PLACE, place.getDescription_place());
String where = KEY_ID_PLACE+" = ?";
String[] whereArgs = {place.getId_place()+""};
return db.update(TABLE_NAME, values, where, whereArgs);
}
public BD getPlace(int id){
BD p = new BD("","","","");
Cursor c = db.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE "+KEY_ID_PLACE+"="+id, null);
if (c.moveToFirst()){
p.setId_place(c.getInt(c.getColumnIndex(KEY_ID_PLACE)));
p.setNom_place(c.getString(c.getColumnIndex(KEY_NOM_PLACE)));
p.setType_place(c.getString(c.getColumnIndex(KEY_TYPE_PLACE)));
p.setAddress_place(c.getString(c.getColumnIndex(KEY_ADDRESS_PLACE)));
p.setDescription_place(c.getString(c.getColumnIndex(KEY_DESCRIPTION_PLACE)));
c.close();
}
return p;
}
public Cursor getPlaces(){
return db.rawQuery("SELECT * FROM "+TABLE_NAME, null);
}
}
It makes the error when I try tu save a place with the addplace function here :
public void savePlace(View view) {
final EditText name = (EditText) findViewById(R.id.NomPlace);
final Spinner type = (Spinner) findViewById(R.id.TypePlace);
final EditText address = (EditText) findViewById(R.id.AdressePlace);
final EditText description = (EditText) findViewById(R.id.DescriptionPlace);
BDManager sav = new BDManager(this);
sav.open();
sav.addPlace(new BD(name.getText().toString() ,type.getSelectedItem().toString() , address.getText().toString(),description.getText().toString()));
sav.close();
name.setText("");
type.setSelection(0);
address.setText("");
description.setText("");
}
Here is the complete error :
table places has no column named description_place
Error inserting description_place= nom_place=fyeyryfu address_place=dure type_place=Default
android.database.sqlite.SQLiteException: table places has no column named description_place (code 1): , while compiling: INSERT INTO places(description_place,nom_place,address_place,type_place) VALUES (?,?,?,?)
#################################################################
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(table places has no column named description_place (code 1): , while compiling: INSERT INTO places(description_place,nom_place,address_place,type_place) VALUES (?,?,?,?))
#################################################################
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1093)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:670)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1607)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1479)
at com.myfavoriteplaces.myfavoriteplaces.BDManager.addPlace(BDManager.java:49)
at com.myfavoriteplaces.myfavoriteplaces.SavePlaces.savePlace(SavePlaces.java:124)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5076)
at android.view.View$PerformClick.run(View.java:20279)
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:5910)
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:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
Can someone help me please ?
Dude i was gonna ask for a magic wand but then.... eureka (no nudity like the greek dude is involved :-) ) I once had similar problem
A SINGLE SPACE BETWEEN THE WORD "TEXT AND THE BRACE IS NEEDED
KEY_DESCRIPTION_PLACE +" TEXT );";
I trust AN UPVOTE IS THE LEAST U CAN OFFER
mostly when a missing column error is crushing android success dream... its the cause of typing error.
Heil Android!!!
when you change database information you need to Drop table in OnOpdate()
if you want shere your onCreate and OnUpdate (MySQLite) code and i fix it

Categories

Resources