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});
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 app crashes when clicking on an item in the list view
(1 answer)
Android: Cannot perform this operation because the connection pool has been closed
(9 answers)
Closed 4 years ago.
Something is wrong with the cursor carrying data issue, debugging, i got that "java.lang.IllegalStateException: Cannot perform this operation because the connection pool has been closed.".
But i still can't adjust the cursor issue, i know that connection shouldn't be closed before cursor returning data, but i can't figure out how to adjust it.
I want to take some info from getEmpData method, and then pass it.
my method:
public Cursor getEmpData(Integer employeeID)
{
EmpDept = getReadableDatabase();
Integer[] empRow = {employeeID};
Cursor c = EmpDept.rawQuery("Select name, Title, phone, email from Employee where EmpID like ?", new String[]{employeeID.toString()});
if (c != null)
{
c.moveToFirst();
}
EmpDept.close();
return c;
}
List view part:
When name is clicked it should move the data to new activity.
namelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String name = namelist.getItemAtPosition(position).toString();
//Getting ID of emp,dept
Cursor empID = Emp.getEmpID(name);
Cursor DepID = Emp.getDeptID(name);
int eID = empID.getInt(0);
int dID = DepID.getInt(0);
Intent intent = new Intent(MainActivity.this, empDetails.class);
intent.putExtra("empName", Emp.getEmpData(eID).toString());
intent.putExtra("empTitle",Emp.getEmpData(eID).toString());
intent.putExtra("empPhone",Emp.getEmpData(eID).toString());
intent.putExtra("empEmail",Emp.getEmpData(eID).toString());
intent.putExtra("empDept",Emp.getDeptName(dID).toString());
startActivity(intent);
}
});
use this code :
public Employee getEmpData(Integer employeeID)
{
EmpDept = getReadableDatabase();
Integer[] empRow = {employeeID};
Cursor c = EmpDept.rawQuery("Select name, Title, phone, email, dept from Employee where EmpID like ?", new String[]{employeeID.toString()});
Employee employee = new Employee();
if (c != null && c.getCount() > 0 && c.moveToFirst())
{
employee.setName(c.getString(0));
employee.setTitle(c.getString(1));
employee.setPhone(c.getString(2));
employee.setEmail(c.getString(3));
employee.setDept(c.getString(4));
}
c.close();
return employee;
}
your list part :
Intent intent = new Intent(MainActivity.this, empDetails.class);
Employee employee = Emp.getEmpData(eID);
intent.putExtra("empName", employee.getName());
intent.putExtra("empTitle",employee.getTitle());
intent.putExtra("empPhone",employee.getPhone());
intent.putExtra("empEmail",employee.getEmail());
intent.putExtra("empDept",employee.getDept());
and Employee is an object including name, title, phone, email, dept and their getter and setters.
I am developing an android app with Firebase, so saving data to Firebase with .push method and displaying them into list , i want to update the UserInfo stored in database but confused how i can access push method generated Key to update profile info , or any other way to setting profile info under the Authenticated user ID and read all this data so it will update on the list i am displaying.
or any other method to access this by User_id in child values?
myOnBtnClick code below
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Validation()) {
final String name = Field_fullName.getText().toString();
String phone = firebaseUser.getPhoneNumber();
String bg = field_bloodGroups.getSelectedItem().toString();
String DOB = Field_dateOfBirth.getText().toString();
String state = Field_state.getText().toString();
final String country = Field_country.getText().toString();
String city = Field_city.getText().toString();
UserSignUp userSignUp = new UserSignUp(name, phone, bg, DOB, state, country, city, firebaseUser.getUid());
DBref.child("DONORS").child(country).push().setValue(userSignUp).addOnCompleteListener(reg.this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(reg.this, DBref.getKey() + "", Toast.LENGTH_SHORT).show();
Toast.makeText(reg.this, "User Created", Toast.LENGTH_SHORT).show();
editor = sharedPreference.edit();
editor.putInt("UserReg", 1);
editor.putString("UserCountry", country);
editor.putInt("FirstTimeRun", 1);
editor.apply();
startActivity(new Intent(reg.this, Main2Activity.class));
finish();
}
}
});
}
}
});
When you are using the push() method to generate that unique key, is the moment in which you can get and store the key like this:
String key = yourRef.getKey();
And to update a record please use the following line of code:
FirebaseDatabase.getInstance().getReference()
.child("Pakistan")
.child(key)
.child("user_ID")
.setValue("123456789");
Edit:
DatabaseReference keyRef = DBref.child("DONORS").child(country).push();
String key = keyRef.getKey();
Log("TAG", key);
keyRef.setValue(userSignUp).addOnCompleteListener(/* ... */);
Once you have this key, you can use it in other DatabaseReference. When you are using DBref.getKey() inside onComplete() method isn't getting the pushed key is just getting the key of your DBref.
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);
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.