Adding reminder to event fails in Android - events

I have a method which adds an reminder to an event, but it fails:
FATAL EXCEPTION: main
android.database.sqlite.SQLiteException
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:184)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:140)
at android.content.ContentProviderProxy.insert(ContentProviderNative.java:420)
at android.content.ContentResolver.insert(ContentResolver.java:864)
at de.appwege.droid.medwege.navigationdrawer.TerminFragment.insertReminder(TerminFragment.java:848)
The method in question:
public long insertReminder(long eventID, int minutes){
ContentResolver cr = getActivity().getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Reminders.MINUTES, minutes);
values.put(CalendarContract.Reminders.EVENT_ID, eventID);
values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
Uri uri = cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
return Long.valueOf(uri.getLastPathSegment());
}
What I am missing here? both eventID and minutes are defined...

Recently, I also faced same issue. Finally, I found the solution.
First of all, you have to find all logged in gmail id from the device and then select any one gmail account and find its calendar id. After that you have to pass that id to the event query like this....
values.put(Events.CALENDAR_ID, calendarId);
at last call you function
public long insertReminder(long eventID, int minutes){
ContentResolver cr = getActivity().getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Reminders.MINUTES, minutes);
values.put(CalendarContract.Reminders.EVENT_ID, eventID);
values.put(CalendarContract.Reminders.METHOD,
CalendarContract.Reminders.METHOD_ALERT);
Uri uri = cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
return Long.valueOf(uri.getLastPathSegment());
}
See below method for finding email id's...
public static Hashtable listCalendarId(Context context) {
try {
if (haveCalendarReadWritePermissions((Activity) context)) {
String projection[] = {"_id", "calendar_displayName"};
Uri calendars;
calendars = Uri.parse("content://com.android.calendar/calendars");
ContentResolver contentResolver = c.getContentResolver();
Cursor managedCursor = contentResolver.query(calendars, projection, null, null, null);
if (managedCursor.moveToFirst()) {
String calName;
String calID;
int cont = 0;
int nameCol = managedCursor.getColumnIndex(projection[1]);
int idCol = managedCursor.getColumnIndex(projection[0]);
Hashtable<String, String> calendarIdTable = new Hashtable<>();
do {
calName = managedCursor.getString(nameCol);
calID = managedCursor.getString(idCol);
Log.v(TAG, "CalendarName:" + calName + " ,id:" + calID);
calendarIdTable.put(calName, calID);
cont++;
} while (managedCursor.moveToNext());
managedCursor.close();
return calendarIdTable;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

Related

TaskContinuation.cs not found exception while accessing WebAPI Task

I'm trying to fetch records from a db cursor from the Client app.
Debugging Web API shows that the Cursor returns records but when returning to the Client it throws mscorlib.pdb not loaded window and clicking on Load option it throws TaskContinuation.cs not found exception
Code snippets as below ( removed irrelevant codes for readability )
WebAPI
[HttpPost("{values}")]
public async Task<ActionResult> Post([FromBody] JToken values)
{
// code removed for readility
string[] cursors = { };
cursors = await cursor.GetRpts();
CursorClass firstCursor = JsonConvert.DeserializeObject<CursorClass>(cursors[0]);
return new OkObjectResult(cursors);
}
public async Task<string[]> GetRpts()
{
try
{
DataTable[] dataTables;
CursorClass[] cursorClasses = new CursorClass[5];
//stripped some code
using (DataAccess dataAccess = new DataAccess()
{
ParamData = PrepareDoc(),
ProcedureName = Constants.Rpt,
RecordSets = this.CursorNumbers,
})
{
Int32 errorNumber = await dataAccess.RunComAsync();
dataTables = dataAccess.TableData;
};
//fetching code stripped off
string[] _cursors = Array.ConvertAll(cursorClasses, JsonConvert.SerializeObject);
return _cursors;
}
catch (Exception ex)
{
string tt = ex.Message;
}
}
public async Task<Int32> RunComAsync()
{
Int32 returnValue = 0;
try
{
//open db connection
//---------- Running the Command in asysnc mode ----------
Task<int> task = new Task<int>(oracleCommand.ExecuteNonQuery);
task.Start();
returnValue = await task;
//--------------------------------------------------------
OracleRefCursor[] refCursor = { null, null, null, null, null };
for (int _sub = 0; _sub < RecordSets; _sub++)
{
//DT declaration / connection code removed
dataAdapter.Fill(dataTable, refCursor[_sub]);
TableData[_sub] = dataTable;
}
}
catch (Exception ex)
{
return LogMsg(ex);
}
finally
{
this.Dispose(true);
}
CloseConnection();
return LogMsg(null,"Successful Operation");
}
Client
private async Task<HttpStatusCode> CallService()
{
HttpResponseMessage _response = null;
try
{
using (HttpRequestMessage requestMessage = new HttpRequestMessage()
{
Content = new System.Net.Http.StringContent(JsonRepo, System.Text.Encoding.UTF8, HeaderJson),
RequestUri = new Uri(UriString),
Method = HttpMethod.Post,
})
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Utils.TOKEN) ;
_response = await httpClient.SendAsync(requestMessage);
if (_response.IsSuccessStatusCode)
{
string httpResponse = await _response.Content.ReadAsStringAsync();
httpString = JsonConvert.DeserializeObject<string[]>(httpResponse);
}
}
}
return ErrorCode;
}
Is that something related to async operation? while debugging the API it confirms the Datatable with records . Any inputs are deeply appreciated.
error image
TIA

loopj JsonObject with inside JsonArray JsonObjects

I have a Webservice which give me back this:
{"result":[{"Id":"20","temperatura":"34","humedad":"29","Insertado":"2016-07-01 12:19:42"},{"Id":"21","temperatura":"34","humedad":"29","Insertado":"2016-07-01 12:34:42"},{"Id":"22","temperatura":"35","humedad":"28","Insertado":"2016-07-01 12:49:43"},{"Id":"23","temperatura":"35","humedad":"19","Insertado":"2016-07-01 13:29:06"},{"Id":"24","temperatura":"31","humedad":"18","Insertado":"2016-07-01 13:44:07"},{"Id":"25","temperatura":"33","humedad":"16","Insertado":"2016-07-01 13:59:10"}]}
This is an Object, which has and Array, and the array has many objects.
Here is my code. I am using loopj library-
private void CaptarParametros(String idObjeto) {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put(UtilitiesGlobal.SENSOR_ID, idObjeto);
RequestHandle post = client.post(this, SENSORS_URL, params, new JsonHttpResponseHandler() {
#Override
public void onStart() {
// called before request is started
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// called when response HTTP status is "200 OK"
JSONObject jsonobject = null;
JSONObject dht11JSONbject = null;
JSONArray dht11JSONarray = null;
try {
jsonobject = new JSONObject(String.valueOf(response));
dht11JSONbject = jsonobject.getJSONObject("result");
dht11JSONarray = new JSONArray(dht11JSONbject);
JSONArray dht11 = dht11JSONarray.getJSONArray(0);
for (int i = 0; i < dht11JSONarray.length(); i++) {
JSONObject item = dht11.getJSONObject(i);
String temperatura = item.getString("temperatura");
String humedad = item.getString("temperatura");
//Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + usuarioiJSONbject);
Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + temperatura + humedad);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
But I get error like this:
org.json.JSONException: Value [{"Id":"19","temperatura":"35","humedad":"16","Insertado":"2016-07-01 12:19:24"}] at result of type org.json.JSONArray cannot be converted to JSONObject
I would appreciate any help.- I need to extract "temperature" and humedad" in separate arrays since later I have to use it in MPAndroidChat to make tow linechart, one chart for one set of parameters and another one for other parameters.
Solution is here:
try {
jsonobject = new JSONObject(String.valueOf(response));
//dht11JSONbject = jsonobject.getJSONObject("result");
List<String> allNames = new ArrayList<String>();
JSONArray cast = jsonobject.getJSONArray("result");
for (int i=0; i<cast.length(); i++) {
JSONObject parametrosdht11 = cast.getJSONObject(i);
String temperatura = parametrosdht11.getString("temperatura");
String humedad = parametrosdht11.getString("humedad");
allNames.add(temperatura);
allNames.add(humedad);
//Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " + usuarioiJSONbject);
Log.i(UtilitiesGlobal.TAG, "onSuccess: loopj " +"temperatura: "+ temperatura +" humedad: " +humedad);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
We have a String with many sub_objects, then we have to put them into an array or List.
Take the solution from:
how to parse JSONArray in android

Xamarin http webservice issue

I m trying to use http request webservice issue is that when we post wrong username and password the login service generate exception and it can't return any value in async calls.
A code snippet would help assist with the problem ...
However using a try catch should help you catch your exception and prevent application from crashing and handling the exceptions accordingly.
As seen in my sample code below I cater for the incorrect details entered / connectivity problems. I peform the http async request then parse the xml to my model handling the exceptions accordingly
var response = await WebRequestHelper.MakeAsyncRequest(url, content);
if (response.IsSuccessStatusCode == true)
{
Debug.WriteLine("Login Successfull" + "result.IsSuccessStatusCode" + response.IsSuccessStatusCode);
var result = response.Content.ReadAsStringAsync().Result;
result = result.Replace("<xml>", "<LoginResult>").Replace("</xml>", "</LoginResult>");
loginResult = XMLHelper.FromXml<LoginResult>(result);
if (loginResult != null)
{
login.Type = ResultType.OK;
login.Result = loginResult;
}
else
{
login.Type = ResultType.WrongDetails;
}
}
else
{
Debug.WriteLine("Login Failed" + "result.IsSuccessStatusCode" + response.IsSuccessStatusCode);
login.Type = ResultType.WrongDetails;
}
}
catch (Exception ex)
{
login.Type = ResultType.ConnectivityProblem;
}
Web Request
public static async Task<HttpResponseMessage> MakeAsyncRequest(string url, Dictionary<string, string> content)
{
var httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 5, 0);
httpClient.BaseAddress = new Uri(url);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type: application/x-www-form-urlencoded", "application/json");
if (content == null)
{
content = new Dictionary<string, string>();
}
var encodedContent = new FormUrlEncodedContent(content);
var result = await httpClient.PostAsync(httpClient.BaseAddress, encodedContent);
return result;
I would recommend wrapping the response in a generic ServiceResponse where you can store the exceptions. await methods can be included in try/catch blocks so the standard process can be followed.
E.G.
public async Task<ServiceResponse<T>> PostAsync<T>(String address, object dto){
var content = Serializer.SerializeObject (dto);
var response = await client.PostAsync (
address,
new StringContent (content));
if (response.IsSuccessStatusCode) {
try {
var responseString = await response.Content.ReadAsStringAsync ();
return new ServiceResponse<T> (Serializer.DeserializeObject<T> (responseString),
response.StatusCode);
} catch (Exception ex) {
return new ServiceResponse<T> (response.StatusCode, ex);
}
} else {
return new ServiceResponse<T> (response.StatusCode);
}
}
With the ServiceResponse defined as :
public class ServiceResponse<T>
{
public HttpStatusCode StatusCode { get; set;}
public T Value { get; set;}
public String Content { get; set;}
public Exception Error {get;set;}
public ServiceResponse(T value, HttpStatusCode httpStatusCode){
this.Value = value;
this.StatusCode = httpStatusCode;
}
public ServiceResponse(HttpStatusCode httpStatusCode, Exception error = null){
this.StatusCode = httpStatusCode;
this.Error = error;
}
}
This will give you a clean way of managing all your HTTP responses and any errors that may occur.

Android getContentResolver insert not returning full URI

I have an activity that is being swapped out when I raise an intent for another activity. onPause calls saveState() to save work so far:
private void saveState() {
...
...
if (myUri == null) {
// Inserting a new record
*** myUri = getContentResolver().insert(ContentProvider.CONTENT_URI, values);
} else {
// Update an existing record
getContentResolver().update(myUri, values, null, null);
}
}
Before calling getContentResolver(), ContentProvider.CONTENT_URI = 'content://nz.co.bkd.extraTime.contentprovider/times'.
After the call, myUri = 'times/#' where #=row ID. My question is; where is the 'content:...' prefix to the returned uri?
During the call, ContentResolver.java is called and returns CreatedRow uri
ContentResolver.java
....
....
public final Uri insert(Uri url, ContentValues values)
{
IContentProvider provider = acquireProvider(url);
if (provider == null) {
throw new IllegalArgumentException("Unknown URL " + url);
}
try {
long startTime = SystemClock.uptimeMillis();
*** Uri createdRow = provider.insert(url, values);
long durationMillis = SystemClock.uptimeMillis() - startTime;
maybeLogUpdateToEventLog(durationMillis, url, "insert", null /* where */);
return createdRow;
} catch (RemoteException e) {
// Arbitrary and not worth documenting, as Activity
// Manager will kill this process shortly anyway.
return null;
} finally {
releaseProvider(provider);
}
}
At this point, createdRow = 'times/#'.
The record does actually get saved in the Sqlite database.
Do I have to add the uri prefix in my code or should the full uri be returned?

Unauthorizedaccessexception{"Invalid cross-thread access."}...is occur

i want to short my url with bitly but an exception is occur when i want to set out string to my text block
private void button1_Click(object sender, RoutedEventArgs e)
{
ShortenUrl(textBox1.Text);
}
enum Format
{
XML,
JSON,
TXT
}
enum Domain
{
BITLY,
JMP
}
void ShortenUrl(string longURL)
{
Format format = Format.XML;
Domain domain = Domain.BITLY;
string _domain;
//string output;
// Build the domain string depending on the selected domain type
if (domain == Domain.BITLY)
_domain = "bit.ly";
else
_domain = "j.mp";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
string.Format(#"http://api.bit.ly/v3/shorten?login={0}&apiKey={1}&longUrl={2}&format={3}&domain={4}",
"username", "appkey", HttpUtility.UrlEncode(longURL), format.ToString().ToLower(), _domain));
request.BeginGetResponse(new AsyncCallback(GetResponse), request);
}
void GetResponse(IAsyncResult result)
{
XDocument doc;
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string responseString = reader.ReadToEnd();
doc = XDocument.Load(reader.BaseStream);
}
//// var x = from c in doc.Root.Element("data").Elements()
// where c.Name == "url"
// select c;
//XElement n = ((IEnumerable<XElement>)x).ElementAt(0);
// textBox2.Text = ((IEnumerable<String>)x).ElementAt(0);
lista = (from Born_rich in doc.Descendants("url")
select new a()
{
shrtenurl = Born_rich.Value
}).ToList();
output = lista.ElementAt(0).shrtenurl;
textBox2.Text = output;
//
//
// textBox2.Text = s;
}
List<a> lista = new List<a>();
String output;
}
public class a
{
public String shrtenurl { set; get; }
}
The calback from HttpWebRequest occurs on a non-UI thread. If you want to change soemthing in the UI you must do it on the UI thread. Fortunatley there is an easy way to do this. You simply use the dispatcher to invoke the code in question on the UI.
Dispatcher.BeginInvoke(() => textBox2.Text = output);

Resources