Android to MS Sql query - android

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.

Related

Can't Retrieve data from sqlite database even though the data exists in the database

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);

Android Sqlite database is not updating the data??

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

error in using insert query in android

I am saving some data and pic to my db I found out the true way to save my pic in db is to use contentvalue so this the code:
try
{
MyDataBase = new MyDatabase(this);
mydb = MyDataBase.getWritableDatabase();
ContentValues tempval;
for (int j = 0; j < myarray.arrtitle.length; j++)
{
tempval = saveimage(myarray.arrpic.get(j),myarray.arrpath[j]);
mydb.execSQL("INSERT INTO news (title,content) VALUES (\"" + myarray.arrtitle[j] +
"\",\"" + myarray.arrcontent[j] + "\"" + ")");
mydb.insert("news", null, tempval);
}
mydb.close();
Toast.makeText(getApplicationContext(), "database 2 done", Toast.LENGTH_LONG).show();
count = 5;
} catch (Exception e) {
// TODO: daabase error2
Toast.makeText(getApplicationContext(), "data error2", Toast.LENGTH_LONG).show();
}
so this is how i can save my data correctly.
but the problem is when I insert my image, it insert in new row not the row as same as title was inserted.
is there any way to handle this?
You need to use UPDATE query, if you want to edit some column data of an already existing row. Every time you execute INSERT query, it will create a new row.
You are executing INSERT query twice, once you are inserting title and content and then in next query you are inserting image path. Instead while saving image path you should execute UPDATE query for the same row in which you saved corresponding data.
Use LIKE instead of = operator.
// updating row
db.update(TABLE, tempval , "title LIKE ?", new String[] { myarray.arrtitle[j] })

Android Sqlite insertion of a single quote ex. "O'Connor"

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.

Error on using REPLACE character manipulation function on query SQLite Android

it gives me an error when I am using this key but when I use LENGTH, it works fine. I hope it is allowed on android sqlite coz it's the best way for this:
I am just trying to remove the spaces after words that will be selected from Database.
public ArrayList<String> getCorrectList() {
// TODO Auto-generated method stub
Cursor c = db.rawQuery("SELECT REPLACE(Level_1, ' ', '') FROM " + TABLE, null);
ArrayList<String> resultsList = new ArrayList<String>();
try {
if (c != null) {
if (c.moveToFirst()) {
do {
String levelData = c.getString(c
.getColumnIndex("Level_1"));
resultsList.add("" + c.getColumnIndex("Level_1"));
} while (c.moveToNext());
}
}
} catch (SQLiteException e) {
Log.e("Database", "Cannot get List (" + e + ")");
}
Log.d("array", "List: " + resultsList);
Collections.shuffle(resultsList);
return resultsList;
}
This works fine in SQLite3 shell:
e$ sqlite3
SQLite version 3.7.14.1 2012-10-04 19:37:12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table t(a,b,c);
sqlite> select replace(a,' ', '') from t;
REPLACE is both a function and a command in SQLite3. Perhaps db.rawQuery is parsing the query and getting confused by REPLACE. Try this:
db.rawQuery("select rtrim(replace(Level_1, ' ', '')) FROM " + TABLE, null);

Categories

Resources