Android how to get attendance name and emails from events - android

I have tried to get attendance name and emails using belwo code, but still not working.
Cursor cur = contentResolver.query(CalendarContract.Attendees.CONTENT_URI, new String[]{Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_RELATIONSHIP, Attendees.ATTENDEE_EMAIL}, Attendees.EVENT_ID +"= "+Long.parseLong("10"), null, null);
if(cur!=null){
SapGenConstants.showLog("cur size: "+cur.getCount());
while(cur.moveToNext()){
attendee_status = cur.getString(cur.getColumnIndex(Attendees.ATTENDEE_STATUS));
attendee_name = cur.getString(cur.getColumnIndex(Attendees.ATTENDEE_RELATIONSHIP));
attendee_Email = cur.getString(cur.getColumnIndex(Attendees.ATTENDEE_EMAIL));
SapGenConstants.showLog("attendee_status 2: "+attendee_status);
SapGenConstants.showLog("attendee_name 2: "+attendee_name);
SapGenConstants.showLog("attendee_Email 2: "+attendee_Email);
}
cur.close();
}

This is how you do it:
final String[] attendeeProjection = new String[]{
CalendarContract.Attendees._ID,
CalendarContract.Attendees.EVENT_ID,
CalendarContract.Attendees.ATTENDEE_NAME,
CalendarContract.Attendees.ATTENDEE_EMAIL,
CalendarContract.Attendees.ATTENDEE_TYPE,
CalendarContract.Attendees.ATTENDEE_RELATIONSHIP,
CalendarContract.Attendees.ATTENDEE_STATUS
};
final String query = "(" + CalendarContract.Attendees.EVENT_ID + " = ?)";
final String[] args = new String[]{"YOUR_EVENT_ID"};
final Cursor cursor = contentResolver.query(CalendarContract.Attendees.CONTENT_URI, attendeeProjection, query, queryArgs, sortOrder);
cursor.moveToFirst();
while (cursor.moveToNext()) {
// process the cursors
}
Since these queries are IO operations, it is advised to call them on a non-UI thread; my tip would be to go with RxJava.
If you don't want to work with cursors and queries (and a lot of boilerplate code), take a look at the CalendarWrapper library. It takes care of mapping objects and database rows to and from, CRUD operations can be performed with object methods. For example, this is how you'd query all attendees for an event ID:
final String query = "(" + CalendarContract.Attendees.EVENT_ID + " = ?)";
final String[] args = new String[]{"YOUR_EVENT_ID"};
final List<Attendee> attendees = Attendee.getAttendeesForQuery(query, args, null, getContentResolver());

i just ran into the same issue - and it was because of a mixup between the instance id and the event id, two distinct elements.
The important thing is that the attendees table is based on the EVENT id - and not the instance id - so it may explain your problem. Where do you get the hardcoded "10" from ?
If it's an instance id, then extract the EVENT id of the event series it belongs to, and pass that on to the ATTENDEES table. See if that helps.

Related

Why Sqlite return only last row not all rows data?

