i trying to search in database whether the id is exist or not, when it exist i open the next activity , but when it not exist the app crash.. i coundnt find the bug , error Cursor Index out of bound
Database dbc = new Database(this);
dbc.open();
String id = searchId.getText().toString();
boolean checkId = dbc.isGotId(id);
if(checkId == true){
String s = searchId.getText().toString();
Bundle b = new Bundle();
b.putString("key",s);
b.putInt("keyX", radioBtnFlag);
Intent a = new Intent(SearchUpdate.this, UpdateDelete.class);
a.putExtras(b);
startActivity(a);
searchId.setText(null);
}else if(checkId == false){
Log.v(id, id + "2222222");
Dialog d = new Dialog(this);
d.setTitle("Error!");
TextView tv = new TextView(this);
tv.setText("This Search is allow only ID! "+ radioBtnFlag);
d.setContentView(tv);
d.show();
searchId.setText(null);
and here ...
public boolean isGotId(String id){
boolean result = false;
try{
Cursor sId = ourDatabase.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + Pro_ID + "=" + id, null);
result = true;
}catch(SQLiteException e)
{
result = false;
}//catch
return result;
}//isGOtId
Try this...
public boolean isGotId(String id){
Cursor sId = ourDatabase.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " +
Pro_ID + "=" + id, null);
int numberOfRows = sId.getCount();
if(numberOfRows <= 0)
{
return false;
}
return true;
}
try{
Cursor sId = ourDatabase.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + Pro_ID + "=" + id, null);
if(sId.moveToFirst() && sId ! = null)
result = true;
}catch(SQLiteException e)
{
result = false;
}
Related
I need (for practicing reasons) to change all the contacts to be starred. So I use this code to read all the contacts in a thread:
Looper.prepare(); //To avoid error: Can't create handler inside thread that has not called Looper.prepare
CursorLoader oCursorLoader = new CursorLoader(ContextoGlobal, ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
Cursor oCursor = oCursorLoader.loadInBackground();
int contactId = oCursor.getColumnIndex(ContactsContract.Contacts._ID);
contactId = oCursor.getColumnIndex(ContactsContract.RawContacts._ID);
int starred = oCursor.getColumnIndex(ContactsContract.Contacts.STARRED);
int number = oCursor.getColumnIndex(ContactsContract.Contacts.Data.DATA1);
int name = oCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
oCursor.moveToFirst();
if(oCursor.isAfterLast()==false) {
do {
String sId = oCursor.getString(contactId);
String phNumber = oCursor.getString(number);
String phName = oCursor.getString(name);
String sStarred = oCursor.getString(starred);
String s = sId + "\n" + phName + "\n" + phNumber + "\nStarred: " + sStarred;
} while (oCursor.moveToNext());
}
This code works and iterates through all the contacts in the device, displaying if they are starred or not.
My problem comes when I want to modify the starred field in the loop:
...
do {
String sId = oCursor.getString(contactId);
String phNumber = oCursor.getString(number);
String phName = oCursor.getString(name);
String sStarred = oCursor.getString(starred);
String s = sId + "\n" + phName + "\n" + phNumber + "\nStarred: " + sStarred;
ChangeStarred(sId, true); <-- HERE!!!!!!!!
} while (oCursor.moveToNext());
...
This is the ChangeStarred() function:
private boolean ChangeStarred(String sContactId, boolean bStarred){
ContentValues values = new ContentValues();
if(bStarred==true)
values.put(ContactsContract.Contacts.STARRED, 1);
else
values.put(ContactsContract.Contacts.STARRED, 0);
//int iAffectedRows = ContextoGlobal.getContentResolver().update(ContactsContract.Contacts.CONTENT_URI, values, ContactsContract.Contacts._ID + "= ?", new String[] { sContactId });
int iAffectedRows = ContextoGlobal.getContentResolver().update(ContactsContract.Contacts.CONTENT_URI, values, ContactsContract.RawContacts._ID + "= ?", new String[] { sContactId });
if(iAffectedRows == 0)
return false;
return true;
}
This function always returns FALSE. No rows are updated.
As you can see in the code comments, I have tried with Contacts._ID and RawContacts._ID
I also have WRITE_CONTACTS permission granted.
This is how I solved:
Looper.prepare(); //To avoid error: Can't create handler inside thread that has not called Looper.prepare
CursorLoader oCursorLoader = new CursorLoader(ContextoGlobal, ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
Cursor oCursor = oCursorLoader.loadInBackground();
int contactId = oCursor.getColumnIndex(ContactsContract.Contacts._ID);
int starred = oCursor.getColumnIndex(ContactsContract.Contacts.STARRED);
int name = oCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
oCursor.moveToFirst();
if(oCursor.isAfterLast()==false) {
do {
String sId = oCursor.getString(contactId);
String phName = oCursor.getString(name);
String sStarred = oCursor.getString(starred);
String s = sId + "\n" + phName + "\n" + "\nStarred: " + sStarred;
ChangeStarred(sId, true);
} while (oCursor.moveToNext());
}
And the ChangeStarred() function:
private boolean ChangeStarred(String sContactId, boolean bStarred) {
ContentValues contentValues = new ContentValues();
if(bStarred==true)
contentValues.put(ContactsContract.Contacts.STARRED, 1);
else
contentValues.put(ContactsContract.Contacts.STARRED, 0);
int iAffectedRows = ContextoGlobal.getContentResolver().update(ContactsContract.Contacts.CONTENT_URI, contentValues, ContactsContract.Contacts._ID + "=" + sContactId, null);
if(iAffectedRows > 0)
return true;
return false;
}
I am working on a code snippet where i am storing my json encoded data into a txt file,and using following method to separate all parts and adding them into database.
public boolean addAnswersFromJSONArray() {
boolean flag = false;
Answer answer = new Answer();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "user_live.txt");
FileReader fr;
JsonReader reader;
try {
fr = new FileReader(file);
reader = new JsonReader(fr);
reader.beginArray();
reader.setLenient(true);
while (reader.hasNext()) {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("product_name")) {
answer.setProductName(reader.nextString());
} else if (name.equals("subject")) {
answer.setSubject(reader.nextString());
} else if (name.equals("month")) {
answer.setMonth(reader.nextString());
} else if (name.equals("year")) {
answer.setYear(reader.nextString());
} else if (name.equals("question")) {
answer.setQuestion(reader.nextString());
} else if (name.equals("answer")) {
answer.setAnswer(reader.nextString());
} else if (name.equals("question_no")) {
answer.setQuestion_no(reader.nextString());
} else if (name.equals("marks")) {
answer.setMarks(reader.nextString());
} else {
reader.skipValue();
}
}
answer.save(db);
reader.endObject();
flag = true;
}
reader.endArray();
reader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
file.delete();
db.close();
}
return flag;
}
and then i am retrieving each fields departments,subjects,month and year,questions,answers,question_no, but while retrieving marks i am getting only unique entries that is 10 and 5....Ideally the size of one set is 18 so i m getting ArrayIndexoutOfBounds Exception.
//database calling part
marks = db.getMarksList(department, subject, month_year);
database method is,
public String[] getMarksList(String department, String subject,
String month_year) {
String month = month_year.split("-")[0];
String year = month_year.split("-")[1];
String whereClause = DEPARTMENT + " = '" + department + "'" + " AND "
+ SUBJECT + " = '" + subject + "' AND " + MONTH + " = '"
+ month + "' AND " + YEAR + " = '" + year + "'";
System.out.println("questions: " + whereClause);
Cursor cursor = db.query(true, "ANSWERS", new String[] { "MARKS" },
whereClause, null, null, null, "DEPARTMENT", null);
String list[] = new String[cursor.getCount()];
int i = 0;
if (cursor != null && cursor.getCount() > 0) {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
.moveToNext()) {
list[i] = new String(cursor.getString(0));
i++;
}
}
return list;
}
Can anyone help me to resolve this issue?? Why getting only unique value,I have checked my json result also each row contains marks.
i got the solution for this,
Changed database query and method as following,
public List<Answer> getMarksList(String department, String subject,
String month_year) {
List<Answer> list = new ArrayList<Answer>();
String month = month_year.split("-")[0];
String year = month_year.split("-")[1];
try {
String sql1 = "select all marks from " + TABLE_NAME
+ " where department = '" + department
+ "' AND subject = '" + subject + "' AND month = '" + month
+ "' AND year = '" + year + "';";
SQLiteDatabase db1 = this.getWritableDatabase();
Cursor cursor = db1.rawQuery(sql1, null);
if (cursor.moveToFirst()) {
do {
Answer a = new Answer();
a.setMarks(cursor.getString(0));
list.add(a);
} while (cursor.moveToNext());
}
} catch (Exception e) {
}
return list;
}
using "all" in query is retrieving all records.
please help me in this issue. I am developing an application which works with a big database in android. The problem is that I need to do big procedures to get some specific info, but the application takes too long to respond and the screen goes black until solve the problem. I put an AsyncTask while it finds the response, but nothing seems to work.
This is a example method.
public ArrayList<SGN_PROMOCIONES> SearchPromos(int p_cabped_id,
int p_agrup_id, int cli_id) {
int li_aplica = 0;
int li_nro_agrup;
// le asignamos por el momento el id del cliente que seleccionamos
InformacionProceso inP = new InformacionProceso();
int ld_clie_id = 0;
int ld_promo_id;
int ld_promo_id1;
String lv_descripcion_corta;
char lv_aplica_a;
String lv_aplica_aS;
String lv_indicador_evaluar;
String lv_indicador_articulo_evaluar;
String lv_otorga_puntos;
String lv_indicador_obsequio;
int ld_maximo_obsequio;
String ld_indicador_aleatorio_id;
String lv_estado;
String lv_actividad;
String lv_canal;
String lv_subcanal;
String lv_automatica_sn;
Cursor c = db
.rawQuery(
"SELECT id,descripcion_corta,aplica_a,indicador_evaluar,indicador_articulo_evaluar,otorga_puntos,indicador_obsequio,maximo_obsequio,indicador_aleatorio_id,automatica_sn FROM sgn_promociones ORDER BY id;",
null);
if (c.moveToFirst()) {
do {
li_aplica = 0;
ld_clie_id = cli_id;
ld_promo_id = c.getInt(0);
lv_descripcion_corta = c.getString(1);
lv_aplica_aS = c.getString(2);
lv_indicador_evaluar = c.getString(3);
lv_indicador_articulo_evaluar = c.getString(4);
lv_otorga_puntos = c.getString(5);
lv_indicador_obsequio = c.getString(6);
ld_maximo_obsequio = c.getInt(7);
ld_indicador_aleatorio_id = c.getString(8);
lv_automatica_sn = c.getString(9);
ld_promo_id1 = 0;
String s1 = "SELECT DISTINCT sg_promo_id FROM sgn_bitacoras_promocion WHERE sg_cabped_id = "
+ p_cabped_id
+ " AND sg_promo_id = "
+ ld_promo_id
+ " AND estado = 'IUS' AND activo_inactivo = 'A'";
Cursor c1 = db.rawQuery(s1, null);
if (c1.moveToFirst()) {
ld_promo_id1 = c1.getInt(0);
} else {
ld_promo_id1 = 0;
}
c1.close();
if (ld_promo_id1 == 0)
lv_estado = "I";
else
lv_estado = "A";
lv_aplica_a = lv_aplica_aS.charAt(0);
switch (lv_aplica_a) {
case 'T':
s1 = "SELECT COUNT(a.nomenclatura) FROM sgn_rutas a,sgn_territorios b,sgn_padrones c,sgn_target_promocion d WHERE a.sg_terri_id = b.id AND a.nomenclatura = c.sg_ruta_nomenclatura AND d.id = b.id AND d.sg_promo_id = "
+ ld_promo_id + " AND c.sg_clie_id =" + ld_clie_id;
c1 = db.rawQuery(s1, null);
if (c1.moveToFirst()) {
li_aplica = c1.getInt(0);
} else {
li_aplica = 0;
}
c1.close();
break;
case 'R':
s1 = "SELECT COUNT(a.nomenclatura) FROM sgn_rutas a,sgn_padrones b,sgn_target_promocion c WHERE a.nomenclatura = b.sg_ruta_nomenclatura AND c.id = a.nomenclatura AND c.sg_promo_id = "
+ ld_promo_id + " AND b.sg_clie_id = " + ld_clie_id;
c1 = db.rawQuery(s1, null);
if (c1.moveToFirst()) {
li_aplica = c1.getInt(0);
} else {
li_aplica = 0;
}
c1.close();
break;
case 'N':
s1 = "SELECT COUNT(cl.id) FROM sgn_clientes cl,sgn_target_promocion tp WHERE cl.id = "
+ ld_clie_id
+ " AND cl.sg_nac_actividad = SUBSTRING(tp.id,1,1) AND cl.sg_nac_canal = SUBSTRING(tp.id,2,3) AND cl.sg_nac_subcanal = SUBSTRING(tp.id,5,3) AND tp.sg_promo_id = "
+ ld_promo_id;
c1 = db.rawQuery(s1, null);
if (c1.moveToFirst()) {
li_aplica = c1.getInt(0);
} else {
li_aplica = 0;
}
c1.close();
break;
case 'C':
s1 = "SELECT COUNT(id) FROM sgn_target_promocion WHERE sg_promo_id = "
+ ld_promo_id + " AND id = " + ld_clie_id;
c1 = db.rawQuery(s1, null);
if (c1.moveToFirst()) {
li_aplica = c1.getInt(0);
} else {
li_aplica = 0;
}
c1.close();
break;
case 'I':
s1 = "SELECT COUNT(a.nomenclatura) FROM sgn_rutas a,sgn_padrones b,sgn_target_promocion c WHERE a.nomenclatura = b.sg_ruta_nomenclatura AND c.id = a.sg_tiprut_tipo AND c.sg_promo_id = "
+ ld_promo_id + " AND b.sg_clie_id = " + ld_clie_id;
c1 = db.rawQuery(s1, null);
if (c1.moveToFirst()) {
li_aplica = c1.getInt(0);
} else {
li_aplica = 0;
}
c1.close();
break;
case 'P':
s1 = "SELECT COUNT(a.sg_clie_id) FROM sgn_clientes_plan_comercial a,sgn_target_promocion c WHERE a.sg_clie_id = "
+ ld_clie_id
+ " AND c.id = a.sg_placom_id AND c.sg_promo_id = "
+ ld_promo_id;
c1 = db.rawQuery(s1, null);
if (c1.moveToFirst()) {
li_aplica = c1.getInt(0);
} else {
li_aplica = 0;
}
c1.close();
break;
case '*':
li_aplica = 1;
break;
}
if (li_aplica > 0) {
if (p_agrup_id == 0
|| lv_indicador_articulo_evaluar.equals("P")) {
s1 = "INSERT INTO TempSGN_PEDIDOS VALUES("
+ ld_promo_id + ", '" + lv_descripcion_corta
+ "' ,'" + lv_estado + "' ,'"
+ lv_indicador_evaluar + "' ,'"
+ lv_indicador_articulo_evaluar + "' ,'"
+ lv_indicador_obsequio + "' ,"
+ ld_maximo_obsequio + " ,'" + lv_otorga_puntos
+ "' ,'" + lv_automatica_sn + "')";
db.execSQL(s1);
} else if (lv_indicador_articulo_evaluar.equals("I")) {
s1 = "SELECT COUNT(epr.id) FROM sgn_promociones pr,sgn_evaluar_promocion epr,sgn_agrupamientos_articulo aa WHERE pr.id = epr.sg_promo_id AND epr.id = aa.articulo_id AND aa.sg_detagr_id = "
+ p_agrup_id + " AND pr.id = " + ld_promo_id;
c1 = db.rawQuery(s1, null);
if (c1.moveToFirst()) {
li_aplica = c1.getInt(0);
} else {
li_aplica = 0;
}
c1.close();
if (li_aplica > 0) {
s1 = "INSERT INTO TempSGN_PEDIDOS VALUES("
+ ld_promo_id + ", '"
+ lv_descripcion_corta + "' ,'" + lv_estado
+ "' ,'" + lv_indicador_evaluar + "' ,'"
+ lv_indicador_articulo_evaluar + "' ,'"
+ lv_indicador_obsequio + "' ,"
+ ld_maximo_obsequio + " ,'"
+ lv_otorga_puntos + "' ,'"
+ lv_automatica_sn + "')";
db.execSQL(s1);
}
} else if (lv_indicador_articulo_evaluar.equals("A")) {
s1 = "SELECT COUNT(epr.id) FROM sgn_promociones pr,sgn_evaluar_promocion epr WHERE pr.id = epr.sg_promo_id AND pr.id = "
+ ld_promo_id;
c1 = db.rawQuery(s1, null);
if (c1.moveToFirst()) {
li_nro_agrup = c1.getInt(0);
} else {
li_nro_agrup = 0;
}
c1.close();
s1 = "SELECT art.id,art.descripcion_corta,COUNT(epr.id) nro_grupos FROM sgn_promociones pr,sgn_evaluar_promocion epr,"
+ "sgn_agrupamientos_articulo aa,articulos art WHERE pr.id = epr.sg_promo_id AND epr.id = aa.sg_detagr_id AND aa.articulo_id = art.id AND aa.articulo_id IN( SELECT articulo_id "
+ "FROM sgn_agrupamientos_articulo WHERE sg_detagr_id = "
+ p_agrup_id
+ ") AND pr.id = "
+ ld_promo_id
+ " GROUP BY art.id,art.descripcion_corta";
int nroGruposT = 0;
Cursor c21 = db.rawQuery(s1, null);
if (c21.moveToFirst()) {
do {
if (c21.getInt(2) == li_nro_agrup) {
nroGruposT++;
}
} while (c21.moveToNext());
}
li_aplica = nroGruposT;
c21.close();
if (li_aplica > 0) {
s1 = "INSERT INTO TempSGN_PEDIDOS VALUES("
+ ld_promo_id + ", '"
+ lv_descripcion_corta + "' ,'" + lv_estado
+ "' ,'" + lv_indicador_evaluar + "' ,'"
+ lv_indicador_articulo_evaluar + "' ,'"
+ lv_indicador_obsequio + "' ,"
+ ld_maximo_obsequio + " ,'"
+ lv_otorga_puntos + "' ,'"
+ lv_automatica_sn + "')";
db.execSQL(s1);
}
}
}
} while (c.moveToNext());
}
ArrayList<SGN_PROMOCIONES> promociones = new ArrayList<SGN_PROMOCIONES>();
Cursor c3 = db.rawQuery("Select * from TempSGN_PEDIDOS ORDER BY DESCRIPCION_CORTA", null);
if (c3.moveToFirst()) {
do {
SGN_PROMOCIONES promo = new SGN_PROMOCIONES();
promo.setID(c3.getInt(0));
promo.setDESCRIPCION_CORTA(c3.getString(1));
promo.setESTADO(c3.getString(2));
promo.setINDICADOR_EVALUAR(c3.getString(3));
promo.setINDICADOR_ARTICULO_EVALUAR(c3.getString(4));
promo.setOTORGA_PUNTOS(c3.getString(5));
promo.setINDICADOR_OBSEQUIO(c3.getString(6));
promo.setMAXIMO_OBSEQUIO(c3.getInt(7));
promo.setAUTOMATICA_SN(c3.getString(8));
promociones.add(promo);
} while (c3.moveToNext());
}
return promociones;
}
In order to process huge SQLite Database in Android, you have to use Custom Loaders. It improves the Database Performance.
To understand the concept of loader check this. To implement it, check this tutorial to set-up Custom loaders or you can find more about it in this Video.
Hope this works for you.
Thanks everyone! I solved my issue, only trying to make all the selects in one, because it consumes a lot of memory open and close a cursor.
I want to retrive the data of last added event from android calendar. I am using this code to get last id.
public static long getNewEventId(ContentResolver cr, Uri cal_uri)
{
Uri local_uri = cal_uri;
if (cal_uri == null)
{
local_uri = Uri.parse("content://com.android.calendar/events");
}
Cursor cursor = cr.query(local_uri,
new String[] { "MAX(_id) as max_id" }, null, null, "_id");
cursor.moveToFirst();
long max_val = cursor.getLong(cursor.getColumnIndex("max_id"));
return max_val + 1;
}
And then I simply add an event using this code:
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", SelectedDate);
intent.putExtra("allDay", false);
intent.putExtra("rrule", "FsREQ=DAILY");
intent.putExtra("endTime", SelectedDate + 60 * 60 * 1000);
intent.putExtra("title", "Advance Scheduler Event");
startActivity(intent);
After this I simply retrieve the data of this event using this code:
public CalendarData EventDetails(int ID)
{
CalendarData temp = null;
// -------------------------------------------------------------------------------
ContentResolver cr = getContentResolver();
Cursor cursor_calendar;
if (Integer.parseInt(Build.VERSION.SDK) >= 8)
{
cursor_calendar = cr.query(
Uri.parse("content://com.android.calendar/calendars"),
new String[] { "_id", "displayname" }, null, null, null);
}
else
{
cursor_calendar = cr.query(
Uri.parse("content://calendar/calendars"), new String[] {
"_id", "displayname" }, null, null, null);
}
cursor_calendar.moveToFirst();
String[] CalNamess = new String[cursor_calendar.getCount()];
int[] CalIdss = new int[cursor_calendar.getCount()];
for (int i = 0; i < CalNamess.length; i++)
{
CalIdss[i] = cursor_calendar.getInt(0);
CalNamess[i] = cursor_calendar.getString(1);
cursor_calendar.moveToNext();
}
cursor_calendar.close();
// -------------------------------------------------------------------------------
Cursor cursor_event;
if (Integer.parseInt(Build.VERSION.SDK) >= 8)
{
cursor_event = cr.query(
Uri.parse("content://com.android.calendar/events"),
new String[] { "calendar_id", "title", "description",
"dtstart", "dtend", "eventLocation" }, null, null,
null);
}
else
{
cursor_event = cr.query(Uri.parse("content://calendar/events"),
new String[] { "calendar_id", "title", "description",
"dtstart", "dtend", "eventLocation" }, null, null,
null);
}
boolean flag = false;
String add = null;
cursor_event.moveToFirst();
String[] CalNames = new String[cursor_event.getCount()];
int[] CalIds = new int[cursor_event.getCount()];
for (int i = 0; i < CalNames.length; i++)
{
CalIds[i] = cursor_event.getInt(0);
if (ID == CalIds[i])
{
flag = true;
Toast.makeText(getApplicationContext(),
"ID Found : " + CalIds[i], Toast.LENGTH_LONG).show();
CalNames[i] = "Event"
+ cursor_event.getInt(0)
+ ": \nTitle: "
+ cursor_event.getString(1)
+ "\nDescription: "
+ cursor_event.getString(2)
+ "\nStart Date: "
+ cursor_event.getLong(cursor_event
.getColumnIndex("dtstart"))
+ cursor_event.getLong(cursor_event
.getColumnIndex("dtend"))
+ cursor_event.getString(5);
temp = new CalendarData();
temp.Title = cursor_event.getString(1);
temp.Description = cursor_event.getString(2);
// temp.StartDate = new Date(cursor_event.getLong(3));
// temp.EndDate = new Date(cursor_event.getLong(4));
temp.StartDate = cursor_event.getLong(cursor_event
.getColumnIndex("dtstart"));
temp.EndDate = cursor_event.getLong(cursor_event
.getColumnIndex("dtend"));
temp.Location = cursor_event.getString(5);
break;
}
cursor_event.moveToNext();
}
return temp;
}
But I can't get the data of this event. I am not getting where is the problem. Please, help me to solve this.
use this code. its working in my aap
public long GetMaxID(ContentResolver cr, Uri cal_uri, Context context)
{
Uri local_uri = cal_uri;
if (cal_uri == null)
{
// local_uri = Uri.parse("content://calendar/calendars/" +
// "events");
local_uri = Uri.parse("content://com.android.calendar/events");
}
Cursor cursor = cr.query(local_uri, new String[]
{ "MAX(_id) as max_id" }, null, null, "_id");
cursor.moveToFirst();
long max_val = cursor.getLong(cursor.getColumnIndex("max_id"));
return max_val + 1;
}
public static CalendarData GetEventDetails(String ID, Context context)
{
CalendarData temp = null;
ContentResolver contentResolver = context.getContentResolver();
// Fetch a list of all calendars synced with the device, their display
// names and whether the
cursor = contentResolver.query(
Uri.parse("content://com.android.calendar/calendars"),
(new String[]
{ "_id", "displayName", "selected" }), null, null, null);
HashSet<String> calendarIds = new HashSet<String>();
try
{
System.out.println("Count=" + cursor.getCount());
if (cursor.getCount() > 0)
{
System.out
.println("the control is just inside of the cursor.count loop");
while (cursor.moveToNext())
{
String _id = cursor.getString(0);
String displayName = cursor.getString(1);
Boolean selected = !cursor.getString(2).equals("0");
System.out.println("Id: " + _id + " Display Name: "
+ displayName + " Selected: " + selected);
calendarIds.add(_id);
}
}
}
catch (AssertionError ex)
{
ex.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
// For each calendar, display all the events from the previous week to
// the end of next week.
// for (String id : calendarIds)
for (int id = 0; id <= calendarIds.size(); id++)
{
Uri.Builder builder = Uri.parse(
"content://com.android.calendar/instances/when")
.buildUpon();
// Uri.Builder builder =
// Uri.parse("content://com.android.calendar/calendars").buildUpon();
long now = new Date().getTime();
ContentUris
.appendId(builder, now - DateUtils.DAY_IN_MILLIS * 10000);
ContentUris
.appendId(builder, now + DateUtils.DAY_IN_MILLIS * 10000);
Cursor eventCursor = contentResolver.query(builder.build(),
new String[]
{ "_id", "title", "begin", "end", "allDay" },
"Calendars._id=" + id, null, null);
System.out.println(id + " eventCursor count="
+ eventCursor.getCount());
if (eventCursor.getCount() > 0)
{
eventCursor.moveToFirst();
while (eventCursor.moveToNext())
{
Object mbeg_date, beg_date, beg_time, end_date, end_time;
final String eventID = eventCursor.getString(0);
final String title = eventCursor.getString(1);
final Date begin = new Date(eventCursor.getLong(2));
final Date end = new Date(eventCursor.getLong(3));
final Boolean allDay = !eventCursor.getString(4)
.equals("0");
if (eventID.equals(ID))
{
temp = new CalendarData();
temp.Title = eventCursor.getString(1);
temp.StartDate = eventCursor.getLong(2);
temp.EndDate = eventCursor.getLong(3);
break;
}
}
}
// break;
}
return temp;
}
I used the following code to retrieve all the data on the Calendar which is:
cr = getApplicationContext().getContentResolver();
caluri=CalendarContract.Events.CONTENT_URI;
atteuri=CalendarContract.Attendees.CONTENT_URI;
try
{
cur1 = cr.query(caluri, new String[]{Events.CALENDAR_ID,Events._ID, Events.TITLE, Events.DESCRIPTION,Events.DTSTART, Events.DTEND, Events.EVENT_LOCATION }, null, null, null);
if(cur1!=null){
while(cur1.moveToNext()){
cal_ID=cur1.getString(cur1.getColumnIndex(Events.CALENDAR_ID));
event_ID=cur1.getString(cur1.getColumnIndex(Events._ID));
cur2=cr.query(atteuri,new String[]{Attendees.ATTENDEE_NAME,Attendees.ATTENDEE_EMAIL}, Attendees.EVENT_ID +"=" +event_ID, null, null);
if(cur2!=null){
while(cur2.moveToNext()){
event_Title=cur1.getString(cur1.getColumnIndex(Events.TITLE));
event_Desc=cur1.getString(cur1.getColumnIndexOrThrow(Events.DESCRIPTION));
event_Start=new Date(cur1.getLong(cur1.getColumnIndex(Events.DTSTART)));
event_end=new Date(cur1.getLong(cur1.getColumnIndex(Events.DTEND)));
event_loc=cur1.getString(cur1.getColumnIndex(Events.EVENT_LOCATION));
attendee_name=cur2.getString(cur2.getColumnIndex(Attendees.ATTENDEE_NAME));
attendee_Email=cur2.getString(cur2.getColumnIndex(Attendees.ATTENDEE_EMAIL));
all_attendee +="\n"+attendee_name;
all_Emails +="\n"+attendee_Email;
}
cur2.close();
}
all +="Event title: " + event_Title + "\n" + "Event Description: " + event_Desc + "\n" +"Event Start: " + event_Start + "\n" + "Events End: " + event_end + "\n" + "Event Location: " + event_loc + "\n" + "Attendees: " + "\n" + all_attendee + "\n" + "Emails: "+ "\n" + all_Emails + "\n";
}
cur1.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
SO all what you need as I guess is to adjust it little bit get data for last event.
ContentResolver cr = getContentResolver();
Uri caluri = CalendarContract.Events.CONTENT_URI;
Uri atteuri = CalendarContract.Attendees.CONTENT_URI;
Cursor cur1, cur2;
String all = null;
try
{
cur1 = cr.query(caluri
, new String[]{ Events.CALENDAR_ID, Events._ID, Events.TITLE, Events.DESCRIPTION, Events.DTSTART, Events.DTEND, Events.EVENT_LOCATION }
, null, null, null);
if (cur1 != null)
{
while (cur1.moveToNext())
{
String event_Title = cur1.getString(cur1.getColumnIndex(Events.TITLE));
String event_Desc = cur1.getString(cur1.getColumnIndexOrThrow(Events.DESCRIPTION));
Date event_Start = new Date(cur1.getLong(cur1.getColumnIndex(Events.DTSTART)));
Date event_end = new Date(cur1.getLong(cur1.getColumnIndex(Events.DTEND)));
String event_loc = cur1.getString(cur1.getColumnIndex(Events.EVENT_LOCATION));
String all_attendee = null;
String all_Emails = null;
String cal_ID = cur1.getString(cur1.getColumnIndex(Events.CALENDAR_ID));
String event_ID = cur1.getString(cur1.getColumnIndex(Events._ID));
cur2 = cr.query(atteuri, new String[]{ Attendees.ATTENDEE_NAME, Attendees.ATTENDEE_EMAIL }
, Attendees.EVENT_ID + "=" + event_ID, null, null);
if (cur2 != null)
{
while (cur2.moveToNext())
{
String attendee_name = cur2.getString(cur2.getColumnIndex(Attendees.ATTENDEE_NAME));
String attendee_Email = cur2.getString(cur2.getColumnIndex(Attendees.ATTENDEE_EMAIL));
all_attendee += "\n" + attendee_name;
all_Emails += "\n" + attendee_Email;
}
cur2.close();
}
all += "Event title: " + event_Title + "\n"
+ "Event Description: " + event_Desc + "\n"
+ "Event Start: " + event_Start + "\n" + "Events End: "
+ event_end + "\n" + "Event Location: " + event_loc
+ "\n" + "Attendees: " + "\n" + all_attendee + "\n"
+ "Emails: " + "\n" + all_Emails + "\n";
}
cur1.close();
}
System.out.println("My log--------" + all);
Im running into an issue inserting items into my database. It really odd that the program will run through 4 rows and insert them fine, but on the 5th row it crashes and I got three reports of Application did not close cursor or database. In my code I am closing and reopening both the cursor and the database so I am really confused on how this is happening. Here is the code.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case REQUEST_CODE_NEW:
if (resultCode == -1) {
Integer chapterId = data.getIntExtra("chapterId", -1);
Toast toast = Toast.makeText(this, "Selected Chapter: " + chapterId.toString(), Toast.LENGTH_LONG);
if (chapterId != -1) {
DbHelper db = new DbHelper(this);
for (int i = 0; i < questions.getTitle().size(); i++) {
db.insertQuestion(chapterId.toString(), questions.getTitle().get(i), questions.getAnswer().get(i), questions.getAr().get(i));
}
}
toast.show();
}
break;
}
}
Thats calling the database to be created through a dbhelper class. Here is the database helper
public void insertQuestion(String cat_id, String title, String answer, String article) {
db.execSQL("INSERT INTO " + QUESTION_TABLE_NAME + " (title,answer,article,picture) VALUES ('" + title + "','" + answer + "','" + article + "','none')");
String id = getQuestionId(title);
db.execSQL("INSERT INTO " + REL_TABLE_NAME + " (question_id, cat_id) VALUES (" + id + "," + cat_id + ")");
}
public String getQuestionId(String title) {
String id;
cursor = this.db.rawQuery("SELECT question_id FROM " + QUESTION_TABLE_NAME + " WHERE title = '" + title + "' LIMIT 1", null);
cursor.moveToFirst();
id = cursor.getString(0);
cursor.close();
db.close();
return id;
}
I put the cursor at the class level so I can try to manage it better, but still to no avail. Its still crashing after 4 queries.
Try this "fix":
DbHelper db = new DbHelper(this);
try{
for (int i = 0; i < questions.getTitle().size(); i++) {
db.insertQuestion(chapterId.toString(), questions.getTitle().get(i), questions.getAnswer().get(i), questions.getAr().get(i));
}
}catch(Exception e1){
android.util.Log.v("DbHelper Error","Crash: "+e1.getMessage(), e1);
}finally{
db.close();
}