List of usage examples for android.app ProgressDialog ProgressDialog
public ProgressDialog(Context context)
From source file:com.shafiq.myfeedle.core.MyfeedleNotifications.java
@Override public boolean onOptionsItemSelected(MenuItem item) { final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Integer, String, Boolean> asyncTask = new AsyncTask<Integer, String, Boolean>() { @Override//from ww w .j a va2s.com protected Boolean doInBackground(Integer... arg0) { if (arg0[0] == R.id.menu_notifications_refresh) { // select all accounts with notifications set Cursor widgets = getContentResolver().query( Widgets_settings.getDistinctContentUri(MyfeedleNotifications.this), new String[] { Widgets.ACCOUNT }, Widgets.ACCOUNT + "!=-1 and (" + Widgets.LIGHTS + "=1 or " + Widgets.VIBRATE + "=1 or " + Widgets.SOUND + "=1)", null, null); if (widgets.moveToFirst()) { mMyfeedleCrypto = MyfeedleCrypto.getInstance(getApplicationContext()); HttpClient httpClient = MyfeedleHttpClient.getThreadSafeClient(getApplicationContext()); while (!widgets.isAfterLast()) { long accountId = widgets.getLong(0); ArrayList<String> notificationSids = new ArrayList<String>(); Cursor account = getContentResolver().query( Accounts.getContentUri(MyfeedleNotifications.this), new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SERVICE, Accounts.SID }, Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null); if (account.moveToFirst()) { // for each account, for each notification, check for updates // if there are no updates past 24hrs and cleared, delete String token = mMyfeedleCrypto.Decrypt(account.getString(0)); String secret = mMyfeedleCrypto.Decrypt(account.getString(1)); int service = account.getInt(2); String accountEsid = mMyfeedleCrypto.Decrypt(account.getString(3)); mSimpleDateFormat = null; if (service == TWITTER) { Cursor currentNotifications = getContentResolver().query( Notifications.getContentUri(MyfeedleNotifications.this), new String[] { Notifications.SID }, Notifications.ACCOUNT + "=?", new String[] { Long.toString(accountId) }, null); // loop over notifications if (currentNotifications.moveToFirst()) { // store sids, to avoid duplicates when requesting the latest feed String sid = mMyfeedleCrypto.Decrypt(currentNotifications.getString(0)); if (!notificationSids.contains(sid)) { notificationSids.add(sid); } } currentNotifications.close(); // limit to newest status MyfeedleOAuth myfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET, token, secret); String last_sid = null; Cursor last_status = getContentResolver().query( Statuses.getContentUri(MyfeedleNotifications.this), new String[] { Statuses.SID }, Statuses.ACCOUNT + "=?", new String[] { Long.toString(accountId) }, Statuses.CREATED + " ASC LIMIT 1"); if (last_status.moveToFirst()) { last_sid = mMyfeedleCrypto.Decrypt(last_status.getString(0)); } last_status.close(); // get all mentions since the oldest status for this account String response = MyfeedleHttpClient.httpResponse(httpClient, myfeedleOAuth.getSignedRequest( new HttpGet(String.format(TWITTER_MENTIONS, TWITTER_BASE_URL, last_sid != null ? String.format(TWITTER_SINCE_ID, last_sid) : "")))); if (response != null) { try { JSONArray comments = new JSONArray(response); for (int i = 0, i2 = comments.length(); i < i2; i++) { JSONObject comment = comments.getJSONObject(i); JSONObject user = comment.getJSONObject(Suser); if (!user.getString(Sid).equals(accountEsid) && !notificationSids.contains(comment.getString(Sid))) { String friend = user.getString(Sname); addNotification(comment.getString(Sid), user.getString(Sid), friend, comment.getString("text"), parseDate(comment.getString("created_at"), TWITTER_DATE_FORMAT), accountId, friend + " mentioned you on Twitter"); } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } } else if (service == IDENTICA) { Cursor currentNotifications = getContentResolver().query( Notifications.getContentUri(MyfeedleNotifications.this), new String[] { Notifications.SID }, Notifications.ACCOUNT + "=?", new String[] { Long.toString(accountId) }, null); // loop over notifications if (currentNotifications.moveToFirst()) { // store sids, to avoid duplicates when requesting the latest feed String sid = mMyfeedleCrypto.Decrypt(currentNotifications.getString(0)); if (!notificationSids.contains(sid)) { notificationSids.add(sid); } } currentNotifications.close(); // limit to newest status MyfeedleOAuth myfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET, token, secret); String last_sid = null; Cursor last_status = getContentResolver().query( Statuses.getContentUri(MyfeedleNotifications.this), new String[] { Statuses.SID }, Statuses.ACCOUNT + "=?", new String[] { Long.toString(accountId) }, Statuses.CREATED + " ASC LIMIT 1"); if (last_status.moveToFirst()) { last_sid = mMyfeedleCrypto.Decrypt(last_status.getString(0)); } last_status.close(); // get all mentions since the oldest status for this account String response = MyfeedleHttpClient.httpResponse(httpClient, myfeedleOAuth.getSignedRequest( new HttpGet(String.format(IDENTICA_MENTIONS, IDENTICA_BASE_URL, last_sid != null ? String.format(IDENTICA_SINCE_ID, last_sid) : "")))); if (response != null) { try { JSONArray comments = new JSONArray(response); for (int i = 0, i2 = comments.length(); i < i2; i++) { JSONObject comment = comments.getJSONObject(i); JSONObject user = comment.getJSONObject(Suser); if (!user.getString(Sid).equals(accountEsid) && !notificationSids.contains(comment.getString(Sid))) { String friend = user.getString(Sname); addNotification(comment.getString(Sid), user.getString(Sid), friend, comment.getString("text"), parseDate(comment.getString("created_at"), TWITTER_DATE_FORMAT), accountId, friend + " mentioned you on Identi.ca"); } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } } else { Cursor currentNotifications = getContentResolver().query( Notifications.getContentUri(MyfeedleNotifications.this), new String[] { Notifications._ID, Notifications.SID, Notifications.UPDATED, Notifications.CLEARED, Notifications.ESID }, Notifications.ACCOUNT + "=?", new String[] { Long.toString(accountId) }, null); if (currentNotifications.moveToFirst()) { String response; MyfeedleOAuth myfeedleOAuth; switch (service) { case FACEBOOK: // loop over notifications while (!currentNotifications.isAfterLast()) { long notificationId = currentNotifications.getLong(0); String sid = mMyfeedleCrypto .Decrypt(currentNotifications.getString(1)); long updated = currentNotifications.getLong(2); boolean cleared = currentNotifications.getInt(3) == 1; // store sids, to avoid duplicates when requesting the latest feed if (!notificationSids.contains(sid)) { notificationSids.add(sid); } // get comments for current notifications if ((response = MyfeedleHttpClient.httpResponse(httpClient, new HttpGet( String.format(FACEBOOK_COMMENTS, FACEBOOK_BASE_URL, sid, Saccess_token, token)))) != null) { // check for a newer post, if it's the user's own, then set CLEARED=0 try { JSONArray comments = new JSONObject(response) .getJSONArray(Sdata); int i2 = comments.length(); if (i2 > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); long created_time = comment.getLong(Screated_time) * 1000; if (created_time > updated) { // new comment ContentValues values = new ContentValues(); values.put(Notifications.UPDATED, created_time); JSONObject from = comment.getJSONObject(Sfrom); if (accountEsid.equals(from.getString(Sid))) { // user's own comment, clear the notification values.put(Notifications.CLEARED, 1); } else if (cleared) { values.put(Notifications.NOTIFICATION, String.format(getString( R.string.friendcommented), from.getString(Sname))); values.put(Notifications.CLEARED, 0); } else { values.put(Notifications.NOTIFICATION, String.format(getString( R.string.friendcommented), from.getString(Sname) + " and others")); } getContentResolver().update( Notifications.getContentUri( MyfeedleNotifications.this), values, Notifications._ID + "=?", new String[] { Long .toString(notificationId) }); } } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } currentNotifications.moveToNext(); } // check the latest feed if ((response = MyfeedleHttpClient.httpResponse(httpClient, new HttpGet(String.format(FACEBOOK_HOME, FACEBOOK_BASE_URL, Saccess_token, token)))) != null) { try { JSONArray jarr = new JSONObject(response).getJSONArray(Sdata); // if there are updates, clear the cache int d2 = jarr.length(); if (d2 > 0) { for (int d = 0; d < d2; d++) { JSONObject o = jarr.getJSONObject(d); String sid = o.getString(Sid); // if already notified, ignore if (!notificationSids.contains(sid)) { // only parse status types, not photo, video or link if (o.has(Stype) && o.has(Sfrom)) { JSONObject f = o.getJSONObject(Sfrom); if (f.has(Sname) && f.has(Sid)) { String notification = null; String esid = f.getString(Sid); String friend = f.getString(Sname); if (o.has(Sto)) { // handle wall messages from one friend to another JSONObject t = o.getJSONObject(Sto); if (t.has(Sdata)) { JSONObject n = t.getJSONArray(Sdata) .getJSONObject(0); if (n.has(Sname)) { if (n.has(Sid) && (n .getString(Sid) .equals(accountEsid))) { notification = String .format(getString( R.string.friendcommented), friend); } } } } int commentCount = 0; if (o.has(Scomments)) { JSONObject jo = o .getJSONObject(Scomments); if (jo.has(Sdata)) { JSONArray comments = jo .getJSONArray(Sdata); commentCount = comments.length(); // notifications if ((sid != null) && (commentCount > 0)) { // default hasCommented to whether or not these comments are for the own user's status boolean hasCommented = notification != null || esid.equals( accountEsid); for (int c2 = 0; c2 < commentCount; c2++) { JSONObject c3 = comments .getJSONObject(c2); if (c3.has(Sfrom)) { JSONObject c4 = c3 .getJSONObject( Sfrom); if (c4.getString(Sid) .equals(accountEsid)) { if (!hasCommented) { // the user has commented on this thread, notify any updates hasCommented = true; } // clear any notifications, as the user is already aware if (notification != null) { notification = null; } } else if (hasCommented) { // don't notify about user's own comments // send the parent comment sid notification = String .format(getString( R.string.friendcommented), c4.getString( Sname)); } } } } } } if (notification != null) { String message = o.has(Smessage) ? o.getString(Smessage) : null; if (!o.getString(Stype).equals(Sstatus) && o.has(Slink)) { message = message == null ? "[" + o.getString(Stype) + "]" : "[" + o.getString(Stype) + "]"; } // new notification addNotification(sid, esid, friend, message, o.getLong(Screated_time) * 1000, accountId, notification); } } } } } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } break; case MYSPACE: myfeedleOAuth = new MyfeedleOAuth(MYSPACE_KEY, MYSPACE_SECRET, token, secret); // loop over notifications while (!currentNotifications.isAfterLast()) { long notificationId = currentNotifications.getLong(0); String sid = mMyfeedleCrypto .Decrypt(currentNotifications.getString(1)); long updated = currentNotifications.getLong(2); boolean cleared = currentNotifications.getInt(3) == 1; String esid = mMyfeedleCrypto .Decrypt(currentNotifications.getString(4)); // store sids, to avoid duplicates when requesting the latest feed if (!notificationSids.contains(sid)) { notificationSids.add(sid); } // get comments for current notifications if ((response = MyfeedleHttpClient.httpResponse(httpClient, myfeedleOAuth.getSignedRequest(new HttpGet( String.format(MYSPACE_URL_STATUSMOODCOMMENTS, MYSPACE_BASE_URL, esid, sid))))) != null) { // check for a newer post, if it's the user's own, then set CLEARED=0 try { JSONArray comments = new JSONObject(response) .getJSONArray(Sentry); int i2 = comments.length(); if (i2 > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); long created_time = parseDate( comment.getString(SpostedDate), MYSPACE_DATE_FORMAT); if (created_time > updated) { // new comment ContentValues values = new ContentValues(); values.put(Notifications.UPDATED, created_time); JSONObject author = comment .getJSONObject(Sauthor); if (accountEsid.equals(author.getString(Sid))) { // user's own comment, clear the notification values.put(Notifications.CLEARED, 1); } else if (cleared) { values.put(Notifications.NOTIFICATION, String.format(getString( R.string.friendcommented), comment.getString( SdisplayName))); values.put(Notifications.CLEARED, 0); } else { values.put(Notifications.NOTIFICATION, String.format(getString( R.string.friendcommented), comment.getString( SdisplayName) + " and others")); } getContentResolver().update( Notifications.getContentUri( MyfeedleNotifications.this), values, Notifications._ID + "=?", new String[] { Long .toString(notificationId) }); } } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } currentNotifications.moveToNext(); } // check the latest feed if ((response = MyfeedleHttpClient .httpResponse(httpClient, myfeedleOAuth.getSignedRequest( new HttpGet(String.format(MYSPACE_HISTORY, MYSPACE_BASE_URL))))) != null) { try { JSONArray jarr = new JSONObject(response).getJSONArray(Sentry); // if there are updates, clear the cache int d2 = jarr.length(); if (d2 > 0) { for (int d = 0; d < d2; d++) { JSONObject o = jarr.getJSONObject(d); String sid = o.getString(SstatusId); // if already notified, ignore if (!notificationSids.contains(sid)) { if (o.has(Sauthor) && o.has(SrecentComments)) { JSONObject f = o.getJSONObject(Sauthor); if (f.has(SdisplayName) && f.has(Sid)) { String notification = null; String esid = f.getString(Sid); String friend = f.getString(SdisplayName); JSONArray comments = o .getJSONArray(SrecentComments); int commentCount = comments.length(); // notifications if ((sid != null) && (commentCount > 0)) { // default hasCommented to whether or not these comments are for the own user's status boolean hasCommented = notification != null || esid.equals(accountEsid); for (int c2 = 0; c2 < commentCount; c2++) { JSONObject c3 = comments .getJSONObject(c2); if (c3.has(Sauthor)) { JSONObject c4 = c3 .getJSONObject(Sauthor); if (c4.getString(Sid) .equals(accountEsid)) { if (!hasCommented) { // the user has commented on this thread, notify any updates hasCommented = true; } // clear any notifications, as the user is already aware if (notification != null) { notification = null; } } else if (hasCommented) { // don't notify about user's own comments // send the parent comment sid notification = String .format(getString( R.string.friendcommented), c4.getString( SdisplayName)); } } } } if (notification != null) { // new notification addNotification(sid, esid, friend, o.getString(Sstatus), parseDate(o.getString( "moodStatusLastUpdated"), MYSPACE_DATE_FORMAT), accountId, notification); } } } } } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } break; case FOURSQUARE: // loop over notifications while (!currentNotifications.isAfterLast()) { long notificationId = currentNotifications.getLong(0); String sid = mMyfeedleCrypto .Decrypt(currentNotifications.getString(1)); long updated = currentNotifications.getLong(2); boolean cleared = currentNotifications.getInt(3) == 1; // store sids, to avoid duplicates when requesting the latest feed if (!notificationSids.contains(sid)) { notificationSids.add(sid); } // get comments for current notifications if ((response = MyfeedleHttpClient.httpResponse(httpClient, new HttpGet(String.format(FOURSQUARE_GET_CHECKIN, FOURSQUARE_BASE_URL, sid, token)))) != null) { // check for a newer post, if it's the user's own, then set CLEARED=0 try { JSONArray comments = new JSONObject(response) .getJSONObject(Sresponse).getJSONObject(Scheckin) .getJSONObject(Scomments).getJSONArray(Sitems); int i2 = comments.length(); if (i2 > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); long created_time = comment.getLong(ScreatedAt) * 1000; if (created_time > updated) { // new comment ContentValues values = new ContentValues(); values.put(Notifications.UPDATED, created_time); JSONObject user = comment.getJSONObject(Suser); if (accountEsid.equals(user.getString(Sid))) { // user's own comment, clear the notification values.put(Notifications.CLEARED, 1); } else if (cleared) { values.put(Notifications.NOTIFICATION, String.format(getString( R.string.friendcommented), user.getString(SfirstName) + " " + user.getString( SlastName))); values.put(Notifications.CLEARED, 0); } else { values.put(Notifications.NOTIFICATION, String.format(getString( R.string.friendcommented), user.getString(SfirstName) + " " + user.getString( SlastName) + " and others")); } getContentResolver().update( Notifications.getContentUri( MyfeedleNotifications.this), values, Notifications._ID + "=?", new String[] { Long .toString(notificationId) }); } } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } currentNotifications.moveToNext(); } // check the latest feed if ((response = MyfeedleHttpClient.httpResponse(httpClient, new HttpGet(String.format(FOURSQUARE_CHECKINS, FOURSQUARE_BASE_URL, token)))) != null) { try { JSONArray jarr = new JSONObject(response) .getJSONObject(Sresponse).getJSONArray(Srecent); // if there are updates, clear the cache int d2 = jarr.length(); if (d2 > 0) { for (int d = 0; d < d2; d++) { JSONObject o = jarr.getJSONObject(d); String sid = o.getString(Sid); // if already notified, ignore if (!notificationSids.contains(sid)) { if (o.has(Suser) && o.has(Scomments)) { JSONObject f = o.getJSONObject(Suser); if (f.has(SfirstName) && f.has(SlastName) && f.has(Sid)) { String notification = null; String esid = f.getString(Sid); String friend = f.getString(SfirstName) + " " + f.getString(SlastName); JSONArray comments = o .getJSONArray(Scomments); int commentCount = comments.length(); // notifications if (commentCount > 0) { // default hasCommented to whether or not these comments are for the own user's status boolean hasCommented = notification != null || esid.equals(accountEsid); for (int c2 = 0; c2 < commentCount; c2++) { JSONObject c3 = comments .getJSONObject(c2); if (c3.has(Suser)) { JSONObject c4 = c3 .getJSONObject(Suser); if (c4.getString(Sid) .equals(accountEsid)) { if (!hasCommented) { // the user has commented on this thread, notify any updates hasCommented = true; } // clear any notifications, as the user is already aware if (notification != null) { notification = null; } } else if (hasCommented) { // don't notify about user's own comments // send the parent comment sid notification = String .format(getString( R.string.friendcommented), c4.getString( SfirstName) + " " + c4.getString( SlastName)); } } } } if (notification != null) { String message = ""; if (o.has(Sshout)) { message = o.getString(Sshout) + "\n"; } if (o.has(Svenue)) { JSONObject venue = o .getJSONObject(Svenue); if (venue.has(Sname)) { message += "@" + venue .getString(Sname); } } // new notification addNotification(sid, esid, friend, message, o.getLong(ScreatedAt) * 1000, accountId, notification); } } } } } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } break; case LINKEDIN: myfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, LINKEDIN_SECRET, token, secret); // loop over notifications while (!currentNotifications.isAfterLast()) { long notificationId = currentNotifications.getLong(0); String sid = mMyfeedleCrypto .Decrypt(currentNotifications.getString(1)); long updated = currentNotifications.getLong(2); boolean cleared = currentNotifications.getInt(3) == 1; // store sids, to avoid duplicates when requesting the latest feed if (!notificationSids.contains(sid)) { notificationSids.add(sid); } // get comments for current notifications HttpGet httpGet = new HttpGet(String .format(LINKEDIN_UPDATE_COMMENTS, LINKEDIN_BASE_URL, sid)); for (String[] header : LINKEDIN_HEADERS) httpGet.setHeader(header[0], header[1]); if ((response = MyfeedleHttpClient.httpResponse(httpClient, myfeedleOAuth.getSignedRequest(httpGet))) != null) { // check for a newer post, if it's the user's own, then set CLEARED=0 try { JSONObject jsonResponse = new JSONObject(response); if (jsonResponse.has(S_total) && (jsonResponse.getInt(S_total) != 0)) { JSONArray comments = jsonResponse.getJSONArray(Svalues); int i2 = comments.length(); if (i2 > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); long created_time = comment.getLong(Stimestamp); if (created_time > updated) { // new comment ContentValues values = new ContentValues(); values.put(Notifications.UPDATED, created_time); JSONObject person = comment .getJSONObject(Sperson); if (accountEsid .equals(person.getString(Sid))) { // user's own comment, clear the notification values.put(Notifications.CLEARED, 1); } else if (cleared) { values.put(Notifications.NOTIFICATION, String.format(getString( R.string.friendcommented), person.getString( SfirstName) + " " + person.getString( SlastName))); values.put(Notifications.CLEARED, 0); } else { values.put(Notifications.NOTIFICATION, String.format(getString( R.string.friendcommented), person.getString( SfirstName) + " " + person.getString( SlastName) + " and others")); } getContentResolver().update( Notifications.getContentUri( MyfeedleNotifications.this), values, Notifications._ID + "=?", new String[] { Long.toString( notificationId) }); } } } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } currentNotifications.moveToNext(); } // check the latest feed HttpGet httpGet = new HttpGet( String.format(LINKEDIN_UPDATES, LINKEDIN_BASE_URL)); for (String[] header : LINKEDIN_HEADERS) { httpGet.setHeader(header[0], header[1]); } if ((response = MyfeedleHttpClient.httpResponse(httpClient, myfeedleOAuth.getSignedRequest(httpGet))) != null) { try { JSONArray jarr = new JSONObject(response).getJSONArray(Svalues); // if there are updates, clear the cache int d2 = jarr.length(); if (d2 > 0) { for (int d = 0; d < d2; d++) { JSONObject o = jarr.getJSONObject(d); String sid = o.getString(SupdateKey); // if already notified, ignore if (!notificationSids.contains(sid)) { String updateType = o.getString(SupdateType); JSONObject updateContent = o .getJSONObject(SupdateContent); if (LinkedIn_UpdateTypes.contains(updateType) && updateContent.has(Sperson)) { JSONObject f = updateContent .getJSONObject(Sperson); if (f.has(SfirstName) && f.has(SlastName) && f.has(Sid) && o.has(SupdateComments)) { JSONObject updateComments = o .getJSONObject(SupdateComments); if (updateComments.has(Svalues)) { String notification = null; String esid = f.getString(Sid); JSONArray comments = updateComments .getJSONArray(Svalues); int commentCount = comments.length(); // notifications if (commentCount > 0) { // default hasCommented to whether or not these comments are for the own user's status boolean hasCommented = notification != null || esid.equals(accountEsid); for (int c2 = 0; c2 < commentCount; c2++) { JSONObject c3 = comments .getJSONObject(c2); if (c3.has(Sperson)) { JSONObject c4 = c3 .getJSONObject( Sperson); if (c4.getString(Sid) .equals(accountEsid)) { if (!hasCommented) { // the user has commented on this thread, notify any updates hasCommented = true; } // clear any notifications, as the user is already aware if (notification != null) { notification = null; } } else if (hasCommented) { // don't notify about user's own comments // send the parent comment sid notification = String .format(getString( R.string.friendcommented), c4.getString( SfirstName) + " " + c4.getString( SlastName)); } } } } if (notification != null) { String update = LinkedIn_UpdateTypes .getMessage(updateType); if (LinkedIn_UpdateTypes.APPS.name() .equals(updateType)) { if (f.has(SpersonActivities)) { JSONObject personActivities = f .getJSONObject( SpersonActivities); if (personActivities .has(Svalues)) { JSONArray updates = personActivities .getJSONArray( Svalues); for (int u = 0, u2 = updates .length(); u < u2; u++) { update += updates .getJSONObject( u) .getString( Sbody); if (u < (updates .length() - 1)) update += ", "; } } } } else if (LinkedIn_UpdateTypes.CONN .name() .equals(updateType)) { if (f.has(Sconnections)) { JSONObject connections = f .getJSONObject( Sconnections); if (connections .has(Svalues)) { JSONArray updates = connections .getJSONArray( Svalues); for (int u = 0, u2 = updates .length(); u < u2; u++) { update += updates .getJSONObject( u) .getString( SfirstName) + " " + updates .getJSONObject( u) .getString( SlastName); if (u < (updates .length() - 1)) update += ", "; } } } } else if (LinkedIn_UpdateTypes.JOBP .name() .equals(updateType)) { if (updateContent.has(Sjob) && updateContent .getJSONObject( Sjob) .has(Sposition) && updateContent .getJSONObject( Sjob) .getJSONObject( Sposition) .has(Stitle)) update += updateContent .getJSONObject(Sjob) .getJSONObject( Sposition) .getString(Stitle); } else if (LinkedIn_UpdateTypes.JGRP .name() .equals(updateType)) { if (f.has(SmemberGroups)) { JSONObject memberGroups = f .getJSONObject( SmemberGroups); if (memberGroups .has(Svalues)) { JSONArray updates = memberGroups .getJSONArray( Svalues); for (int u = 0, u2 = updates .length(); u < u2; u++) { update += updates .getJSONObject( u) .getString( Sname); if (u < (updates .length() - 1)) update += ", "; } } } } else if (LinkedIn_UpdateTypes.PREC .name() .equals(updateType)) { if (f.has( SrecommendationsGiven)) { JSONObject recommendationsGiven = f .getJSONObject( SrecommendationsGiven); if (recommendationsGiven .has(Svalues)) { JSONArray updates = recommendationsGiven .getJSONArray( Svalues); for (int u = 0, u2 = updates .length(); u < u2; u++) { JSONObject recommendation = updates .getJSONObject( u); JSONObject recommendee = recommendation .getJSONObject( Srecommendee); if (recommendee.has( SfirstName)) update += recommendee .getString( SfirstName); if (recommendee.has( SlastName)) update += recommendee .getString( SlastName); if (recommendation .has(SrecommendationSnippet)) update += ":" + recommendation .getString( SrecommendationSnippet); if (u < (updates .length() - 1)) update += ", "; } } } } else if (LinkedIn_UpdateTypes.SHAR .name().equals(updateType) && f.has(ScurrentShare)) { JSONObject currentShare = f .getJSONObject( ScurrentShare); if (currentShare.has(Scomment)) update = currentShare .getString( Scomment); } // new notification addNotification(sid, esid, f.getString(SfirstName) + " " + f.getString( SlastName), update, o.getLong(Stimestamp), accountId, notification); } } } } } } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } break; case GOOGLEPLUS: // get new access token, need different request here HttpPost httpPost = new HttpPost(GOOGLE_ACCESS); List<NameValuePair> httpParams = new ArrayList<NameValuePair>(); httpParams.add(new BasicNameValuePair("client_id", GOOGLE_CLIENTID)); httpParams.add( new BasicNameValuePair("client_secret", GOOGLE_CLIENTSECRET)); httpParams.add(new BasicNameValuePair("refresh_token", token)); httpParams.add(new BasicNameValuePair("grant_type", "refresh_token")); try { httpPost.setEntity(new UrlEncodedFormEntity(httpParams)); if ((response = MyfeedleHttpClient.httpResponse(httpClient, httpPost)) != null) { JSONObject j = new JSONObject(response); if (j.has(Saccess_token)) { String access_token = j.getString(Saccess_token); while (!currentNotifications.isAfterLast()) { long notificationId = currentNotifications.getLong(0); String sid = mMyfeedleCrypto .Decrypt(currentNotifications.getString(1)); long updated = currentNotifications.getLong(2); boolean cleared = currentNotifications.getInt(3) == 1; // store sids, to avoid duplicates when requesting the latest feed if (!notificationSids.contains(sid)) { notificationSids.add(sid); } // get comments for current notifications if ((response = MyfeedleHttpClient.httpResponse( httpClient, new HttpGet(String.format(GOOGLEPLUS_ACTIVITY, GOOGLEPLUS_BASE_URL, sid, access_token)))) != null) { // check for a newer post, if it's the user's own, then set CLEARED=0 try { JSONObject item = new JSONObject(response); if (item.has(Sobject)) { JSONObject object = item .getJSONObject(Sobject); if (object.has(Sreplies)) { int commentCount = 0; JSONObject replies = object .getJSONObject(Sreplies); if (replies.has(StotalItems)) { //TODO: notifications } } } } catch (JSONException e) { Log.e(TAG, service + ":" + e.toString()); } } currentNotifications.moveToNext(); } // get new feed if ((response = MyfeedleHttpClient.httpResponse(httpClient, new HttpGet(String.format(GOOGLEPLUS_ACTIVITIES, GOOGLEPLUS_BASE_URL, "me", "public", 20, access_token)))) != null) { JSONObject r = new JSONObject(response); if (r.has(Sitems)) { JSONArray items = r.getJSONArray(Sitems); for (int i1 = 0, i2 = items .length(); i1 < i2; i1++) { JSONObject item = items.getJSONObject(i1); if (item.has(Sactor) && item.has(Sobject)) { JSONObject actor = item .getJSONObject(Sactor); JSONObject object = item .getJSONObject(Sobject); if (item.has(Sid) && actor.has(Sid) && actor.has(SdisplayName) && item.has(Spublished) && object.has(Sreplies) && object.has(SoriginalContent)) { String sid = item.getString(Sid); String esid = actor.getString(Sid); String friend = actor .getString(SdisplayName); String originalContent = object .getString(SoriginalContent); if ((originalContent == null) || (originalContent .length() == 0)) { originalContent = object .getString(Scontent); } String photo = null; if (actor.has(Simage)) { JSONObject image = actor .getJSONObject(Simage); if (image.has(Surl)) { photo = image.getString(Surl); } } long date = parseDate( item.getString(Spublished), GOOGLEPLUS_DATE_FORMAT); int commentCount = 0; JSONObject replies = object .getJSONObject(Sreplies); String notification = null; if (replies.has(StotalItems)) { Log.d(TAG, Sreplies + ":" + replies.toString()); commentCount = replies .getInt(StotalItems); } if (notification != null) { // new notification addNotification(sid, esid, friend, originalContent, date, accountId, notification); } } } } } } } } } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } catch (JSONException e) { Log.e(TAG, e.toString()); } break; } } currentNotifications.close(); } // remove old notifications getContentResolver().delete(Notifications.getContentUri(MyfeedleNotifications.this), Notifications.CLEARED + "=1 and " + Notifications.ACCOUNT + "=? and " + Notifications.CREATED + "<?", new String[] { Long.toString(accountId), Long.toString(System.currentTimeMillis() - 86400000) }); } account.close(); widgets.moveToNext(); } } else { publishProgress("No notifications have been set up on any accounts."); } widgets.close(); return false; } else if (arg0[0] == R.id.menu_notifications_clear_all) { // clear all notifications ContentValues values = new ContentValues(); values.put(Notifications.CLEARED, 1); MyfeedleNotifications.this.getContentResolver() .update(Notifications.getContentUri(MyfeedleNotifications.this), values, null, null); return true; } return false; } @Override protected void onProgressUpdate(String... messages) { (Toast.makeText(MyfeedleNotifications.this, messages[0], Toast.LENGTH_LONG)).show(); } @Override protected void onPostExecute(Boolean finish) { if (loadingDialog.isShowing()) { loadingDialog.dismiss(); } if (finish) { MyfeedleNotifications.this.finish(); } } private void addNotification(String sid, String esid, String friend, String message, long created, long accountId, String notification) { ContentValues values = new ContentValues(); values.put(Notifications.SID, sid); values.put(Notifications.ESID, esid); values.put(Notifications.FRIEND, friend); values.put(Notifications.MESSAGE, message); values.put(Notifications.CREATED, created); values.put(Notifications.ACCOUNT, accountId); values.put(Notifications.NOTIFICATION, notification); values.put(Notifications.CLEARED, 0); values.put(Notifications.UPDATED, created); getContentResolver().insert(Notifications.getContentUri(MyfeedleNotifications.this), values); } private long parseDate(String date, String format) { if (date != null) { // hack for the literal 'Z' if (date.substring(date.length() - 1).equals("Z")) { date = date.substring(0, date.length() - 2) + "+0000"; } Date created = null; if (format != null) { if (mSimpleDateFormat == null) { mSimpleDateFormat = new SimpleDateFormat(format, Locale.ENGLISH); // all dates should be GMT/UTC mSimpleDateFormat.setTimeZone(sTimeZone); } try { created = mSimpleDateFormat.parse(date); return created.getTime(); } catch (ParseException e) { Log.e(TAG, e.toString()); } } else { // attempt to parse RSS date if (mSimpleDateFormat != null) { try { created = mSimpleDateFormat.parse(date); return created.getTime(); } catch (ParseException e) { Log.e(TAG, e.toString()); } } for (String rfc822 : sRFC822) { mSimpleDateFormat = new SimpleDateFormat(rfc822, Locale.ENGLISH); mSimpleDateFormat.setTimeZone(sTimeZone); try { if ((created = mSimpleDateFormat.parse(date)) != null) { return created.getTime(); } } catch (ParseException e) { Log.e(TAG, e.toString()); } } } } return System.currentTimeMillis(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); loadingDialog.show(); asyncTask.execute(item.getItemId()); return true; // return super.onOptionsItemSelected(item); }
From source file:com.piusvelte.sonet.SonetCreatePost.java
private void setLocation(final long accountId) { final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() { int serviceId; @Override//w w w. j av a 2s . c o m protected String doInBackground(Void... none) { Cursor account = getContentResolver().query(Accounts.getContentUri(SonetCreatePost.this), new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SERVICE, Accounts.SECRET }, Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null); if (account.moveToFirst()) { SonetOAuth sonetOAuth; serviceId = account.getInt(account.getColumnIndex(Accounts.SERVICE)); switch (serviceId) { case TWITTER: // anonymous requests are rate limited to 150 per hour // authenticated requests are rate limited to 350 per hour, so authenticate this! sonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET, mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))), mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET)))); return SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest( new HttpGet(String.format(TWITTER_SEARCH, TWITTER_BASE_URL, mLat, mLong)))); case FACEBOOK: return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(FACEBOOK_SEARCH, FACEBOOK_BASE_URL, mLat, mLong, Saccess_token, mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN)))))); case FOURSQUARE: return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format( FOURSQUARE_SEARCH, FOURSQUARE_BASE_URL, mLat, mLong, mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN)))))); } } account.close(); return null; } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { switch (serviceId) { case TWITTER: try { JSONArray places = new JSONObject(response).getJSONObject(Sresult) .getJSONArray(Splaces); final String placesNames[] = new String[places.length()]; final String placesIds[] = new String[places.length()]; for (int i = 0, i2 = places.length(); i < i2; i++) { JSONObject place = places.getJSONObject(i); placesNames[i] = place.getString(Sfull_name); placesIds[i] = place.getString(Sid); } mDialog = (new AlertDialog.Builder(SonetCreatePost.this)) .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mAccountsLocation.put(accountId, placesIds[which]); dialog.dismiss(); } }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .create(); mDialog.show(); } catch (JSONException e) { Log.e(TAG, e.toString()); } break; case FACEBOOK: try { JSONArray places = new JSONObject(response).getJSONArray(Sdata); final String placesNames[] = new String[places.length()]; final String placesIds[] = new String[places.length()]; for (int i = 0, i2 = places.length(); i < i2; i++) { JSONObject place = places.getJSONObject(i); placesNames[i] = place.getString(Sname); placesIds[i] = place.getString(Sid); } mDialog = (new AlertDialog.Builder(SonetCreatePost.this)) .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mAccountsLocation.put(accountId, placesIds[which]); dialog.dismiss(); } }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .create(); mDialog.show(); } catch (JSONException e) { Log.e(TAG, e.toString()); } break; case FOURSQUARE: try { JSONArray groups = new JSONObject(response).getJSONObject(Sresponse) .getJSONArray(Sgroups); for (int g = 0, g2 = groups.length(); g < g2; g++) { JSONObject group = groups.getJSONObject(g); if (group.getString(Sname).equals(SNearby)) { JSONArray places = group.getJSONArray(Sitems); final String placesNames[] = new String[places.length()]; final String placesIds[] = new String[places.length()]; for (int i = 0, i2 = places.length(); i < i2; i++) { JSONObject place = places.getJSONObject(i); placesNames[i] = place.getString(Sname); placesIds[i] = place.getString(Sid); } mDialog = (new AlertDialog.Builder(SonetCreatePost.this)) .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mAccountsLocation.put(accountId, placesIds[which]); dialog.dismiss(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .create(); mDialog.show(); break; } } } catch (JSONException e) { Log.e(TAG, e.toString()); } break; } } else { (Toast.makeText(SonetCreatePost.this, getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); loadingDialog.show(); asyncTask.execute(); }
From source file:com.piusvelte.sonet.core.SonetCreatePost.java
private void setLocation(final long accountId) { final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() { int serviceId; @Override// w w w . j a v a 2 s .co m protected String doInBackground(Void... none) { Cursor account = getContentResolver().query(Accounts.getContentUri(SonetCreatePost.this), new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SERVICE, Accounts.SECRET }, Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null); if (account.moveToFirst()) { SonetOAuth sonetOAuth; serviceId = account.getInt(account.getColumnIndex(Accounts.SERVICE)); switch (serviceId) { case TWITTER: // anonymous requests are rate limited to 150 per hour // authenticated requests are rate limited to 350 per hour, so authenticate this! sonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET, mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))), mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET)))); return SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest( new HttpGet(String.format(TWITTER_SEARCH, TWITTER_BASE_URL, mLat, mLong)))); case FACEBOOK: return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(FACEBOOK_SEARCH, FACEBOOK_BASE_URL, mLat, mLong, Saccess_token, mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN)))))); case FOURSQUARE: return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format( FOURSQUARE_SEARCH, FOURSQUARE_BASE_URL, mLat, mLong, mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN)))))); } } account.close(); return null; } @Override protected void onPostExecute(String response) { if (loadingDialog.isShowing()) loadingDialog.dismiss(); if (response != null) { switch (serviceId) { case TWITTER: try { JSONArray places = new JSONObject(response).getJSONObject(Sresult) .getJSONArray(Splaces); final String placesNames[] = new String[places.length()]; final String placesIds[] = new String[places.length()]; for (int i = 0, i2 = places.length(); i < i2; i++) { JSONObject place = places.getJSONObject(i); placesNames[i] = place.getString(Sfull_name); placesIds[i] = place.getString(Sid); } mDialog = (new AlertDialog.Builder(SonetCreatePost.this)) .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mAccountsLocation.put(accountId, placesIds[which]); dialog.dismiss(); } }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .create(); mDialog.show(); } catch (JSONException e) { Log.e(TAG, e.toString()); } break; case FACEBOOK: try { JSONArray places = new JSONObject(response).getJSONArray(Sdata); final String placesNames[] = new String[places.length()]; final String placesIds[] = new String[places.length()]; for (int i = 0, i2 = places.length(); i < i2; i++) { JSONObject place = places.getJSONObject(i); placesNames[i] = place.getString(Sname); placesIds[i] = place.getString(Sid); } mDialog = (new AlertDialog.Builder(SonetCreatePost.this)) .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mAccountsLocation.put(accountId, placesIds[which]); dialog.dismiss(); } }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .create(); mDialog.show(); } catch (JSONException e) { Log.e(TAG, e.toString()); } break; case FOURSQUARE: try { JSONArray groups = new JSONObject(response).getJSONObject(Sresponse) .getJSONArray(Sgroups); for (int g = 0, g2 = groups.length(); g < g2; g++) { JSONObject group = groups.getJSONObject(g); if (group.getString(Sname).equals(SNearby)) { JSONArray places = group.getJSONArray(Sitems); final String placesNames[] = new String[places.length()]; final String placesIds[] = new String[places.length()]; for (int i = 0, i2 = places.length(); i < i2; i++) { JSONObject place = places.getJSONObject(i); placesNames[i] = place.getString(Sname); placesIds[i] = place.getString(Sid); } mDialog = (new AlertDialog.Builder(SonetCreatePost.this)) .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mAccountsLocation.put(accountId, placesIds[which]); dialog.dismiss(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .create(); mDialog.show(); break; } } } catch (JSONException e) { Log.e(TAG, e.toString()); } break; } } else { (Toast.makeText(SonetCreatePost.this, getString(R.string.failure), Toast.LENGTH_LONG)).show(); } } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); loadingDialog.show(); asyncTask.execute(); }
From source file:net.gerosyab.dailylog.activity.MainActivity.java
private void importCategory() { DialogProperties properties = new DialogProperties(); properties.selection_mode = DialogConfigs.SINGLE_MODE; properties.selection_type = DialogConfigs.FILE_SELECT; properties.root = new File(DialogConfigs.DEFAULT_DIR); properties.extensions = null;// www . j a va 2 s . c om dialog = new FilePickerDialog(MainActivity.this, properties); dialog.setDialogSelectionListener(new DialogSelectionListener() { @Override public void onSelectedFilePaths(String[] files) { ProgressDialog progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressDialog.setTitle("Importing data [" + files[0] + "]"); progressDialog.show(); //files is the array of the paths of files selected by the Application User. try { String newCategoryUUID = UUID.randomUUID().toString(); // CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(files[0]), "UTF-8"), '\t'); CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(files[0]), "UTF-8"), ','); String[] nextLine; long lineNum = 0; boolean dbVersionCheck = false, categoryNameCheck = false, categoryUnitCheck = false; boolean categoryTypeCheck = false, defaultValueCheck = false, headerCheck = false; boolean isCategoryNameExists = false, rowDataCheck = false, dataCheck = false; String dbVersion = null, categoryName = null, categoryUnit = null; long categoryType = -1, defaultValue = -1; // Category category = null; List<Record> records = new ArrayList<Record>(); while ((nextLine = reader.readNext()) != null) { // nextLine[] is an array of values from the line String temp2 = ""; for (int i = 0; i < nextLine.length; i++) { temp2 += nextLine[i] + ", "; } MyLog.d("opencsv", temp2); if (lineNum == 0) { //header MyLog.d("opencsv", "nextLine.length : " + nextLine.length); for (int i = 0; i < nextLine.length; i++) { String[] split2 = nextLine[i].split(":"); MyLog.d("opencsv", "split2.length : " + split2.length); MyLog.d("opencsv", "split2[0] : " + split2[0]); if (split2[0].replaceAll("\\s+", "").equals("Version")) { if (split2[1] != null && !split2[1].equals("")) { dbVersion = split2[1]; dbVersionCheck = true; } } else if (split2[0].replaceAll("\\s+", "").equals("Name")) { if (split2[1] != null && !split2[1].equals("")) { categoryName = split2[1]; if (categoryName.length() <= Category.getMaxCategoryNameLength()) { categoryNameCheck = true; } } } else if (split2[0].replaceAll("\\s+", "").equals("Unit")) { if (split2.length == 1) { categoryUnitCheck = true; } else if (split2[1] != null && !split2[1].equals("")) { categoryUnit = split2[1]; categoryUnitCheck = true; } } else if (split2[0].replaceAll("\\s+", "").equals("Type")) { if (split2[1] != null && !split2[1].equals("")) { if (split2[1].equals("0") || split2[1].equals("1") || split2[1].equals("2")) { categoryType = Long.parseLong(split2[1]); categoryTypeCheck = true; } } } else if (split2[0].replaceAll("\\s+", "").equals("DefaultValue")) { if (split2.length == 1) { defaultValueCheck = true; } else if (split2[1] != null && !split2[1].equals("")) { if (NumberUtils.isDigits(split2[1]) && NumberUtils.isNumber(split2[1])) { defaultValue = Long.parseLong(split2[1]); MyLog.d("opencsv", "split2[1] : " + split2[1]); if (defaultValue >= 0) { defaultValueCheck = true; } } } } } if (dbVersionCheck && categoryNameCheck && categoryTypeCheck) { if (categoryType == 1) { //number if (categoryUnitCheck && defaultValueCheck) { headerCheck = true; } } else { //boolean, string headerCheck = true; } } if (!headerCheck) { break; //header parsing, data checking failed } else if (Category.isCategoryNameExists(realm, categoryName)) { isCategoryNameExists = true; break; } else { // category = new Category(categoryName, categoryUnit, Category.getLastOrderNum(realm), categoryType); } } else { //data Record record; rowDataCheck = true; if (nextLine.length != 2) { rowDataCheck = false; break; } else { record = new Record(); record.setRecordType(categoryType); DateTime dateTime = StaticData.fmtForBackup.parseDateTime(nextLine[0]); if (dateTime != null) { record.setDate(new java.sql.Date(dateTime.toDate().getTime())); } else { rowDataCheck = false; break; } if (categoryType == StaticData.RECORD_TYPE_BOOLEAN) { if (nextLine[1].equals("true")) { record.setBool(true); } else { rowDataCheck = false; break; } } else if (categoryType == StaticData.RECORD_TYPE_NUMBER) { if (NumberUtils.isNumber(nextLine[1]) && NumberUtils.isDigits(nextLine[1])) { long value = Long.parseLong(nextLine[1]); if (value > Category.getMaxValue()) { rowDataCheck = false; break; } else { record.setNumber(value); } } else { dataCheck = false; break; } } else if (categoryType == StaticData.RECORD_TYPE_MEMO) { String value = nextLine[1]; if (value.length() > Category.getMaxMemoLength()) { rowDataCheck = false; break; } else { record.setString(nextLine[1]); } } } if (record != null && rowDataCheck == true) { record.setCategoryId(newCategoryUUID); record.setRecordId(UUID.randomUUID().toString()); records.add(record); } } lineNum++; } if (!headerCheck) { Toast.makeText(context, "Data file's header context/value is not correct", Toast.LENGTH_LONG).show(); } else if (isCategoryNameExists) { Toast.makeText(context, "Category Name [" + categoryName + "] is already exists", Toast.LENGTH_LONG).show(); } else if (!rowDataCheck) { Toast.makeText(context, "Data file's record data is not correct", Toast.LENGTH_LONG).show(); } else { long newOrder = Category.getNewOrderNum(realm); realm.beginTransaction(); Category category = realm.createObject(Category.class, newCategoryUUID); category.setName(categoryName); category.setUnit(categoryUnit); category.setOrder(newOrder); category.setRecordType(categoryType); realm.insert(category); realm.insertOrUpdate(records); realm.commitTransaction(); Toast.makeText(context, "Data import [ " + categoryName + " ] is completed!!", Toast.LENGTH_LONG).show(); // refreshList(); // categoryHolderList.add(getHolderFromCategory(category)); // mDragListView.getAdapter().notifyDataSetChanged(); // mDragListView.getAdapter().notifyItemInserted((int) newOrder); // setCategoryHolderList(); // mDragListView.getAdapter().setItemList(categoryHolderList); adapter.notifyDataSetChanged(); } } catch (FileNotFoundException e) { Toast.makeText(context, "Selected file is not found", Toast.LENGTH_LONG).show(); e.printStackTrace(); } catch (IOException e) { Toast.makeText(context, "File I/O exception occured", Toast.LENGTH_LONG).show(); e.printStackTrace(); } finally { progressDialog.dismiss(); } } }); dialog.show(); }
From source file:net.networksaremadeofstring.rhybudd.ViewZenossEvent.java
private void AddLogMessage(final String Message) { addMessageProgressDialog = new ProgressDialog(this); addMessageProgressDialog.setTitle("Contacting Zenoss"); addMessageProgressDialog.setMessage("Please wait:\nProcessing Event Log Updates"); addMessageProgressDialog.show();//from ww w . j av a2 s . com addLogMessageHandler = new Handler() { public void handleMessage(Message msg) { addMessageProgressDialog.dismiss(); if (msg.what == 1) { try { /*String[] tmp = LogEntries.clone(); final int NewArrlength = tmp.length + 1; LogEntries = new String[NewArrlength]; LogEntries[0] = settings.getString("userName", "") + " wrote " + Message + "\nAt: Just now";*/ /*for (int i = 1; i < NewArrlength; ++i) // { LogEntries[i] = tmp[(i -1)]; } tmp = null;//help out the GC ((ListView) findViewById(R.id.LogList)).setAdapter(new ArrayAdapter<String>(ViewZenossEvent.this, R.layout.search_simple,LogEntries));*/ TextView newLog = new TextView(ViewZenossEvent.this); newLog.setText(Html.fromHtml("<strong>" + settings.getString("userName", "") + "</strong> wrote " + Message + "\n<br/><strong>At:</strong> Just now")); newLog.setPadding(0, 6, 0, 6); ((LinearLayout) findViewById(R.id.LogList)).addView(newLog); } catch (Exception e) { BugSenseHandler.sendExceptionMessage("ViewZenossEvent", "AddMessageProgressHandler", e); Toast.makeText(ViewZenossEvent.this, "The log message was successfully sent to Zenoss but an error occured when updating the UI", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(ViewZenossEvent.this, "An error was encountered adding your message to the log", Toast.LENGTH_LONG).show(); } } }; addLogMessageThread = new Thread() { public void run() { Boolean Success = false; try { if (API == null) { if (settings.getBoolean(ZenossAPI.PREFERENCE_IS_ZAAS, false)) { API = new ZenossAPIZaas(); } else { API = new ZenossAPICore(); } ZenossCredentials credentials = new ZenossCredentials(ViewZenossEvent.this); API.Login(credentials); } Success = API.AddEventLog(getIntent().getStringExtra("EventID"), Message); } catch (Exception e) { BugSenseHandler.sendExceptionMessage("ViewZenossEvent", "AddLogMessageThread", e); addLogMessageHandler.sendEmptyMessage(0); } if (Success) { addLogMessageHandler.sendEmptyMessage(1); } else { addLogMessageHandler.sendEmptyMessage(0); } } }; addLogMessageThread.start(); }
From source file:com.zigvine.zagriculture.UIActivity.java
private void manualUpdateCheck() { final ProgressDialog pd = new ProgressDialog(this); pd.setMessage(""); pd.setCanceledOnTouchOutside(false); pd.show();/*from w w w . j av a2 s . c om*/ MainApp.getInstance().startCheck(new UpdateCheckListener() { @Override public void onCheckedOver(int result) { pd.dismiss(); if (result == MainApp.CHECKED_NO_NEED) { UI.toast("?"); } else if (result == MainApp.UNCHECKED) { UI.toast(""); } } }, true); }
From source file:com.chaturs.notepad.NoteEditor.java
@Override protected Dialog onCreateDialog(int id) { switch (id) { case SELECT_STUDY_GROUP: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(" Select Study Group(s)"); final CharSequence[] charArray = new CharSequence[studyGroupNames.size()]; for (int i = 0; i < studyGroupNames.size(); i++) { charArray[i] = studyGroupNames.get(i).substring(0); }//from w ww.j a v a2s.c om builder.setMultiChoiceItems(charArray, null, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int which, boolean isChecked) { if (isChecked) { selectedStudyGroupList.add(studyGroupList.get(which)); } else { if (!selectedStudyGroupList.isEmpty()) { selectedStudyGroupList.remove(studyGroupList.get(which)); } } } }); builder.setPositiveButton("Send", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (selectedStudyGroupList.isEmpty()) { Toast.makeText(getApplicationContext(), "No option selected to send", Toast.LENGTH_SHORT) .show(); return; } if (title == null) { title = "Sample Note"; } DatabaseHandler databaseHandler = DatabaseHandler.getInstance(); String text = mText.getText().toString(); if (text == null || text.length() == 0) { text = "empty Note"; } StringBuffer Ids = new StringBuffer(); for (int i = 0; i < selectedStudyGroupList.size(); i++) { if (Ids.length() > 0) { Ids.append("|"); } long id = selectedStudyGroupList.get(i).getServerId(); Ids.append(id); } String user = preferences.getString(KEY_USERNAME, "android"); note = new Note(Ids.toString(), title, text, user, ""); selectedStudyGroupList.clear(); dismissDialog(SELECT_STUDY_GROUP); showDialog(PROGRESS_DIALOG_KEY); new Thread(new Runnable() { public void run() { response = postData(); handler.sendEmptyMessage(0); } }).start(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); Dialog dialog = builder.create(); return dialog; case PROGRESS_DIALOG_KEY: ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setMessage("sending...."); progressDialog.setIndeterminate(true); return progressDialog; } return null; }
From source file:de.ub0r.android.callmeter.ui.prefs.Preferences.java
/** * Export data./*from w w w .ja va 2s .com*/ * * @param descr * description of the exported rule set * @param fn * one of the predefined file names from {@link DataProvider}. */ private void exportData(final String descr, final String fn) { if (descr == null) { final EditText et = new EditText(this); Builder builder = new Builder(this); builder.setView(et); builder.setCancelable(true); builder.setTitle(R.string.export_rules_descr); builder.setNegativeButton(android.R.string.cancel, null); builder.setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { Preferences.this.exportData(et.getText().toString(), fn); } }); builder.show(); } else { final ProgressDialog d = new ProgressDialog(this); d.setIndeterminate(true); d.setMessage(this.getString(R.string.export_progr)); d.setCancelable(false); d.show(); // run task in background final AsyncTask<Void, Void, String> task = // . new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(final Void... params) { if (fn.equals(DataProvider.EXPORT_RULESET_FILE)) { return DataProvider.backupRuleSet(Preferences.this, descr); } else if (fn.equals(DataProvider.EXPORT_LOGS_FILE)) { return DataProvider.backupLogs(Preferences.this, descr); } else if (fn.equals(DataProvider.EXPORT_NUMGROUPS_FILE)) { return DataProvider.backupNumGroups(Preferences.this, descr); } else if (fn.equals(DataProvider.EXPORT_HOURGROUPS_FILE)) { return DataProvider.backupHourGroups(Preferences.this, descr); } return null; } @Override protected void onPostExecute(final String result) { Log.d(TAG, "export:\n" + result); System.out.println("\n" + result); d.dismiss(); if (result != null && result.length() > 0) { Uri uri = null; int resChooser = -1; if (fn.equals(DataProvider.EXPORT_RULESET_FILE)) { uri = DataProvider.EXPORT_RULESET_URI; resChooser = R.string.export_rules_; } else if (fn.equals(DataProvider.EXPORT_LOGS_FILE)) { uri = DataProvider.EXPORT_LOGS_URI; resChooser = R.string.export_logs_; } else if (fn.equals(DataProvider.EXPORT_NUMGROUPS_FILE)) { uri = DataProvider.EXPORT_NUMGROUPS_URI; resChooser = R.string.export_numgroups_; } else if (fn.equals(DataProvider.EXPORT_HOURGROUPS_FILE)) { uri = DataProvider.EXPORT_HOURGROUPS_URI; resChooser = R.string.export_hourgroups_; } final Intent intent = new Intent(Intent.ACTION_SEND); intent.setType(DataProvider.EXPORT_MIMETYPE); intent.putExtra(Intent.EXTRA_STREAM, uri); intent.putExtra(Intent.EXTRA_SUBJECT, // . "Call Meter 3G export"); intent.addCategory(Intent.CATEGORY_DEFAULT); try { final File d = Environment.getExternalStorageDirectory(); final File f = new File(d, DataProvider.PACKAGE + File.separator + fn); f.mkdirs(); if (f.exists()) { f.delete(); } f.createNewFile(); FileWriter fw = new FileWriter(f); fw.append(result); fw.close(); // call an exporting app with the uri to the // preferences Preferences.this.startActivity( Intent.createChooser(intent, Preferences.this.getString(resChooser))); } catch (IOException e) { Log.e(TAG, "error writing export file", e); Toast.makeText(Preferences.this, R.string.err_export_write, Toast.LENGTH_LONG) .show(); } } } }; task.execute((Void) null); } }
From source file:com.huison.DriverAssistant_Web.util.LoginHelper.java
public static void changePassword(final BaseActivity activity, final String username, final String phone, final String oldPassword, final String newPassword) { UmengEventSender.sendEvent(activity, UmengEventTypes.changePW); final ProgressDialog pd = new ProgressDialog(activity); pd.setMessage(""); pd.show();//from ww w . jav a 2 s . c o m AsyncHttpClient client = activity.getAsyncHttpClient(); RequestParams params = new RequestParams(); /* * Map<String, String> map = new HashMap<String, String>(); * map.put("sessionkey", BaseActivity.getSESSIONKEY()); * map.put("userid", username); map.put("mob", phone); * map.put("oldpasswork", oldPassword); map.put("passwork", * newPassword); map.put("version", activity.getVersionName()); * params.put("action", CHANGE_PASSWORD_ACTION); params.put("xml", * BaseActivity.getXML(map)); */ try { JSONObject p = new JSONObject(); p.put("mobile", phone); p.put("password", oldPassword); p.put("method", "editpassword"); p.put("version", activity.getVersionName()); p.put("devicetype", "android"); p.put("newpassword", newPassword); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date curDate = new Date(System.currentTimeMillis());// String time = formatter.format(curDate); p.put("time", time); Log.v("", p.toString()); String data = Util.DesJiaMi(p.toString(), "czxms520"); // Log.v("",data); params.put("data", data); } catch (Exception e) { e.printStackTrace(); } client.post(BaseActivity.REQUESTURL, params, new JsonHttpResponseHandler() { @Override public void onDispatchSuccess(int statusCode, Header[] headers, String result) { try { result = Util.decrypt(result, "czxms520"); Log.v(TAG, "JSON" + result); JSONObject jo = new JSONObject(result); String code = jo.getString("code"); String msg = getJSONValueAsString(jo, "message"); if (code.equals("0")) { // jo = jo.getJSONObject("data"); activity.showMessageBoxAndFinish(msg); activity.setPassword(newPassword); } else { activity.showMessageBox(msg); } } catch (JSONException e) { activity.showMessageBox(activity.getText(R.string.server404)); Log.e("change password error", Log.getStackTraceString(e)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onFailureAnyway(int statusCode, Header[] headers, Throwable throwable, BaseBinaryResponse jsonResponse) { pd.dismiss(); activity.showMessageBox(activity.getText(R.string.server404)); } @Override public void onSuccessAnyway(int statusCode, Header[] headers, BaseBinaryResponse jsonResponse) { pd.dismiss(); // ChangePasswordActivity.instance.finish(); } }); TimeCounter.countTime(activity, pd); }
From source file:com.arantius.tivocommander.SeasonPass.java
public void reorderEnable(View unusedView) { Utils.log("SeasonPass::reorderEnable() " + Boolean.toString(mInReorderMode)); final ArrayList<String> subscriptionIds = new ArrayList<String>(); final ArrayList<Integer> slots = new ArrayList<Integer>(); int i = 0;/* w w w. jav a 2 s . co m*/ while (i < mSubscriptionData.size()) { if (mSubscriptionStatus.get(i) == SubscriptionStatus.MISSING) { String subscriptionId = mSubscriptionIds.get(i); subscriptionIds.add(subscriptionId); slots.add(i); mSubscriptionStatus.set(i, SubscriptionStatus.LOADING); } i++; } final ProgressDialog d = new ProgressDialog(this); final MindRpcResponseListener onAllPassesLoaded = new MindRpcResponseListener() { public void onResponse(MindRpcResponse response) { if (response != null) { mDetailCallback.onResponse(response); } d.dismiss(); // Save the state before ordering. mSubscriptionIdsBeforeReorder.clear(); mSubscriptionIdsBeforeReorder.addAll(mSubscriptionIds); // Flip the buttons. findViewById(R.id.reorder_enable).setVisibility(View.GONE); findViewById(R.id.reorder_apply).setVisibility(View.VISIBLE); // Show the drag handles. mInReorderMode = true; mListAdapter.notifyDataSetChanged(); } }; if (subscriptionIds.size() == 0) { // No subscriptions need loading? Proceed immediately. onAllPassesLoaded.onResponse(null); } else { // Otherwise, show dialog and start loading. d.setIndeterminate(true); d.setTitle("Preparing ..."); d.setMessage("Loading all season pass data."); d.setCancelable(false); d.show(); final SubscriptionSearch req = new SubscriptionSearch(subscriptionIds); mRequestSlotMap.put(req.getRpcId(), slots); MindRpc.addRequest(req, onAllPassesLoaded); } }