For some reason I can't get the single quote with apostrophes in a name field to submit to my sqlite database.
Here's where I get the input and call the database function
if(fnamelabel.contains("'") || fnamelabel.contains("-")){
fnamelabel = DatabaseUtils.sqlEscapeString(fnamelabel);
}else if(lnamelabel.contains("'") || lnamelabel.contains("-")){
lnamelabel = DatabaseUtils.sqlEscapeString(lnamelabel);
}
Log.w("myApp", "fname " + fnamelabel + ".");
Log.w("myApp", "lname " + lnamelabel + ".");
try{
//if all fields are filled and has a number between 0 and 99
LiteHandlerPlayers db = new LiteHandlerPlayers(getApplicationContext());
if(db.insertLabel(fnamelabel, lnamelabel, pnumlabel)){
db.getWritableDatabase();
db.insertLabel(fnamelabel, lnamelabel, pnumlabel);
Toast.makeText(getApplicationContext(), "#" + pnumlabel + " " + fnamelabel + " " + lnamelabel + " has been added to your team.", Toast.LENGTH_SHORT).show();
db.close();
}else{
Toast.makeText(getApplicationContext(), "That player is already on your team!", Toast.LENGTH_SHORT).show();
}
Here's my function within the db
if(flag){
//no player in db with name
ContentValues values = new ContentValues();
values.put(Player_fname, label);
values.put(Player_lname, label2);
values.put(Player_num , label3);
values.put(Player_gplay, 0);
values.put(Player_assist, 0);
values.put(Player_shots, 0);
values.put(Player_goals, 0);
values.put(Player_shagn, 0);
values.put(Player_gallw, 0);
values.put(Player_assist, 0);
db.insert(Table_labels, null, values);
db.close();//close db
return true;
}else{
db.close();
return false;
}
and eventually gets displayed on a spinner on a different screen but the error that i keep getting for an example name like Bob O'Connor (O'Connor is changed to O''Connor at this point) is that there is a syntax error near the O in O''Connor which is pretty vague. ((1) near "O": syntax error , is exactly what it says) If anyone can enlighten me I would be much obliged.
Related
Im trying to retrieve some data out of a database called Train_list When i try to do so m greeted with the error:
D/FinalĀ Error: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
After a bit of googling And a bit of Trail and error i realized that the cursor was returning a null value So i Questioned if the data was actually being inserted into the database. So i Used a third party plugin ( Or what ever you want to call it ) to see if the data was indeed present in the Database
As You can see the database does indeed have three entries. Now when i Try to read the database with this code:
setContentView(R.layout.activity_display_data);
Bundle bundle = getIntent().getExtras();
no_name = (ListView) findViewById(R.id.Disp_list);
String message = bundle.getString("package");
String parameter;
SQLiteDatabase db = openOrCreateDatabase(message, SQLiteDatabase.CREATE_IF_NECESSARY, null);
SQLiteDatabase db1 = openOrCreateDatabase("Train_list.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
Cursor header;
namer=(TextView)findViewById(R.id.T1);
try {
header = db1.rawQuery("Select Train_name From Train_list Where Train_no='"+message.substring(0,(message.length()-3))+ "'", null);
header.moveToFirst();
String temp = header.getString((header.getColumnIndex("Train_name")));
Toast.makeText(Display_data.this, "blahhh:"+temp, Toast.LENGTH_LONG).show();
Log.d("Sucess!","temp:"+temp);
Toast.makeText(Display_data.this, "Gotcha:"+temp , Toast.LENGTH_LONG).show();
namer.setText("Train Name: " + temp);
header.close();
}catch(Exception e)
{
Log.d("Final Error",e.toString());
Toast.makeText(Display_data.this, "Error", Toast.LENGTH_LONG).show();
}
I get the aforementioned error. Some posts suggested adding a '?' but that didnt help either
Heres the code with which i inserted the data:
try {
final String CREATE_TABLE_TRAIN_LIST = "CREATE TABLE IF NOT EXISTS Train_list ("
+ "Train_name VARCHAR,"
+ "Train_no VARCHAR,"
+ "Train_start VARCHAR,"
+ "Train_end VARCHAR,"
+ "Seats_Available VARCHAR);";
db.execSQL(CREATE_TABLE_TRAIN_LIST);
Toast.makeText(admin_manipulation.this, "Table created", Toast.LENGTH_LONG).show();
String sql = "INSERT or replace INTO Train_list (Train_name, Train_no, Train_start, Train_end, Seats_Available) VALUES('"+str_Train_name + "',' " +str_Train_no + "', '" +str_Train_start+"','" +str_Train_end+"',' " +str_Train_seats +"');";
try {
db.execSQL(sql);
Toast.makeText(admin_manipulation.this, "train no:"+str_Train_no, Toast.LENGTH_SHORT).show();
}catch(Exception e)
{
Toast.makeText(admin_manipulation.this, "Sorry Not Inserted Sucessfully", Toast.LENGTH_SHORT).show();
Log.d("Error experienced",e.toString());
}
Any idea why this is happening?
Try checking by getting the cursor count for the query you have run. header.getCount() and then do the header.getString() only if there is data
if (header!= null && header.getCount() > 0){
header.moveToFirst();
// All the logic of retrieving data from cursor
}
This line in your code:
header = db1.rawQuery("Select Train_name From Train_list Where Train_no='"+message.substring(0,(message.length()-3))+ "'", null);
might throw problems depending on the message passed in.
If the Train_no is supposed to be the train numbers in your table, substringing - 3 looks like it will return only the "aa" portion. Then your rawQuery will look for a Train_no that is "aa".
Consider using the LIKE SQL syntax. This question is useful.
Your query may look like:
header = db1.rawQuery("Select Train_name From Train_list Where Train_no like '"+message.substring((message.length()-3), message.length())+ "'", null);
i am using this code to update the values
this Code is working properly without an error there is no error in query but when i show data after updating its showing the old data??
this is the code i am using for updating the data in sqlite.
#Override
public void onClick(View v) {
if (v == Update) {
try {
ContentValues CV = new ContentValues();
CV.put("cname", EditName.getText().toString());
CV.put("mobileno", EditMobile.getText().toString());
CV.put("phone", EditLandline.getText().toString());
CV.put("address", EditAddress.getText().toString());
CV.put("email", EditEmail.getText().toString());
CV.put("picture", Editbytes);
DB.update("contacts", CV, "cname=" + V,null);
Intent I = new Intent(ctx, ContactList.class);
ctx.startActivity(I);
// DB.execSQL("insert into contacts values('" + Name.getText() + "','" + Mobile.getText() + "','" + Phone.getText() + "','" + Add.getText() + "','" + Email.getText() + "')");
Toast.makeText(ctx, "Contact Updated...",Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(ctx, "Fail to Update Contact.." + e, Toast.LENGTH_LONG).show();
}
} else if (v == Delete) {
}
}
Can you please try this,
DB.update("contacts", CV, "cname=" + V,null);
What is the V, is that particular name , I thingk, you may try to udapte using id, which is more effective.
Change to
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.update("contacts", CV, "cid=" + "=" + id, null);
db.close(); // Closing database connection
However, if you don't update, please clean your project and rebuild, that might work.If this will not help, please post you logcat.
Is there any chance WHERE clause is not matching any rows?
You can test your condition on console with:
Log.i(db.execSQL("SELECT * FROM contacts WHERE cname=" + V));
But I think the best way to test this is connect directly to database:
Open a terminal on Android Studio (View > Tool Windows > Terminal)
Enter adb shell (if command fails, add your adb installation into PATH variable)
The database file is usually stored in /data/data/com.your.package/database/
Run sqlite3 /data/data/com.your.package/database/YourAPP.db to open a prompt where you can run all SQL commands
Another good answer
Can someone explain to me how this code works and how I am inserting this data into the database? I Java two Java files. The first piece of code is located in the first Java file and the second is located in the second Java file. Why am I passing the following parameters ImageID, currentDay, v.getID. Then when I call the insertNewRoutine function it is using the parameters int activityResourceID, String day and int slot? Confused about why it's using that?Thanks in advance!
boolean routineInserted = myDb.insertNewRoutine(ImageID, currentDay, v.getId());
if (routineInserted == true) {
Toast.makeText(MondayRoutineEdit.this, "Activity Inserted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MondayRoutineEdit.this, "Activity Not Inserted", Toast.LENGTH_LONG).show();
}
public boolean insertNewRoutine(int activityResourceID, String day, int slot)
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + RoutineTable + " WHERE DayID ='" + day + "' AND SlotID =" + slot);
ContentValues contentValues = new ContentValues();
contentValues.put(RoutineColumn2, day);
contentValues.put(RoutineColumn3, activityResourceID);
contentValues.put(RoutineColumn4, slot);
long result = db.insert(RoutineTable, null, contentValues);
if (result == -1)
return false;
else
return true;
}
ContentValues contentValues = new ContentValues();
contentValues.put(RoutineColumn2, day);
contentValues.put(RoutineColumn3, activityResourceID);
contentValues.put(RoutineColumn4, slot);
long result = db.insert(RoutineTable, null, contentValues);
You are population the content values (they are going to be inserted as VALUES in sql) with function paramaters.
This method call is responsible for insertion.
SQLiteDatabase.class exposes methods to manage a SQLite database.
Reference to the official android documentation
https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#insert(java.lang.String,%20java.lang.String,%20android.content.ContentValues)
my application was working fine but then i changed something and its not inserting records in the database. when ever i press the submit button it show me toast "Record not inserted"
here is the code
connect=connn.ConnHelper(username, password, db, ipaddress);
if (connect == null){
Toast.makeText(getBaseContext(),"Connection Unsuccessfull",Toast.LENGTH_LONG).show();
}
else {
//inserting records in database
//is se nechy nechy
try {
st = connect.createStatement();
String query = "insert into profiles(Name,City,Address,Speciality,Phone,CNIC,Picture,Status) values('" + name + "','" + city + "','" + add + "','"+spec+"','"+ph+"','"+cn+"','"+img+"','pending');";
preStatement = connect.prepareStatement(query);
int k=preStatement.executeUpdate();
if(k==1){
Toast.makeText(getBaseContext(),"Record Inserted Successfully",Toast.LENGTH_LONG).show();
Intent imageIntent = new Intent("com.androsoft.application.Profile");
imageIntent.putExtra("Id",Cnic.getText().toString());
startActivity(imageIntent);
}
else{
Toast.makeText(getBaseContext(),"Record Not Inserted",Toast.LENGTH_LONG).show();
}
} catch (SQLException e) {
Toast.makeText(getBaseContext(),"Record Not Inserted",Toast.LENGTH_LONG).show();
}
here its returning zero to k.
mydatabase entities are.
database entities
Try to run this application in debug mode, and get the String query value on runtime (like insert into profiles(Name,City,Address,Speciality,Phone,CNIC,Picture,Status) value('dav','city','new york',null,'33','f');, then try to execute the query directly in sql server. If there is no problem in your query so this is something in the connection to the data base or problem in the application.
public boolean findContact(String phoneNumber) {
boolean exists = false;
Cursor mCursor = mDb.rawQuery("SELECT * FROM " + SQLITE_TABLE + " WHERE " + KEY_PHONENUMBER + " = " + phoneNumber, null);
if (mCursor.moveToFirst()) {
exists = true;
} else exists = false;
return exists;
}
It is supose to return true when a row with telephone number exists (format is +441212312312 - String ). The problem is that it always return false, even if such a row exists. I think that a problem is with WHERE clause, but LIKE don't work either. How can I do this ?
thanks for your response
i suggest you that use query, insert, update or delete clauses directly from SQLiteDatabase object instance ;)
And see link below to know which values you will have returned
SQLiteDatabase Object
And i suggest too that if you just want if it exists don't ask about * ... ask about _id because it's primary key it has a index ;)) <-- it means faster
Here i seek a specific row:
public Cursor getEnvio(final String empresa_p, final String albaran_p) {
return db.query(Envio.KEY_ENVIO, new String[] { Envio.KEY_ID,
Envio.KEY_ALBARAN, Envio.KEY_LINEA, Envio.KEY_TIPO,
Envio.KEY_DESTINATARIO, Envio.KEY_DIR, Envio.KEY_POBLACION,
Envio.KEY_POBLACION, Envio.KEY_PRIORIDAD, Envio.KEY_INCIDENCIA,
Envio.KEY_EMP, Envio.KEY_CPOSTAL }, Envio.KEY_EMP + " = ? AND "
+ Envio.KEY_ALBARAN + " = ? ", new String[] { empresa_p,
albaran_p }, null, null, Envio.KEY_LINEA);
}