I don't know what's wrong with my code I follow the rule but I get wrong result. I want to search db and find all rows data but I only get last row from sqlite. my code to search database is bellow:
public ArrayList<ArrayList<ContractSaveDataFromDB>> ActiveContractData(String phone, String numberId)
{
ArrayList<ContractSaveDataFromDB> UserData = new ArrayList<ContractSaveDataFromDB>();
ArrayList<ArrayList<ContractSaveDataFromDB>> SendUserData =
new ArrayList<ArrayList<ContractSaveDataFromDB>>();
SQLiteDatabase db = this.getReadableDatabase();
String whereClause = "phone = ? AND numberId = ?";
String[] whereArgs = new String[]{
phone,
numberId
};
String orderBy = "activeContract";
Cursor res2=db.query("usersAccount",null,whereClause,whereArgs,null,null,orderBy);
res2.moveToFirst();
do{
UserData.clear();
int index;
ContractSaveDataFromDB contractSaveDataFromDB=new ContractSaveDataFromDB();
index = res2.getColumnIndex("buyAmount");
String buyAmount = res2.getString(index);
contractSaveDataFromDB.setBuyAmount(buyAmount);
UserData.add(contractSaveDataFromDB);
SendUserData.add(UserData);
} while(res2.moveToNext());
res2.close();
db.close();
return SendUserData;
I don't know what's wrong. I appreciate if you help me to solve my problem.
you already added where clause so maybe it is filtering your results try to remove it by change this
Cursor res2=db.query("usersAccount",null,whereClause,whereArgs,null,null,orderBy);
to this
Cursor res2=db.query("usersAccount",null,null,null,null,null,orderBy);
I believe that your issues is that you are trying to use an ArrayList of ArrayList of ContractSaveDataFromDB objects.
I believe that an ArrayList of ContractSaveDataFromDB objects would suffice.
It would also help you if you learnt to do a bit of basic debugging, as an issue could be that you are not extracting multiple rows.
The following is an alternative method that :-
uses the ArrayList of ContractSaveDataFromDB objects,
introduces some debugging by the way of writing some potentially useful information to the log
and is more sound, as it will not crash if no rows are extracted
i.e. if you use moveToFirst and don't check the result (false means the move could not be accomplished) then you would get an error because you are trying to read row -1 (before the first row) as no rows exists in the cursor.
:-
public ArrayList<ContractSaveDataFromDB> ActiveContractData(String phone, String numberId) {
ArrayList<ContractSaveDataFromDB> SendUserData = new ArrayList<ContractSaveDataFromDB>();
SQLiteDatabase db = this.getReadableDatabase();
String whereClause = "phone = ? AND numberId = ?";
String[] whereArgs = new String[]{
phone,
numberId
};
String orderBy = "activeContract";
Cursor res2 = db.query("usersAccount", null, whereClause, whereArgs, null, null, orderBy);
Log.d("RES2 COUNT", "Number of rows in Res2 Cursor is " + String.valueOf(res2.getCount()));
while (res2.moveToNext()) {
ContractSaveDataFromDB current_user_data = new ContractSaveDataFromDB();
current_user_data.setBuyAmount(res2.getString(res2.getColumnIndex("buyAmount")));
Log.d("NEWROW", "Adding data from row " + String.valueOf(res2.getPosition()));
SendUserData.add(current_user_data);
}
res2.close();
db.close();
Log.d("EXTRACTED", "The number of rows from which data was extracted was " + String.valueOf(SendUserData.size()));
return SendUserData;
}
If after running you check the log you should see :-
A line detailing how many rows were extracted from the table
A line for each row (if any were extracted) saying Adding data from row ? (where ? will be the row 0 being the first)
A line saying The number of rows from which data was extracted was ? (? will be the number of elements in the array to be returned)

I can't get data from database using cursor

I have make following function for getting data.
public List<Presentation> getSlideMaster() {
List<Presentation> pptList = new ArrayList<Presentation>();
String selectQuery = "SELECT * FROM "
+ Constants.SLIDE_MASTER.slideMaster_Table + " WHERE dm_Id=" + lastDeckID;
SQLiteDatabase db = dbhelper.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Presentation presentation = new Presentation();
presentation.setSlideId(cursor.getString(0));
getSlideID = presentation.getSlideId();
Log.i("string slide id in database helper", "" + presentation.getSlideId());
pptList.add(presentation);
} while (cursor.moveToNext());
}
String selectQuery2 = "SELECT sl_Id FROM "
+ Constants.SLIDE_LAYOUT.slideLayout_Table + " WHERE sm_Id = "
+ getSlideID;
Cursor cursorSL = db.rawQuery(selectQuery2, null);
Log.i("query", ""+selectQuery2);
if(cursorSL.moveToFirst()){
Log.i("getslideLayout function", "");
do{
Log.i("query string 0 ", ""+cursorSL.getString(0));
Presentation presentation = new Presentation();
presentation.setSlideLayoutId(cursorSL.getString(0));
getSlideLayoutId = presentation.getSlideLayoutId();
Log.i("string slide layout id in slideMaster", "" + getSlideLayoutId);
}while(cursorSL.moveToNext());
}
else{
Log.i("No Data Found!!!!!", "");
}
cursor.close();
cursorSL.close();
db.close();
return pptList;
}
I getting data from slideMaster_Table very fine and easily but I can't get data from another query, which is not print any value in Logcat inside of if(cursorSL.moveToFirst()) condition
When I use code in another activity i can get sl_Id very easily.
may below solution solve your problem
use Cursor cursorSL = db.rawQuery(selectQuery2, new String[]{getSlideID});
for
selectQuery2="SELECT sl_Id FROM "+Constants.SLIDE_LAYOUT.slideLayout_Table + " WHERE sm_Id = ?";
My speculation is that you have troubles constructing the second query. Basically it is never a good idea to construct database queries like you do. The android database API is providing more accurate interface for that. Rewrite your second part of program to:
String [] selectArgs = {getSlideID};
String selectQuery2 = "sm_Id = ?";
Cursor cursorSL = db.query(Constants.SLIDE_LAYOUT.slideLayout_Table, null,
selectQuery2, selectArgs, null, null, null, null);
Note that the fourth parameter of query is meant for substitution of where arguments, it is String[] and all the array members are substituted in sequence in the places of ? in the query string.
I think you might be facing problem with constructing the query.
PS: You are also misusing the log tags:
Log.i("No Data Found!!!!!", "");
Should actually be Log.i("TAG", "No Data Found!!!!!");
The first parameter is log tag and is supposed to be used for grouping related log messages, in your case you print every message in its own group, which does not make much sense.
I know this note will not solve your immediate problem, but I am pointing it out, so that you will know it for the future (I also suffer from seeing colleagues of mine learning from SO wrong practises like that one).

