how to use SerialExecutor with AsyncTask (API < 11) - android

I've an app that is used by carers to sign in to the system using their android phones. They scan a QRcode or swipe an NFC tag to get the client's information, scan time and location. The latter info constitutes a transaction. The transaction is placed in the phone's DB as well as submitted to a server via HTTP.
All works well as all transactions are put in DB and posted to web service until i have to make two transactions at the same time. A transaction is made by calling AsyncTask as it's a network call and so not to block UI thread. Both transactions are made to the web service but not all the data is sent to DB. I've commented out some code and made one Async post at a time and the data is then sent fine.
The problem
When one AsyncTask is running the other starts. When this happens the first AsyncTask doesn't work correctly. I have found the following thread where there is a similar problem and using a SerialExecutor seems to be the answer.
serialexecutor
https://stackoverflow.com/questions/6645203/android-asynctask-avoid-multiple-instances-running
Could anyone help me implement the 2 following AsyncTasks in a SerialExecutor, I'm fairly new to Android and i'm struggling to start this off. I'd like apd to execute and finish then apd3 to execute after. All in a serial fashion.
Thanks in advance Matt
String temp_tagType = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_TYPE));
String temp_tagCompId = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_COMPANY_ID));
String temp_PersonId = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_PERSON_ID));
String temp_tagName = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_NAME));
String temp_tagId = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_TAG_ID));
String temp_tagScanTime = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_TAG_SCAN_TIME));
String temp_tagLatitude = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_TRANSACTIONS_LATITUDE));
String temp_tagLongitude = cursor.getString(cursor
.getColumnIndex(LoginValidate.C_TRANSACTIONS_LONGITUDE));
if(temp_tagId == null){
temp_tagId = "notag";
}
String manualM = "M";
Log.e(TAG, " temp name and status = " + temp_tagName + " " + manualM);
////////insert the temp variables with the status set to M
ContentValues values = new ContentValues();
values.putNull(LoginValidate.C_ID);
values.put(LoginValidate.C_TYPE, temp_tagType);
values.put(LoginValidate.C_COMPANY_ID, nfcscannerapplication.getCompId());
values.put(LoginValidate.C_PERSON_ID, temp_PersonId);
values.put(LoginValidate.C_NAME, temp_tagName);
values.put(LoginValidate.C_TAG_ID, temp_tagId);
values.put(LoginValidate.C_STATUS, manualM);
values.put(LoginValidate.C_TAG_SCAN_TIME, manualLogoutTime);
values.put(LoginValidate.C_TRANSACTIONS_LATITUDE, temp_tagLatitude);
values.put(LoginValidate.C_TRANSACTIONS_LONGITUDE, temp_tagLongitude);
DateTime now = new DateTime();
DateTimeFormatter df = DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss.SSS");
String formattedNowTime = df.print(now);
Log.e(TAG, "formattedNowTime = " + formattedNowTime);
DateTimeFormatter df2 = DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss.SSS");
String manualTime = df2.print(timeSetOnSpinner);
Log.e(TAG, "about to put " + temp_tagName + " into DB");
nfcscannerapplication.loginValidate.insertIntoTransactions(values);
String[] params = new String[]{nfcscannerapplication.getCompId(), temp_tagId, temp_PersonId, nfcscannerapplication.getCarerID(),
manualTime, formattedNowTime, manualM, getDeviceName(), temp_tagLatitude, temp_tagLongitude};
AsyncPostData apd = new AsyncPostData();
apd.execute(params);
///////////////now carry on as usual with the last actual tag that has been scanned
Log.e(TAG, "about to insert the current record after inserting the manual logout");
if(tagId == null){
tagId = _tagId;
}
ContentValues values3 = new ContentValues();
values3.putNull(LoginValidate.C_ID);
values3.put(LoginValidate.C_TYPE, tagType);
values3.put(LoginValidate.C_COMPANY_ID, nfcscannerapplication.getCompId());
values3.put(LoginValidate.C_PERSON_ID, tagPerson);
values3.put(LoginValidate.C_NAME, tagUserName);
values3.put(LoginValidate.C_TAG_ID, tagId);
values3.put(LoginValidate.C_STATUS, IN);
values3.put(LoginValidate.C_TAG_SCAN_TIME, tagScanTime.getMillis());
values3.put(LoginValidate.C_TRANSACTIONS_LATITUDE, tagLatitude);
values3.put(LoginValidate.C_TRANSACTIONS_LONGITUDE, tagLongitude);
// make the current transaction out
DateTime now3 = new DateTime();
DateTimeFormatter df3 = DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss.SSS");
String formattedNowTime3 = df3.print(now3);
Log.e(TAG, "formattedNowTime = " + formattedNowTime3);
String formattedTagScanTime3 = df3.print(tagScanTime);
Log.e(TAG, "about to put " + tagUserName + " into DB");
nfcscannerapplication.loginValidate.insertIntoTransactions(values3);
String[] params3 = new String[]{nfcscannerapplication.getCompId(), tagId, tagPerson, nfcscannerapplication.getCarerID(),
formattedTagScanTime3, formattedNowTime, IN, getDeviceName(), tagLatitude, tagLongitude};
AsyncPostData apd3 = new AsyncPostData();
apd3.execute(params3);
.

