I want to update my database where the hotelname = "" (the text in EditText). but i am getting an error in my class file and the sqlitehelper file for the same method {updatedetails())
Where am I going wrong in this?
Here is my code: SQliteHelper class
public int updatedetails(String hotelname, String city, String desc,
String rooms, String price, byte[] image) {
ContentValues updateValues=new ContentValues();
updateValues.put("hotelname", hotelname);
updateValues.put("city", city);
updateValues.put("desc", desc);
updateValues.put("rooms", rooms);
updateValues.put("price", price);
updateValues.put("image", image);
return db.update("Hotel_info", updateValues, "hotelname" + "="
+hotelname, null);
}
And AdminActivity Class:
sqLiteHelper.updatedetails( edtName.getText().toString().trim(),
edtcity.getText().toString().trim(),
edtdesc.getText().toString().trim(),
edtrooms.getText().toString().trim(),
edtPrice.getText().toString().trim(),
imageViewToByte(imageView));
}
});
Try this code:
String[] hotelname= new String[]{hotelname};
db.update("Hotel_info", updateValues, "hotelname=?" , hotelname,null);
Related
Sorry if this is a stupid question but I am new to Android Development. I am trying to create a login screen which will direct doctors to a one activity and nurses to another activity when they login. This does not seem to work. I have put code into the login.java class:
btLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String email = loginemail.getText().toString();
String password = loginpassword.getText().toString();
Boolean Chkemailpass = db.emailpassword(email, password);
if(Chkemailpass == true) {
Cursor typeofuser;
typeofuser = db.checkUser(loginemail.getText().toString()); //get user type from database
if(typeofuser.equals("Nurse")) {
Intent mainintent = new Intent(Login.this, NurseHome.class);
startActivity(mainintent);}
else if (typeofuser.equals("Doctor")){
Intent intent = new Intent(Login.this, DoctorHome.class);
startActivity(intent);}
}
else
Toast.makeText(getApplicationContext(),"Wrong email or password", Toast.LENGTH_SHORT).show();
}
});
}
}
And I also have this code in the databasehelper class relating to the usertype:
public Cursor checkUser(String email) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("SELECT TYPEOFUSER from user_table WHERE EMAIL=email", null);
return res;
}
All help would be appreciated, thank you.
The argument email of checkUser() is a string, so in your sql statement it should be enclosed inside single quotes like this:
SELECT TYPEOFUSER from user_table WHERE EMAIL = 'email'
but the correct way to pass parameters to rawQuery() is with the use of ? placeholders and the use of the 2nd argument as an array of string parameters (instead of null).
Also don't return the Cursor, but the type of user as a String from checkUser().
So change to this:
public String checkUser(String email) {
String result = "";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(
"SELECT TYPEOFUSER from user_table WHERE EMAIL = ?",
new String[] {email}
);
if (res.moveToNext()) {
result = res.getString(0);
}
res.close();
return result;
}
and instead of:
Cursor typeofuser;
typeofuser = db.checkUser(loginemail.getText().toString());
use this:
String typeofuser = db.checkUser(loginemail.getText().toString());
This question already has answers here:
Android Cursor Index out of Bound Exception
(3 answers)
Closed 6 years ago.
I'm trying to retrieve data from sqlite data base but but when I call the nameData() logcat shows the exception:
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
I don't understand why, any clues?
process:
public class SearchContactByName2 extends AppCompatActivity {
String dbString="",dbString2="";
SQLiteDatabase db;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.searchcontactbynamelayout2_main);
TextView textView=(TextView)findViewById(R.id.textViewShowName);
TextView textView2=(TextView)findViewById(R.id.textView2ShowNumber);
SearchContactByName objOfSearchContactByName=new SearchContactByName();
ContactDatabase onbOfContactDatabase=new ContactDatabase(getBaseContext());
Cursor allcontact2= onbOfContactDatabase.nameData(objOfSearchContactByName.getNameForSearchTypeString);
allcontact2.moveToFirst();
do{
dbString+=allcontact2.getString(allcontact2.getColumnIndex("name"));
dbString2+=allcontact2.getString(allcontact2.getColumnIndex("phone"));
dbString+="\n";
dbString2+="\n";
textView.setText(dbString);
textView2.setText(dbString2);
}while(allcontact2.moveToNext());
Toast.makeText(getBaseContext(), "data", Toast.LENGTH_LONG).show();
}
}
database part:
public class ContactDatabase extends SQLiteOpenHelper {
SQLiteDatabase db;
public static final String DATABASE_NAME="totalContact.db";
public static final String TABLE_NAME="mecontact";
public static final String NAME="name";
public static final String PHONE="phone";
public ContactDatabase(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("create table mecontact" +
"(id integer primary key autoincrement, name text, phone text)");
}catch(android.database.SQLException e){
System.out.println("table create nhi ho rha");
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS mecontact");
onCreate(db);
}
public void insertContact(String nam,String mob){
db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(NAME,nam);
contentValues.put(PHONE,mob);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public Cursor showData(){
db=this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM mecontact", null);
return res;
}
public Cursor nameData(String dataName){
db=this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM mecontact WHERE name = '"+dataName+"'", null);
return res;
}
}
try below code
if(allcontact2.moveToFirst()){
do{
dbString+=allcontact2.getString(allcontact2.getColumnIndex("name"));
dbString2+=allcontact2.getString(allcontact2.getColumnIndex("phone"));
dbString+="\n";
dbString2+="\n";
textView.setText(dbString);
textView2.setText(dbString2);
}while(allcontact2.moveToNext());}
Toast.makeText(getBaseContext(), " no data", Toast.LENGTH_LONG).show();
actually your database has no data
Cursor allcontact2= onbOfContactDatabase.nameData(objOfSearchContactByName.getNameForSearchTypeString);
if(allcontact2.size() > 0){
while(allcontact2.moveToNext()){
dbString+=allcontact2.getString(allcontact2.getColumnIndex("name"));
dbString2+=allcontact2.getString(allcontact2.getColumnIndex("phone"));
dbString+="\n";
dbString2+="\n";
textView.setText(dbString);
textView2.setText(dbString2);
}
Toast.makeText(getBaseContext(), "data", Toast.LENGTH_LONG).show();
}
Along with the answer by sush change nameData method to,
public Cursor nameData(String dataName){
db=this.getReadableDatabase();
//String dataname might contain special characters like a quote
//retreive the cursor this way
Cursor res=db.query("mecontact",new String[]{columnsYouwantToSelect},"name =?",new String[]{dataName},null,null,null);
//if you want to select all the columns in the table replace
//the second parameter with null
return res;
}
Not really answering your question, but more advice on how to prevent trouble in the future. I would suggest you change your oncreate code to this and declare your ID value in the top like you did for the others. This will make sure the database is created correctly and that in the future if changes happen you can easily get values without making typing errors. Code like this is safer to use than pure queries.
db.execSQL("CREATE TABLE "
+ TABLE_NAME
+ " (" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ NAME + " TEXT,"
+ PHONE + " TEXT);" );
I have used a database class, datamodel class and main activity in my application. I am not populating spinner values from sqlite database but I am storing selected spinner values in db. I have a text entry too. I declared datamodel object separately.
StudentModel student=new StudentModel();
I have used this is at two diff places.The first one inside Onclick(text)
if(v == findViewById(R.id.add)){
tv.setText("");
student.name = name.getText().toString();
}
The next inside OnItemSelected(Spinner)
student.subject=subject.getItemAtPosition(position).toString();
In the databasehelper class I insert value like
public long addStudentDetail(StudentModel student) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_SUBJECT, student.subject);
values.put(KEY_NAME, student.name);
long insert = db.insert(TABLE_STUDENT, null, values);
return insert;
}
And in the databasehelper class I retrieve them like
if (c.moveToFirst()) {
do {
StudentModel students = new StudentModel();
students.id = c.getInt(c.getColumnIndexOrThrow(KEY_ID));
students.name = c.getString(c.getColumnIndexOrThrow(KEY_NAME));
students.subject = c.getString(c.getColumnIndexOrThrow(KEY_SUBJECT));
studentsArrayList.add(students);
} while (c.moveToNext());
}
I get java.lang.IllegalArgumentException: column 'subject' does not exist while running.
I am currently working from a project used in a tutorial that displays contacts in a listview. All the fields in the database are used and saved as strings. A custom adapter class is being used for the edit and delete buttons - the buttons appear on the listview, per item. Clicking on edit leads to a separate activity to in which details for that record are parsed in.
I have added another button that I'd like to update a record when clicked and reload the activity. When you press the button it calls a method from the connector method:
public void updateContact(long id, String name, String phone, String mail,
String fb, byte[] blob) {
ContentValues cv = new ContentValues();
cv.put(Contacts.NAME, name);
cv.put(Contacts.PHONE, phone);
cv.put(Contacts.MAIL, mail);
cv.put(Contacts.FB, fb);
cv.put(Contacts.IMAGE, blob);
db = sqlHp.getWritableDatabase();
db.update(Contacts.TABLE, cv, Contacts.ID + "=" + id, null);
db.close();
}
I would like phone to convert the string to an integer, increment the value by 1 and then save using contentvalues as a string. Here is what I've tried:
public void updateContact(long id, String name, String phone,
String mail, String fb, byte[] blob) {
ContentValues cv = new ContentValues();
cv.put(Contacts.NAME, name);
int phone1 = 0;
phone1 = (Integer) cv.getAsInteger(Contacts.PHONE);
phone1++;
phone = String.valueOf(phone1);
cv.put(Contacts.PHONE, phone);
cv.put(Contacts.MAIL, mail);
cv.put(Contacts.FB, fb);
cv.put(Contacts.IMAGE, blob);
db = sqlHp.getWritableDatabase();
db.update(Contacts.TABLE, cv, Contacts.ID + "=" + id, null);
db.close();
}
This gives me a null pointer exception error. I'm not sure where to go from here.
This is the method from the custom adapter which holds the onclick method
setPresent = (ImageButton) v.findViewById(R.id.setPresent);
setPresent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sqlCon.updateContact(id, name, phone, email, fb, image);
Intent intent = new Intent(context, MyContactsActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
It's when I click this button the null pointer exception error occurs. These are the lines it flags up:
sqlCon.updateContact(id, name, phone, email, fb, image);
- from the customadapter
and
phone1 = (Integer) cv.getAsInteger(Contacts.PHONE);
- from the connector
This part doesn't really make sense in your code:
ContentValues cv = new ContentValues();
int phone1 = (Integer) cv.getAsInteger(Contacts.PHONE);
You are trying to get Contacts.PHONE from a ContentValues you just created.
Perhaps you wanted to do something like this instead:
cv.put(Contacts.PHONE, Integer.parseInt(phone) + 1);
If you clean up this part, the NullPointerException will probably disappear naturally.
Also, it's safer to update tables using ? placeholders for parameters instead of puttin them in the query string, like this:
db.update(Contacts.TABLE, cv, Contacts.ID + " = ?", new long[]{id});
I'm currently developing an android app with eclipse. I got a problem while updating the database. The problem is the app crash while the updateFlag method is called. The updateFlag method only update one specific column only based on the rowId.
This is my database structure in SQLiteAdapter class:
public long insert(String answer, String question, String hint, String flag, String level){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_ANSWER, answer);
contentValues.put(KEY_QUESTION, question);
contentValues.put(KEY_HINT, hint);
contentValues.put(KEY_FLAG, flag);
contentValues.put(KEY_LEVEL, level);
return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
}
This is the update method in SQLiteAdapter class:
public void updateFlag(long rowId)
{
ContentValues args = new ContentValues();
args.put(KEY_FLAG, "1");
sqLiteDatabase.update(MYDATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null);
}
And this is how I call the updateFlag method in another class:
mySQLiteAdapterListener2 = new SQLiteAdapter(this);
mySQLiteAdapterListener2.openToWrite();
long idListener = Long.parseLong(getId);
mySQLiteAdapterListener2.updateFlag(idListener);
mySQLiteAdapterListener2.close();
What's wrong with my code? Anyone know how to update one specific column based on rowId in the right way?
SQLiteDatabase update method takes four arguments:
database.update(String table_name, ContentValues values, String selection, String[] selectionArgs);
So, your query should be like in your below updateFlag method. Replace your updateFlag method with this one and try this.
public void updateFlag(long rowId)
{
ContentValues args = new ContentValues();
args.put(KEY_FLAG, "1");
sqLiteDatabase.update(MYDATABASE_TABLE, args, KEY_ROWID + "=?", new String[]{rowId+""});
}
Try this:
sqLiteDatabase.update(MYDATABASE_TABLE, args, KEY_ROWID + "=?", new String[] {rowId});
The last parameters if for passing the values that will replace the '?'.
This assumes you have a problem with your update. You need to post a stacktrace so we can see where the app is crashing.