Update row in SQlite database by row position in android

I have database which contains "date" column and "item" column.
I want that user could update specific row in the database.
I trying to do it with update method in SQLiteDatabase class.
My problem is that i dont know how to make update method find exactly the row i want.
I saw some example that use it with parameters from one word.
like this:
ourDatabase.update(tableName, cvUpdate, rowId + "=" + item , null);
My problem is that i want to update the row that have specific item and date. so the name of the item alone is not enough.
I tried this code below but its didnt work, hope youll can help me.
public void updateEntry(String item, String date) throws SQLException{
String[] columns = new String[]{myItem, myDate};
Cursor c = ourDatabase.query(tableName, columns, null, null, null, null, null);
long position;
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(date, myDate);
cvUpdate.put(item, myExercise);
int itemAll = c.getColumnIndex(myItem);
int dateAll = c.getColumnIndex(myDate);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
if (c.getString(itemAll).equals(myItem) && c.getString(dateAll).equals(myDate))
{
position = c.getPosition();
break;
}
}
ourDatabase.update(tableName, cvUpdate, rowId + "=" + position , null);
}
First, the columns String[] is supposed to contain column names, such as "_ID", or whatever are the column names you have used. Given that you compare the content of the column myItem with the object myItem, I assume there is a confusion somewhere here.
Secondly, rowId and position are different things in SQL, especially if you delete rows, as the row id usually is autoincrement, and especially since your query is not explicitely sorted. Replacing c.getPosition() by c.getLong(c.getColumnIndex(ID_COLUMN)) would make more sense.
Thirdly, sql is nice because you can query it. For example, rather than get all items and loop to find the matching date and item, you can :
String whereClause = ITEM_COLUMN + " = ? and " + DATE_COLUMN + " = ?";
String[] whereArgs = new String[] { item, date };
Cursor c = ourDatabase.query(tableName, columns, whereClause, whereArgs, null, null, null);
instead of your for loop.
Forthly, you can even make the query in the update :
String whereClause = ITEM_COLUMN + " = ? and " + DATE_COLUMN + " = ?";
String[] whereArgs = new String[] { item, date };
ourDatabase.update(tableName, cvUpdate, whereClause, whereArgs);
Extra tip: use full caps variable names for contants such as column names, it help with readability.

Updating a single column is creating sqlite syntax error

