I use this code to update a contact's address, but it only works for contacts that have an existing address. If the contact address field is empty, the update() method returns zero and the contact data is not updated. How do I add an address to an existing contact?
//str_id is the contact's ID
//input is the String representing an address
ContentValues cv = new ContentValues();
String[] params = new String[] { str_id, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };
cv.put(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, input);
getContentResolver().update(ContactsContract.Data.CONTENT_URI, cv, ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?", params);
I have also tried the equivalent logic with a ContentProviderOperation, but get the same result. Just like my previous example, I can update an existing address but cannot create an address.
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, id)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, input)
.build());
You need to check whether Adress exist or not before updating Address,
If address exist your above code will work fine as you are doing just update..
While doing insert address, actually you are doing a child insert" see here, Very good explanation of ContentProviderOperation which relates to your issue closely..
Related
I have a weird sqlite problem, partly Flutter partly Android... I have a database that I create in Flutter. When I insert a new row and I save it, I want to retrieve it in Android and send the values to a broadcast receiver. I am using this query: "SELECT * FROM " + TABLE_NAME + " ORDER BY " + COLUMN_ID + " DESC LIMIT 1"; This works great when creating the first row, but after that my broadcast receiver only ever receives the value of the last but one row, not the last row.
This is my code on the Java side, to get the details from the sqlite database and send them to the receiver:
public void getScheduleFromFlutter() {
String setting = "";
DatabaseHandler db = new DatabaseHandler(this);
Cursor cursor = db.getValues();
if (cursor.moveToFirst())
setting = cursor.getString(cursor.getColumnIndex(COLUMN_SETTING));
Intent intent = new Intent(this, Schedules.class);
intent.putExtra("SETTING", setting);
sendBroadcast(intent);
cursor.close();
db.close();
}
Any ideas?
You might have some issues in the query to retrieve the last row.
However if you re inserting values in table with Sqflite.
When inserting a value:
// Insert the Dog into the correct table. You might also specify the
// `conflictAlgorithm` to use in case the same dog is inserted twice.
//
// In this case, replace any previous data.
await db.insert(
'dogs',
dog.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
The method insert returns a future with the ID of new column.
// INSERT helper
Future<int> insert(String table, Map<String, dynamic> values,
{String nullColumnHack, ConflictAlgorithm conflictAlgorithm});
You can then send this ID instead or query the table with this ID to get the entry you need.
I am new to Selenium. I am testing a user registration form in which i have to verify if the data is inserted into database or not. I am using following code to check. Is there any better option than this? I am first checking if registration ID is inserted and it it is then checking other details.
#Test
public void testVerifyListOfRecords() throws InterruptedException {
String query = "SELECT ID FROM usermaster WHERE RegistrationNumber = '" + REGNO + "' ";
String ID = DatabaseConnector.executeSQLQuery("QA", query);
if(ID == ""){
STATUS = "FALSE";
System.out.println("REGISTRATION NUMBER IS NOT INSERTED..!! TEST FAILED..!!");
} else STATUS = "TRUE";
String sqlQuery = "SELECT FirstName,LastName,SpecialityCode,QualificationCode FROM usermaster WHERE ID = '" + ID + "' ";
List<String> listOfDBValues = new ArrayList<String>();
listOfDBValues = DatabaseConnector.executeSQLQuery_List("QA", sqlQuery);
List<String> Branch = new ArrayList<>();
Branch.add(listOfDBValues.get(0));
List<String> list1 = new ArrayList<>(Arrays.asList("testfirstname testlastname ORP DM"));
Assert.assertEquals(STATUS, "TRUE");
System.out.println("STATUS IS " + STATUS);
Assert.assertEquals(Branch, list1);
}
This is not really a Selenium question... it's more of an automation and/or database question. Selenium only interacts with a browser. If you have no other way to verify if the user was registered and that is a requirement, then querying the database seems like the most straightforward way to verify it.
There are several things I would change to make this function better/more efficient.
You seem to be using a lot of global variables, e.g. STATUS, REGNO. This is generally not a good practice. Pass into the function what it needs.
Unless I'm missing something, you can be more efficient with your variable usage. You have a couple cases in this short function where you have a value already in a variable, store in it another variable, and then assert it's value. There's no need to put it into a new variable, just assert it's value from the initial variable. This minimizes lines of code and gets rid of unneeded variables which makes the code easier to read and understand.
Pick the best data type for each variable. For example, you are storing "TRUE"/"FALSE" in a String when you should be using boolean. Don't create a List<String> and only add one item... just use a String variable.
Assert early and often. You don't assert the value of STATUS until the end of the function but you knew the value of STATUS in the first few lines of code and you hit the database afterwards. You should have asserted the value of STATUS right when you got it to fail the test as soon as possible and avoid extra hits to the db, additional code, etc.
You have several sysouts that are redundant with your asserts. There's no need to sysout the value of STATUS if it's right after an assert that would fail if it's anything but "TRUE".
Asserts have an optional message parameter. Use it. Add a comment on what the assert is testing, e.g. "Verifying ID is not empty" so that when it fails one day you will know from the logs what it was verifying. Make it descriptive and useful so that if all you had was that message, you would know what it was testing and possibly why it might have failed.
Here's how I would clean this up
#Test
public void testVerifyListOfRecords(String regNo) throws InterruptedException
{
String query = "SELECT ID FROM usermaster WHERE RegistrationNumber = '" + regNo + "' ";
String ID = DatabaseConnector.executeSQLQuery("QA", query);
Assert.assertFalse(ID == "", "Verify ID is not empty");
String sqlQuery = "SELECT FirstName,LastName,SpecialityCode,QualificationCode FROM usermaster WHERE ID = '" + ID + "' ";
List<String> listOfDBValues = DatabaseConnector.executeSQLQuery_List("QA", sqlQuery);
List<String> list1 = new ArrayList<>(Arrays.asList("testfirstname testlastname ORP DM"));
Assert.assertEquals(listOfDBValues.get(0), list1, "Verify user registration data is correct");
}
I am making a app that incorporates login/register functionalities and I'm making a issue that I have been trying to solve.
When a user logins and the login is successful, I'd like to use the email that they signed in with to pass to the next activity using Intent (I checked that the email is in fact getting passed by displaying what is being passed through the intent) and then passing that email to a function in the Dbhelper that uses that email to look for the name of the person that signed in then displaying "Welcome (name of person)" in the current activity but I keep getting a null returned in the function which ultimately leads to the app crashing.
Here is where I'm calling the function in the activity where I want to display the name.
if(!session.loggedIn())
{
Logout();
}
else
{
Intent in = getIntent();
String email = in.getStringExtra("email");
Name.setText("Welcome " + db.findName(email));
}
And this is the function in my DbHelper.java where I'm looking for the name with a query and such.
public String findName(String user_email)
{
String query = "SELECT " + COLUMN_NAME + " FROM " + USER_TABLE + " WHERE " + COLUMN_EMAIL + " = " + "'" + user_email + "'";
SQLiteDatabase db = this.getWritableDatabase();
//reads for database
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
if(c.getCount() > 0) // if cursor is not empty
{
String n = c.getString(0);
return n;
}
else
{
return null;
}
}
As you can see, it's returning null. And yes there is entries in the database already. Also, I tried just passing the email to the function and returning what was passed and it still gave me an error.
Normally, to check for a value in a text column, you do not use the equal = sign, but rather WHERE Column LIKE '%text%'. Also, when saving to a database you should escape and "sanitize" strings. If you did this, then you should also be doing the same process when looking for them, else you won't find them.
I am telling you this since, even if you are sure there are entries in your table, the result of the query may be empty. You could just debug by printing the result of the c.getCount() call or something.
I am trying to fetch only those contacts for which birthday or anniversary information is available. However, I only found way to get contacts with phone number, but my app needs only contacts with birthday/anniversary information available and sorted in their upcoming birthdays order.
I am showing the results in ListView.
I need proper query to get around this problem, I tried googling and stackoverflow but found no solution.
Here is the code I'm using to get the information about contacts:
Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
String SORT_ORDER = ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY + " ASC ";
// Querying the table ContactsContract.Contacts to retrieve all the contacts
Cursor contactsCursor = getContentResolver().query(contactsUri,
null,
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1",
null,
ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
if (contactsCursor.moveToFirst()) {
do {
long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex("_ID"));
Uri dataUri = ContactsContract.Data.CONTENT_URI;
String[] projection1 ={
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Event.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.DATA2,
ContactsContract.Contacts.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Phone.DATA1,
ContactsContract.CommonDataKinds.Phone.DATA15
};
// Querying the table ContactsContract.Data to retrieve individual items like
// home phone, mobile phone, work email etc corresponding to each contact
String selection =
ContactsContract.Data.CONTACT_ID + "=" + contactId;
Cursor dataCursor = getContentResolver().query(
dataUri,
projection1, //projection
selection, //selection
null,
null);
////some code here
} while (dataCursor.moveToNext());
////some more code
// Adding id, display name, path to photo and other details to cursor
mMatrixCursor.addRow(new Object[]{Long.toString(contactId), displayName, photoPath, details});
}
} while (contactsCursor.moveToNext());
}
return mMatrixCursor;
}
I am getting all the required information correctly and having no problem with that, however I'm struggling in finding proper query to show only contacts with birthdays and sorting them in proper order as birthdays are not always stored in proper format. Thanks in advance !
I have a SQLite DB with a table called "students". In the students table, there are 2 columns: "student_id" and "student_name".
I am trying to delete a row from an SQLite table using this code:
String TABLE_STUDENTS = "students";
String COLUMN_STUDENTNAME= "student_name";
public void deleteUser(String name) {
database.delete(TABLE_STUDENTS, COLUMN_STUDENTNAME + "=" + name, null);
}
However, when I try to delete the user "John" I get this error message from LogCat
12-19 16:28:47.132: E/SQLiteLog(14883): (1) no such column: John
I was trying to follow the example here: Deleting Row in SQLite in Android, but I could swear my syntax is the same.
Guessing I am doing something stupid, but anyone able to help? Thanks.
You may try:
database.delete(TABLE_STUDENTS,COLUMN_STUDENTNAME +" = ?", new String[] { name });
What you are doing is sending the equivalent statement DELETE FROM students WHERE student_name=John, which is why it is looking for a column called John. You need to use the third parameter of the method to provide the argument, so:
final String[] deleteConditions = new String[]{ name };
database.delete(TABLE_STUDENTS, COLUMN_STUDENTNAME + "=?", deleteConditions);
Note that you can delete multiple rows by adding more entries to the array deleteConditions.
That works, although I would recommend
db.delete(TABLE, "column_name=?", new String[] { String.valueOf(custname) });
or use
String query = "DELETE FROM " +TABLE_NAME+ " WHERE " + COLUM_NAME+ " = " + "'"+VALUE +"'" ;
db.execSQL(query);