Related

How to change UI colors at BroadcastReceiver?

I have an Alarm Manager for update database"s values.When user starts to alarm,My broadcastReceiver is activeted.There is another alarm in my BroadcastReceiver that İt always active when first alarm launch that It works only once.My BroadcastReceiver works but It doesn"t do what I say.My purpose is:Updating UI with colors.I have 3 if loops to updating my database.My problem is I update my database but When Updated my database,Third one loop doesn"t work.I am working with Toast for understanding . How can I fix it?
First one works good:
if( !listDataBoya.contains("#1eac02")){
Toast.makeText(context, "Alarm !!!!!!!!!!1111111111", Toast.LENGTH_LONG).show();
String table = "people_table";
ContentValues productDetailsContentValues = new ContentValues();
productDetailsContentValues.put("boya", "#1eac02");
String where = " id = " + listDataId.get(secilmissayı);
mDatabaseHelper.update(table, productDetailsContentValues, where , null);
setalarm(context);
}
Second one works good:
if (listDataBoya.get(secilmissayı) != "#1eac02" ){
String table = "people_table";
ContentValues productDetailsContentValues = new ContentValues();
productDetailsContentValues.put("boya", "#1eac02");
String where = " id = " + listDataId.get(secilmissayı);
mDatabaseHelper.update(table, productDetailsContentValues, where , null);
Toast.makeText(context, "Alarm !!!!!!!!!!22222222"+ listDataBoya.get(secilmissayı), Toast.LENGTH_LONG).show();
setalarm(context);
}
Third one It doesn"t work: (I can"t see my Toast.)
if (listDataBoya.get(secilmissayı) == "#1eac02" ){
Toast.makeText(context, "Alarm !!!!!!!!!!333333333", Toast.LENGTH_LONG).show();
String table = "people_table";
ContentValues productDetailsContentValues = new ContentValues();
productDetailsContentValues.put("boya", "#1eac02");
String where = " id = " + listDataId.get(secilmissayı);
mDatabaseHelper.update(table, productDetailsContentValues, where , null);
setalarm(context);}
Your third example isn't firing because you're comparing string objects with == instead you should use an equals method that will return true if the argument is a string object that represents the same sequence of characters as the string object you're comparing. Similarly you should change your other examples accordingly.
if(listDataBoya.get(secilmissayı).equals("#1eac02")){
...
}

How to retrieve database row in a soap web service?