I'm not sure what I'm doing wrong, but I'm trying to update a single integer value in a column of a table to 1 from 0. When creating the database, I set all values of the column to zero using:
for (int i = 0; i < setups.length; i++) {
ContentValues values = new ContentValues();
values.put(JokeDbContract.TblJoke.COLUMN_NAME_SETUP, setups[i]);
values.put(JokeDbContract.TblJoke.COLUMN_NAME_PUNCHLINE, punchlines[i]);
values.put(JokeDbContract.TblJoke.COLUMN_NAME_USED, 0);
db.insert(JokeDbContract.TblJoke.TABLE_NAME, null, values);
}
Then, in the actual activity, I'm doing:
private void findNewJoke() {
JokeDb jokeDb = JokeDb.getInstance(this);
SQLiteDatabase theDb = jokeDb.getDB();
String selection = JokeDbContract.TblJoke.COLUMN_NAME_USED + "=" + 0;
// Query database for a joke that has not been used, update the fields
// theJoke and thePunchline appropriately
String[] columns = {JokeDbContract.TblJoke._ID,
JokeDbContract.TblJoke.COLUMN_NAME_PUNCHLINE,
JokeDbContract.TblJoke.COLUMN_NAME_SETUP,
JokeDbContract.TblJoke.COLUMN_NAME_USED};
Cursor c = theDb.query(JokeDbContract.TblJoke.TABLE_NAME, columns, selection,
null, null, null, null);
if (c.moveToFirst() == false) {
Toast.makeText(this, R.string.error_retrieving_joke, Toast.LENGTH_LONG).show();
Log.e(getString(R.string.app_name),"No jokes retreived from DB in JokeActivity.findNewJoke()!");
}
else {
ContentValues values = new ContentValues();
theSetup = c.getString(c.getColumnIndexOrThrow(JokeDbContract.TblJoke.COLUMN_NAME_SETUP));
thePunchline = c.getString(c.getColumnIndexOrThrow(JokeDbContract.TblJoke.COLUMN_NAME_PUNCHLINE));
String updateSelection = JokeDbContract.TblJoke.COLUMN_NAME_SETUP + "=" + theSetup;
values.put(JokeDbContract.TblJoke.COLUMN_NAME_USED, 1);
theDb.update(JokeDbContract.TblJoke.TABLE_NAME, values, updateSelection, null);
}
}
I'm getting an error on the update:
java.lang.RuntimeException: .... while compiling: UPDATE jokes SET used=?
WHERE setup=Why do programmers always mix up Halloween and Christmas?
It seems as though I'm not getting an actual value set for the used column. What the program ultimately does is cycle through jokes where used=0, then sets used to 1 when it has been viewed. So the query only pulls those jokes that aren't used yet. I have a feeling I'm missing something simple, one can hope.
I think you are having problems with quotation marks.
Example:
String updateSelection = JokeDbContract.TblJoke.COLUMN_NAME_SETUP + "=\"" + theSetup + "\"";
However, the recommended way to do this, would be:
theDb.update(JokeDbContract.TblJoke.TABLE_NAME, values, JokeDbContract.TblJoke.COLUMN_NAME_SETUP + " = ?", new String[] { theSetup });
It is better to use field = ?, because this helps sqlite cache queries (I believe).

passing parameter of _id and updating SQLitedatabase

I'm trying to update an SQLite table using the row id as my where statement. I'm getting the row _id from a row shown in a listview and passing to another activity with this statement:
Cursor cursor = (Cursor) nurseTableAdapter.getItem((int)id);
showAssignments.putExtra("Nurse", cursor.getInt(cursor.getColumnIndex("_id")));
The receiving activity receives the parameter:
nurse = extras.getString("Nurse");
and passes it as a parameter to my DbCommunicator class:
updateAssignments.updateNurseAssignments(listItemsArray, nurse);
and my DbCommunicator class does this with it:
public void updateNurseAssignments(String[] choices, String nurseId) {
// set parameter variables
//int nurseIdToInt = Integer.parseInt(nurseId);
//String strFilter = "_id=" + nurseIdToInt;
//String where = "_id=?";
String[] whereArgs = {String.valueOf(nurseId)};
Log.i(TAG, "value of whereArgs is " + whereArgs[0]);
// set content values
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_FIRST_ASSIGNMENT, choices[0]);
cvUpdate.put(KEY_SECOND_ASSIGNMENT, choices[1]);
cvUpdate.put(KEY_THIRD_ASSIGNMENT, choices[2]);
cvUpdate.put(KEY_FOURTH_ASSIGNMENT, choices[3]);
cvUpdate.put(KEY_FIFTH_ASSIGNMENT, choices[4]);
cvUpdate.put(KEY_SIXTH_ASSIGNMENT, choices[5]);
// update database
sqldb.update(NURSE_TABLE, cvUpdate, KEY_NURSE_ROWID + "= ?", whereArgs);
}
I'm getting no errors, but the table is not updating. I've only found one similar example in Stack Overflow, and have tried to incorporate some of that here, but still having problems. Suggestions appreciated.

Categories

Resources