I am developing a mobile application in android.The application gets data from a database(in SQL Server) using a soap web service(in java). Now i have been stuck into a problem and it is as follows- the android application retrieves a row (all the columns) from the database and sets the column values to the respective text fields but i don't know what to do in the web service. Please help me
My Code for the web method is-
#WebMethod(operationName = "DiseaseInfoGC")
public String DiseaseInfo4( #WebParam(name = "crop_name") String crop,
#WebParam(name = "spread_mode") String spread_mode,
#WebParam(name = "path_cong_env") String path_cong_env) {
query_disease = new String();
try {
DBConnect.databaseconnect();
Statement stmt_disease = DBConnect.connect.createStatement();
query_disease = "Select * from Disease where crop_name='" + crop + "' and Disease_SpreadMode='"+spread_mode+"' "
+ "and Disease_PathCongEnv='" + path_cong_env + "'";
System.out.println(query_disease);
ResultSet rslt_disease = stmt_disease.executeQuery(query_disease);
System.out.println(query_disease);
executemyquery(rslt_disease);
System.out.println(query_disease);
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
} catch (SQLException ex) {
System.out.println(ex.getMessage());;
} catch (NullPointerException ex) {
System.out.println(ex.getMessage());
}
return disease_name;
}
And the executequery() is-
private void executemyquery(ResultSet rslt_disease) throws SQLException {
while (rslt_disease.next()) {
disease_name = rslt_disease.getString("Disease_EngName");
System.out.println("Name Of the Disease: "+disease_name);
path_name = rslt_disease.getString("Disease_PathScName");
System.out.println("Name of the Pathogen: "+path_name);
path_geo_dis = rslt_disease.getString("Disease_PathGeoDist");
System.out.println("Pathogen Scientific name: "+path_geo_dis);
path_life_cycle = rslt_disease.getString("Disease_PathLCycle");
System.out.println("Life Cycle of the Pathogen: "+path_life_cycle);
disease_symptoms = rslt_disease.getString("Disease_Symptom");
System.out.println("Disease Symptoms: "+disease_symptoms);
disease_controls = rslt_disease.getString("Disease_Control");
System.out.println("Disease control mechanism: "+disease_controls);
prevention = rslt_disease.getString("Disease_Prevention");
System.out.println("Disease prevention Mechanism: "+prevention);
spread_mode = rslt_disease.getString("Disease_SpreadMode");
System.out.println("Spread mode of the disease: "+spread_mode);
primary_source = rslt_disease.getString("Disease_PSource");
System.out.println("Primary Source: "+primary_source);
secondary_source = rslt_disease.getString("Disease_SSource");
System.out.println("Secondary Source: "+secondary_source);
path_a_host = rslt_disease.getString("Disease_PathAHost");
System.out.println("Pathogen host"+path_a_host);
path_cong_env = rslt_disease.getString("Disease_PathCongEnv");
System.out.println("Pathogen Congenial Envoronment"+path_cong_env);
occur_period = rslt_disease.getString("Disease_OccurancePd");
System.out.println("Disease occuring period: "+occur_period);
}
I have just stored the column values in the string. I know that it is useless use string here. But i have no idea how to store the column values from the database in the web method so that i can use them in the android application.Hope you can understand my question. Please guide me..

broadcast to have application launch count

How can I get the launch count of all applications? I have the complete list of installed apps, and I have a broadcast when an application is installed, but I need the launch count of any apps.
I see this app with this. You have the cpu time, the foreground time, and the launch count... how do they do it??
Finally i do that! i create a AlarmManager that every minute check the running applications, if an application in running (background or active) i check the last time that i saw it. if this time is greater than one minute i increase the count.
Now i'm trying to have how many data the application sent to an external server, i have this data, but do you know if this data is from i have installed my application or from when i boot my smartphone?
Long txByte = TrafficStats.getUidTxBytes(listApp.getAppsRunning().get(i).getPid());
this code is for get the count time
for(int i=0; i< listApp.getAppsRunning().size(); i++)
{
String pName = listApp.getAppsRunning().get(i).getPackageName();
String Ldate = "0";
int Nrun = 0;
Long Ntime = null, Ndata = null ;
Cursor c=db.fetchInstalled(pName);
if(c.moveToFirst())
{
Nrun = c.getInt(2);
Ldate = c.getString(3);
Ntime = c.getLong(4);
Ndata = c.getLong(5);
Log.d("db", "last time: " + Nrun+ " time: " + Ldate);
}
if(Ldate.equalsIgnoreCase("0"))
{
Nrun++;
db.updateLaunchAndTime(Nrun, lastUpdated, pName, Ntime, Ndata);
}
else
{
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM dd, yyyy h:mmaa");
Date lastDate = null;
Date currentDate = null;
try {
lastDate = dateFormat.parse(Ldate);
currentDate = dateFormat.parse(lastUpdated);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//int pid = android.os.Process.getUidForName(listApp.getAppsRunning().get(i).getPid());
Long txByte = TrafficStats.getUidTxBytes(listApp.getAppsRunning().get(i).getPid());
Log.d("pid process", "pid: " + listApp.getAppsRunning().get(i).getPid());
Ndata = txByte;
Log.d("data send", "send: " + Ndata);
long diff = currentDate.getTime() - lastDate.getTime();
if(diff > 100* 1000)
{
Log.d("db", "difference plus 1 min app: " + pName);
Nrun++;
}
Ntime = Ntime+diff;
db.updateLaunchAndTime(Nrun, lastUpdated, pName, Ntime, Ndata);
}
//db.insertRunningP(pName , lastUpdated);
}
db.close()
I checked the power consume of this code and is less than 3% of total battery, so for now this is the best solution that i have found
I've never done it before, but I'm pretty sure http://developer.android.com/reference/android/app/ActivityManager.html provides the information you need.
if you had rooted your device, you also can read the usage stats files in /data/system/usagestats/usage-* for detail infomation.

Capturing part of string from a txt file?

I have a text file like this, separated by ";"
1022-3, 1603-4, 2012-5, 2489-6;
Gotta catch the first part before the "-" and pass to variable, and compare with milliseconds, if is equal the number, capture the number after of "-".
And do so with the next number after the semicolon, and so front.
public static long MilliSeconds() {
// get Calendar instance
Calendar now = Calendar.getInstance();
return now.getTimeInMillis();
}
And the beginning of the code to do what I need this here
private void LerArquivo() {
String lstrNomeArq;
File arq;
String lstrlinha;
long tempoInicio = 0;
long tempoDecorrido = 0;
try {
tempoDecorrido = (RecordSound.MilliSeconds() - tempoInicio);
lstrNomeArq = "/Android/data/br.com.couldsys.drumspro/cache/GravaSound.TXT";
String conteudotexto = "";
arq = new File(Environment.getExternalStorageDirectory(),
lstrNomeArq);
BufferedReader br = new BufferedReader(new FileReader(arq));
// pega o conteudo do arquivo texto
conteudotexto = br.readLine();
String capturaIndex = ("Conteudo do texto: "
+ conteudotexto.substring(
conteudotexto.indexOf("-") + 1,
conteudotexto.indexOf(";",
conteudotexto.lastIndexOf("-"))));
if (tempoDecorrido == capturatempo) {
DrumsProActivity.vsm.playSound(capturaindex);
// ler a nova linha
// se chegar ao final do string então para o while
if (conteudotexto.length() > 0) {
executar = false;
}
}
} catch (Exception e) {
trace("Erro : " + e.getMessage());
}
}
use this simpler code : create an array of substrings each contain a string formated ####-#
string[] MyStr = conteudotexto.split(',');
string sss= MyStr[0];
string sss2= MyStr[1];
....
now sss is 1022-3
sss2 is 1603-4 and so on ....
then reuse split function:
string[] MyStr2 = sss.split('-');
now we have :
MyStr2[0] = 1022
MyStr2[1] = 3
Maybe not particular elegant but just pragmatic for me - use the String split method. First split with ","
String[] parts = conteudotexto.split(",");
and then with each of the parts (here for the first)
String[] subParts = parts[0].split("-");
Just gives you everything in the pieces you need to look at and no danger get mixed up with positions etc.
What I need now is know how to catch part of text.
arq = new File(Environment.getExternalStorageDirectory(),
lstrNomeArq);
BufferedReader br = new BufferedReader(new FileReader(arq));
// pega o conteudo do arquivo texto
conteudotexto = br.readLine();
The text may vary more separation has two, the first number is separated from the second number by a "-" (dash) which is then separated by "," (comma)
549-8,1019-9,1404-3,1764-3,2208-10,2593-5,2938-9,3264-6,3700-0,4174-7,4585-8,4840-2,5192-9,5540-10,5932-0,
As has been shown
String[] parte1 = conteudotexto.split(",");
e em seguida
String[] parte2 = parte1[0].split("-");
The rule I'm trying to do is: Turn within a millisecond while the method and compare with the first part of the text
type
**If valor_milissegundos first part is equal to the number of text then
---> enters and runs the function playSound (the second number of the text);
------> goes to the next number in the text loop, capturing the second number of the text and compares it to the millisecond, if equal enters the IF block and catch the second number after the dash, and so on, until you reach the end of the text.**
Method return milliseconds calculates milliseconds
public static long MilliSeconds() {
// get Calendar instance
Calendar now = Calendar.getInstance();
return now.getTimeInMillis();
}
I hope understand why I used the google translator
thank you

Getting events from calendar

My issue is, I have to make one demo application in which I wants to read the events of the Google calendar, for that I have manually inserted the events like the title of event, the time of events and the details of the whole events. now I need to just read those events form that calendar.
For that I have tried to use the gcode(google code) API which provides the calendar API class. But still I cant read those events.
That code above is pretty awful (and it does not seem to work in ICS - definitely the column names are different)
The page here:
http://developer.android.com/guide/topics/providers/calendar-provider.html
provides a much better overview.
A (much) simpler code to retrieve calendars:
public class CalendarContentResolver {
public static final String[] FIELDS = {
CalendarContract.Calendars.NAME,
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
CalendarContract.Calendars.CALENDAR_COLOR,
CalendarContract.Calendars.VISIBLE
};
public static final Uri CALENDAR_URI = Uri.parse("content://com.android.calendar/calendars");
ContentResolver contentResolver;
Set<String> calendars = new HashSet<String>();
public CalendarContentResolver(Context ctx) {
contentResolver = ctx.getContentResolver();
}
public Set<String> getCalendars() {
// Fetch a list of all calendars sync'd with the device and their display names
Cursor cursor = contentResolver.query(CALENDAR_URI, FIELDS, null, null, null);
try {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String name = cursor.getString(0);
String displayName = cursor.getString(1);
// This is actually a better pattern:
String color = cursor.getString(cursor.getColumnIndex(CalendarContract.Calendars.CALENDAR_COLOR));
Boolean selected = !cursor.getString(3).equals("0");
calendars.add(displayName);
}
}
} catch (AssertionError ex) { /*TODO: log exception and bail*/ }
return calendars;
}
}
Hope this helps!
Ok i found the answer of this whole of the concept that how to use the google calendar application integration with the android phone.
code:--
first you set this line which will goes to read the calendar events form the other class form your class which is current is the ApplicationSettings.java .
ReadCalendar.readCalendar(ApplicationSettings.this);
package com.mycalendarevents.android;
import java.util.Date;
import java.util.HashSet;
import java.util.regex.Pattern;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.format.DateUtils;
public class ReadCalendar
{
static Cursor cursor;
public static void readCalendar(Context context) {
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) {
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[] { "title", "begin", "end", "allDay"}, "Calendars._id=" + 1,
null, "startDay ASC, startMinute ASC");
System.out.println("eventCursor count="+eventCursor.getCount());
if(eventCursor.getCount()>0)
{
if(eventCursor.moveToFirst())
{
do
{
Object mbeg_date,beg_date,beg_time,end_date,end_time;
final String title = eventCursor.getString(0);
final Date begin = new Date(eventCursor.getLong(1));
final Date end = new Date(eventCursor.getLong(2));
final Boolean allDay = !eventCursor.getString(3).equals("0");
/* System.out.println("Title: " + title + " Begin: " + begin + " End: " + end +
" All Day: " + allDay);
*/
System.out.println("Title:"+title);
System.out.println("Begin:"+begin);
System.out.println("End:"+end);
System.out.println("All Day:"+allDay);
/* the calendar control metting-begin events Respose sub-string (starts....hare) */
Pattern p = Pattern.compile(" ");
String[] items = p.split(begin.toString());
String scalendar_metting_beginday,scalendar_metting_beginmonth,scalendar_metting_beginyear,scalendar_metting_begindate,scalendar_metting_begintime,scalendar_metting_begingmt;
scalendar_metting_beginday = items[0];
scalendar_metting_beginmonth = items[1];
scalendar_metting_begindate = items[2];
scalendar_metting_begintime = items[3];
scalendar_metting_begingmt = items[4];
scalendar_metting_beginyear = items[5];
String calendar_metting_beginday = scalendar_metting_beginday;
String calendar_metting_beginmonth = scalendar_metting_beginmonth.toString().trim();
int calendar_metting_begindate = Integer.parseInt(scalendar_metting_begindate.trim());
String calendar_metting_begintime = scalendar_metting_begintime.toString().trim();
String calendar_metting_begingmt = scalendar_metting_begingmt;
int calendar_metting_beginyear = Integer.parseInt(scalendar_metting_beginyear.trim());
System.out.println("calendar_metting_beginday="+calendar_metting_beginday);
System.out.println("calendar_metting_beginmonth ="+calendar_metting_beginmonth);
System.out.println("calendar_metting_begindate ="+calendar_metting_begindate);
System.out.println("calendar_metting_begintime="+calendar_metting_begintime);
System.out.println("calendar_metting_begingmt ="+calendar_metting_begingmt);
System.out.println("calendar_metting_beginyear ="+calendar_metting_beginyear);
/* the calendar control metting-begin events Respose sub-string (starts....ends) */
/* the calendar control metting-end events Respose sub-string (starts....hare) */
Pattern p1 = Pattern.compile(" ");
String[] enditems = p.split(end.toString());
String scalendar_metting_endday,scalendar_metting_endmonth,scalendar_metting_endyear,scalendar_metting_enddate,scalendar_metting_endtime,scalendar_metting_endgmt;
scalendar_metting_endday = enditems[0];
scalendar_metting_endmonth = enditems[1];
scalendar_metting_enddate = enditems[2];
scalendar_metting_endtime = enditems[3];
scalendar_metting_endgmt = enditems[4];
scalendar_metting_endyear = enditems[5];
String calendar_metting_endday = scalendar_metting_endday;
String calendar_metting_endmonth = scalendar_metting_endmonth.toString().trim();
int calendar_metting_enddate = Integer.parseInt(scalendar_metting_enddate.trim());
String calendar_metting_endtime = scalendar_metting_endtime.toString().trim();
String calendar_metting_endgmt = scalendar_metting_endgmt;
int calendar_metting_endyear = Integer.parseInt(scalendar_metting_endyear.trim());
System.out.println("calendar_metting_beginday="+calendar_metting_endday);
System.out.println("calendar_metting_beginmonth ="+calendar_metting_endmonth);
System.out.println("calendar_metting_begindate ="+calendar_metting_enddate);
System.out.println("calendar_metting_begintime="+calendar_metting_endtime);
System.out.println("calendar_metting_begingmt ="+calendar_metting_endgmt);
System.out.println("calendar_metting_beginyear ="+calendar_metting_endyear);
/* the calendar control metting-end events Respose sub-string (starts....ends) */
System.out.println("only date begin of events="+begin.getDate());
System.out.println("only begin time of events="+begin.getHours() + ":" +begin.getMinutes() + ":" +begin.getSeconds());
System.out.println("only date begin of events="+end.getDate());
System.out.println("only begin time of events="+end.getHours() + ":" +end.getMinutes() + ":" +end.getSeconds());
beg_date = begin.getDate();
mbeg_date = begin.getDate()+"/"+calendar_metting_beginmonth+"/"+calendar_metting_beginyear;
beg_time = begin.getHours();
System.out.println("the vaule of mbeg_date="+mbeg_date.toString().trim());
end_date = end.getDate();
end_time = end.getHours();
CallHandlerUI.metting_begin_date.add(beg_date.toString());
CallHandlerUI.metting_begin_mdate.add(mbeg_date.toString());
CallHandlerUI.metting_begin_mtime.add(calendar_metting_begintime.toString());
CallHandlerUI.metting_end_date.add(end_date.toString());
CallHandlerUI.metting_end_time.add(end_time.toString());
CallHandlerUI.metting_end_mtime.add(calendar_metting_endtime.toString());
}
while(eventCursor.moveToNext());
}
}
break;
}
}
}
here is the whole of the code is to be posted which will simply reads each and every events form your calendar with the help of that postback url which is for 2.2 and above version:
Uri.parse("content://com.android.calendar/instances/when").buildUpon();
pl find the under those version lower then 2.2 in android and use those events as you required place...
I am aware that this is an old post, but I found inspiration for optimizing the solution found in the answer given by Akash Takkar if anyone is in need of a solution in the near future.
The issues
Specically, I found a few issues in the original code:
The loop for retrieving calendar events broke immaturely
Hereby, only events from the first calendar was retrieved
The first event in each calendar was skipped by using eventCursor.moveToFirst(); which thereafter moves directly to the next event in the while loop
The id of the calendars were not set correctly in the eventCursor
"Calendars._id=" + 1, should be "Calendars._id=" + id,
It would be difficult for others to specify their own time range
The current solution is not object oriented which would hold many advantages
The readability and documentation is not the best
The solution
I have hereby created a Github Library which returns a list of event objects in a specified time range which can be found at:
https://github.com/david-laundav/CalendarService
The source files can be found under "CalendarService/src/dk/CalendarService".
Use cases
The solution itself contains two different methods for different purposes.
First use case:
CalendarService.readCalendar(class.this)
// where class.this is either your class or the context
This method will return a list of events for +/- 1 day
Second use case:
You can also specify your own time range:
CalendarService.readCalendar(class.this, int days, int hours)
An example might be:
CalendarService.readCalendar(class.this, 2, 5)
In doing so will return a list of events from +/-2 days and +/- 5 hours.
The service has been tested, but please tell me if you experience any issues.
This post is a little bit old, but here is another easy solution for getting data related to Calendar content provider in Android:
Use this lib: https://github.com/EverythingMe/easy-content-providers
And now, get all calendars:
CalendarProvider calendarProvider = new CalendarProvider(context);
List<Calendar> calendars = calendarProvider.getCalendars().getList();
Each Calendar has all fields, so you can get any info you need:
id, name, calendarColor, ownerAccount, accountName, calendarAccessLevel, ...
Or, get all Events of specific calendar:
List<Event> calendars = calendarProvider.getEvents(calendar.id).getList();
And there is also option to get Reminders, Attendees, Instances.
It works with lists or cursor and there a sample app to see how it looks and works.
In fact, there is support for all Android content providers like: Contacts, SMS, Calls, ...
Full doc with all options: https://github.com/EverythingMe/easy-content-providers/wiki/Android-providers
Hope it helped :)
Use this code get the calendar events for one day.
public static void readCalendarEvent(Context context) throws ParseException {
ContentResolver contentResolver = context.getContentResolver();
Calendar calendar = Calendar.getInstance();
String dtstart = "dtstart";
String dtend = "dtend";
SimpleDateFormat displayFormatter = new SimpleDateFormat("MMMM dd, yyyy (EEEE)");
stime=displayFormatter.format(calendar.getTime());
SimpleDateFormat startFormatter = new SimpleDateFormat("MM/dd/yy");
String dateString = startFormatter.format(calendar.getTime());
long after = calendar.getTimeInMillis();
SimpleDateFormat formatterr = new SimpleDateFormat("hh:mm:ss MM/dd/yy");
Calendar endOfDay = Calendar.getInstance();
Date dateCCC = formatterr.parse("23:59:59 " + dateString);
endOfDay.setTime(dateCCC);
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"), (new String[] { "calendar_id", "title", "description", "dtstart", "dtend","eventTimezone", "eventLocation" }), "(" + dtstart + ">" + after + " and " + dtend + "<" + endOfDay.getTimeInMillis() + ")", null, "dtstart ASC");
/*String[] COLS={"calendar_id", "title", "description", "dtstart", "dtend","eventTimezone", "eventLocation"};
cursor = contentResolver.query(
CalendarContract.Events.CONTENT_URI, COLS,null, null, null);*/
gCalendar = new ArrayList<GoogleCalendar>();
try {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
GoogleCalendar googleCalendar = new GoogleCalendar();
gCalendar.add(googleCalendar);
int calendar_id = cursor.getInt(0);
googleCalendar.setCalendar_id(calendar_id);
String title = cursor.getString(1);
googleCalendar.setTitle(title);
String description = cursor.getString(2);
googleCalendar.setDescription(description);
String dtstart1 = cursor.getString(3);
dt=convertDate(dtstart1,"hh:mm:ss");
googleCalendar.setDtstart(dt);
String dtend1 = cursor.getString(4);
googleCalendar.setDtend(dtend1);
String eventTimeZone=cursor.getString(5);
googleCalendar.setEventTimeZone(eventTimeZone);
String eventlocation = cursor.getString(6);
googleCalendar.setEventlocation(eventlocation);
}
}
} catch (AssertionError ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Categories

Resources