List of usage examples for org.json JSONObject getInt
public int getInt(String key) throws JSONException
From source file:com.iespuig.attendancemanager.UserFetchr.java
public Boolean fetchUser(String login, String password) { SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(context); String urlServer = SP.getString("urlServer", ""); String schoolName = SP.getString("schoolName", ""); try {//from w w w . ja va 2 s .c om String url = Uri.parse(urlServer).buildUpon().appendQueryParameter("action", ACTION) .appendQueryParameter("school", schoolName).appendQueryParameter("login", login) .appendQueryParameter("password", password).build().toString(); Log.i(TAG, "url: " + url); String data = AtmNet.getUrl(url); Log.i(TAG, "Received json: " + data); JSONObject jsonObject = new JSONObject(data); if (jsonObject.has("error")) { return false; } else { User.getInstance().setFullname(jsonObject.getString("fullName")); User.getInstance().setLogin(jsonObject.getString("login")); User.getInstance().setPassword(password); User.getInstance().setId(jsonObject.getInt("id")); } } catch (IOException ioe) { Log.e(TAG, "Failed to fetch items", ioe); return false; } catch (JSONException je) { Log.e(TAG, "Failed to parse JSON", je); return false; } return true; }
From source file:net.homelinux.penecoptero.android.citybikes.app.MainActivity.java
private void showAutoNetworkDialog(int method) { AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setIcon(android.R.drawable.ic_dialog_map); final int mth = method; try {//w w w .ja v a2 s . c om mNDBAdapter.update(); final JSONObject network = mNDBAdapter.getAutomaticNetwork(hOverlay.getPoint(), method); alertDialog.setTitle(R.string.bike_network_alert_success_title); alertDialog.setMessage(getString(R.string.bike_network_alert_success_text0) + ":\n- (" + network.getString("city") + ") " + network.getString("name") + "\n" + getString(R.string.bike_network_alert_success_text1)); alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.sure), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { mNDBAdapter.setManualNetwork(network.getInt("id")); fillData(view_all); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, getString(R.string.try_again), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { showAutoNetworkDialog(0); } }); alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.manual), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { showBikeNetworks(); } }); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); alertDialog.setTitle(R.string.bike_network_alert_error_title); alertDialog.setMessage(getString(R.string.bike_network_alert_error_text)); alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.try_again), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mth == 0) showAutoNetworkDialog(1); else showAutoNetworkDialog(0); } }); alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.manual), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { showBikeNetworks(); } }); } alertDialog.show(); }
From source file:app.com.example.kiran.sunshine.FetchWeatherTask.java
/** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * <p/>/*from ww w . j a va 2 s . c o m*/ * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException { // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; // Location coordinate final String OWM_LATITUDE = "lat"; final String OWM_LONGITUDE = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; try { JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD); double cityLatitude = cityCoord.getDouble(OWM_LATITUDE); double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE); long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay + i); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } // add to database if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); } // Sort order: Ascending, by date. String sortOrder = WeatherEntry.COLUMN_DATE + " ASC"; Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate(locationSetting, System.currentTimeMillis()); // Students: Uncomment the next lines to display what what you stored in the bulkInsert Cursor cur = mContext.getContentResolver().query(weatherForLocationUri, null, null, null, sortOrder); cVVector = new Vector<ContentValues>(cur.getCount()); if (cur.moveToFirst()) { do { ContentValues cv = new ContentValues(); DatabaseUtils.cursorRowToContentValues(cur, cv); cVVector.add(cv); } while (cur.moveToNext()); } Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted"); //String resultStrs = convertContentValuesToUXFormat(cur); //return resultStrs; } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } catch (Exception e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } //return null; }
From source file:de.damdi.fitness.activity.settings.sync.WgerJSONParser.java
/** * A generic parsing method for parsing JSON to SportsEquipment, Muscle or Locale. *///from ww w. j a v a2s .co m private <T> SparseArray<T> parse(String jsonString, Class<T> c) throws JSONException { JSONObject mainObject = new JSONObject(jsonString); Log.d(TAG, "jsonString: " + mainObject.toString()); JSONArray mainArray = mainObject.getJSONArray("objects"); SparseArray<T> sparseArray = new SparseArray<T>(); // parse each exercise of the JSON Array for (int i = 0; i < mainArray.length(); i++) { JSONObject singleObject = mainArray.getJSONObject(i); Integer id = singleObject.getInt("id"); Object parsedObject; if (c.equals(Muscle.class)) { // handle Muscles String name = singleObject.getString("name"); parsedObject = mDataProvider.getMuscleByName(name); if (parsedObject == null) Log.e(TAG, "Could not find Muscle: " + name); } else if (c.equals(SportsEquipment.class)) { // handle SportsEquipment String name = singleObject.getString("name"); parsedObject = mDataProvider.getEquipmentByName(name); if (parsedObject == null) Log.e(TAG, "Could not find SportsEquipment: " + name); } else if (c.equals(Locale.class)) { // handle Locales String short_name = singleObject.getString("short_name"); parsedObject = new Locale(short_name); if (parsedObject == null) Log.e(TAG, "Could not find Locale.class: " + short_name); } else { throw new IllegalStateException( "parse(String, Class<T>) cannot be applied for class: " + c.toString()); } sparseArray.put(id, (T) parsedObject); } return sparseArray; }
From source file:com.macmoim.pang.FoodListFragment.java
/** * Parsing json reponse and passing the data to feed view list adapter *///ww w .j av a 2s . c om private void ParseJsonFeed(JSONObject response, boolean toClearArray) { if (mRecyclerView == null) { return; } if (toClearArray) { feedItems.clear(); } try { if ("success".equals(response.getString("ret_val"))) { JSONArray feedArray = response.getJSONArray("post_info"); int length = feedArray.length(); for (int i = 0; i < length; i++) { JSONObject feedObj = (JSONObject) feedArray.get(i); FoodItem item = new FoodItem(); item.setId(feedObj.getInt("id")); item.setName(feedObj.getString("title")); item.setUserId(feedObj.getString("user_id")); item.setUserName(feedObj.getString("user_name")); // Image might be null sometimes String image = feedObj.isNull("img_path") ? null : feedObj.getString("img_path"); item.setImge(image); item.setTimeStamp(feedObj.getString("date")); item.setLikeSum(feedObj.getString("like_sum")); String score = feedObj.getString("score"); item.setScore("null".equals(score) ? "0" : score); Log.d(TAG, "parseJsonFeed dbname " + feedObj.getString("img_path")); feedItems.add(0, item); } // notify data changes to list adapater mRecyclerView.getAdapter().notifyDataSetChanged(); } else { Log.e(TAG, "return fail : " + response.getString("ret_detail")); } } catch (JSONException e) { e.printStackTrace(); } }
From source file:com.piusvelte.sonet.core.SonetComments.java
private void loadComments() { mComments.clear();/*from w w w. j a v a2 s . c o m*/ setListAdapter(new SimpleAdapter(SonetComments.this, mComments, R.layout.comment, new String[] { Entities.FRIEND, Statuses.MESSAGE, Statuses.CREATEDTEXT, getString(R.string.like) }, new int[] { R.id.friend, R.id.message, R.id.created, R.id.like })); mMessage.setEnabled(false); mMessage.setText(R.string.loading); final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Void, String, String> asyncTask = new AsyncTask<Void, String, String>() { @Override protected String doInBackground(Void... none) { // load the status itself if (mData != null) { SonetCrypto sonetCrypto = SonetCrypto.getInstance(getApplicationContext()); UriMatcher um = new UriMatcher(UriMatcher.NO_MATCH); String authority = Sonet.getAuthority(SonetComments.this); um.addURI(authority, SonetProvider.VIEW_STATUSES_STYLES + "/*", SonetProvider.STATUSES_STYLES); um.addURI(authority, SonetProvider.TABLE_NOTIFICATIONS + "/*", SonetProvider.NOTIFICATIONS); Cursor status; switch (um.match(mData)) { case SonetProvider.STATUSES_STYLES: status = getContentResolver().query(Statuses_styles.getContentUri(SonetComments.this), new String[] { Statuses_styles.ACCOUNT, Statuses_styles.SID, Statuses_styles.ESID, Statuses_styles.WIDGET, Statuses_styles.SERVICE, Statuses_styles.FRIEND, Statuses_styles.MESSAGE, Statuses_styles.CREATED }, Statuses_styles._ID + "=?", new String[] { mData.getLastPathSegment() }, null); if (status.moveToFirst()) { mService = status.getInt(4); mServiceName = getResources().getStringArray(R.array.service_entries)[mService]; mAccount = status.getLong(0); mSid = sonetCrypto.Decrypt(status.getString(1)); mEsid = sonetCrypto.Decrypt(status.getString(2)); Cursor widget = getContentResolver().query( Widgets_settings.getContentUri(SonetComments.this), new String[] { Widgets.TIME24HR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(status.getInt(3)), Long.toString(mAccount) }, null); if (widget.moveToFirst()) { mTime24hr = widget.getInt(0) == 1; } else { Cursor b = getContentResolver().query( Widgets_settings.getContentUri(SonetComments.this), new String[] { Widgets.TIME24HR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(status.getInt(3)), Long.toString(Sonet.INVALID_ACCOUNT_ID) }, null); if (b.moveToFirst()) { mTime24hr = b.getInt(0) == 1; } else { Cursor c = getContentResolver() .query(Widgets_settings.getContentUri(SonetComments.this), new String[] { Widgets.TIME24HR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID), Long.toString(Sonet.INVALID_ACCOUNT_ID) }, null); if (c.moveToFirst()) { mTime24hr = c.getInt(0) == 1; } else { mTime24hr = false; } c.close(); } b.close(); } widget.close(); HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, mSid); commentMap.put(Entities.FRIEND, status.getString(5)); commentMap.put(Statuses.MESSAGE, status.getString(6)); commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(status.getLong(7), mTime24hr)); commentMap.put(getString(R.string.like), mService == TWITTER ? getString(R.string.retweet) : mService == IDENTICA ? getString(R.string.repeat) : ""); mComments.add(commentMap); // load the session Cursor account = getContentResolver().query(Accounts.getContentUri(SonetComments.this), new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SID }, Accounts._ID + "=?", new String[] { Long.toString(mAccount) }, null); if (account.moveToFirst()) { mToken = sonetCrypto.Decrypt(account.getString(0)); mSecret = sonetCrypto.Decrypt(account.getString(1)); mAccountSid = sonetCrypto.Decrypt(account.getString(2)); } account.close(); } status.close(); break; case SonetProvider.NOTIFICATIONS: Cursor notification = getContentResolver().query( Notifications.getContentUri(SonetComments.this), new String[] { Notifications.ACCOUNT, Notifications.SID, Notifications.ESID, Notifications.FRIEND, Notifications.MESSAGE, Notifications.CREATED }, Notifications._ID + "=?", new String[] { mData.getLastPathSegment() }, null); if (notification.moveToFirst()) { // clear notification ContentValues values = new ContentValues(); values.put(Notifications.CLEARED, 1); getContentResolver().update(Notifications.getContentUri(SonetComments.this), values, Notifications._ID + "=?", new String[] { mData.getLastPathSegment() }); mAccount = notification.getLong(0); mSid = sonetCrypto.Decrypt(notification.getString(1)); mEsid = sonetCrypto.Decrypt(notification.getString(2)); mTime24hr = false; // load the session Cursor account = getContentResolver().query(Accounts.getContentUri(SonetComments.this), new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SID, Accounts.SERVICE }, Accounts._ID + "=?", new String[] { Long.toString(mAccount) }, null); if (account.moveToFirst()) { mToken = sonetCrypto.Decrypt(account.getString(0)); mSecret = sonetCrypto.Decrypt(account.getString(1)); mAccountSid = sonetCrypto.Decrypt(account.getString(2)); mService = account.getInt(3); } account.close(); HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, mSid); commentMap.put(Entities.FRIEND, notification.getString(3)); commentMap.put(Statuses.MESSAGE, notification.getString(4)); commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(notification.getLong(5), mTime24hr)); commentMap.put(getString(R.string.like), mService == TWITTER ? getString(R.string.retweet) : getString(R.string.repeat)); mComments.add(commentMap); mServiceName = getResources().getStringArray(R.array.service_entries)[mService]; } notification.close(); break; default: mComments.clear(); HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, ""); commentMap.put(Entities.FRIEND, ""); commentMap.put(Statuses.MESSAGE, "error, status not found"); commentMap.put(Statuses.CREATEDTEXT, ""); commentMap.put(getString(R.string.like), ""); mComments.add(commentMap); } String response = null; HttpGet httpGet; SonetOAuth sonetOAuth; boolean liked = false; String screen_name = ""; switch (mService) { case TWITTER: sonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET, mToken, mSecret); if ((response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest( new HttpGet(String.format(TWITTER_USER, TWITTER_BASE_URL, mEsid))))) != null) { try { JSONObject user = new JSONObject(response); screen_name = "@" + user.getString(Sscreen_name) + " "; } catch (JSONException e) { Log.e(TAG, e.toString()); } } publishProgress(screen_name); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(new HttpGet(String.format(TWITTER_MENTIONS, TWITTER_BASE_URL, String.format(TWITTER_SINCE_ID, mSid))))); break; case FACEBOOK: if ((response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(FACEBOOK_LIKES, FACEBOOK_BASE_URL, mSid, Saccess_token, mToken)))) != null) { try { JSONArray likes = new JSONObject(response).getJSONArray(Sdata); for (int i = 0, i2 = likes.length(); i < i2; i++) { JSONObject like = likes.getJSONObject(i); if (like.getString(Sid).equals(mAccountSid)) { liked = true; break; } } } catch (JSONException e) { Log.e(TAG, e.toString()); } } publishProgress(getString(liked ? R.string.unlike : R.string.like)); response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet( String.format(FACEBOOK_COMMENTS, FACEBOOK_BASE_URL, mSid, Saccess_token, mToken))); break; case MYSPACE: sonetOAuth = new SonetOAuth(MYSPACE_KEY, MYSPACE_SECRET, mToken, mSecret); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(new HttpGet(String .format(MYSPACE_URL_STATUSMOODCOMMENTS, MYSPACE_BASE_URL, mEsid, mSid)))); break; case LINKEDIN: sonetOAuth = new SonetOAuth(LINKEDIN_KEY, LINKEDIN_SECRET, mToken, mSecret); httpGet = new HttpGet(String.format(LINKEDIN_UPDATE, LINKEDIN_BASE_URL, mSid)); for (String[] header : LINKEDIN_HEADERS) httpGet.setHeader(header[0], header[1]); if ((response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpGet))) != null) { try { JSONObject data = new JSONObject(response); if (data.has("isCommentable") && !data.getBoolean("isCommentable")) { publishProgress(getString(R.string.uncommentable)); } if (data.has("isLikable")) { publishProgress(getString( data.has("isLiked") && data.getBoolean("isLiked") ? R.string.unlike : R.string.like)); } else { publishProgress(getString(R.string.unlikable)); } } catch (JSONException e) { Log.e(TAG, e.toString()); } } else { publishProgress(getString(R.string.unlikable)); } httpGet = new HttpGet(String.format(LINKEDIN_UPDATE_COMMENTS, LINKEDIN_BASE_URL, mSid)); for (String[] header : LINKEDIN_HEADERS) httpGet.setHeader(header[0], header[1]); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpGet)); break; case FOURSQUARE: response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet( String.format(FOURSQUARE_GET_CHECKIN, FOURSQUARE_BASE_URL, mSid, mToken))); break; case IDENTICA: sonetOAuth = new SonetOAuth(IDENTICA_KEY, IDENTICA_SECRET, mToken, mSecret); if ((response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest( new HttpGet(String.format(IDENTICA_USER, IDENTICA_BASE_URL, mEsid))))) != null) { try { JSONObject user = new JSONObject(response); screen_name = "@" + user.getString(Sscreen_name) + " "; } catch (JSONException e) { Log.e(TAG, e.toString()); } } publishProgress(screen_name); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(new HttpGet(String.format(IDENTICA_MENTIONS, IDENTICA_BASE_URL, String.format(IDENTICA_SINCE_ID, mSid))))); break; case GOOGLEPLUS: //TODO: // get plussed status break; case CHATTER: // Chatter requires loading an instance if ((mChatterInstance == null) || (mChatterToken == null)) { if ((response = SonetHttpClient.httpResponse(mHttpClient, new HttpPost( String.format(CHATTER_URL_ACCESS, CHATTER_KEY, mToken)))) != null) { try { JSONObject jobj = new JSONObject(response); if (jobj.has("instance_url") && jobj.has(Saccess_token)) { mChatterInstance = jobj.getString("instance_url"); mChatterToken = jobj.getString(Saccess_token); } } catch (JSONException e) { Log.e(TAG, e.toString()); } } } if ((mChatterInstance != null) && (mChatterToken != null)) { httpGet = new HttpGet(String.format(CHATTER_URL_LIKES, mChatterInstance, mSid)); httpGet.setHeader("Authorization", "OAuth " + mChatterToken); if ((response = SonetHttpClient.httpResponse(mHttpClient, httpGet)) != null) { try { JSONObject jobj = new JSONObject(response); if (jobj.getInt(Stotal) > 0) { JSONArray likes = jobj.getJSONArray("likes"); for (int i = 0, i2 = likes.length(); i < i2; i++) { JSONObject like = likes.getJSONObject(i); if (like.getJSONObject(Suser).getString(Sid).equals(mAccountSid)) { mChatterLikeId = like.getString(Sid); liked = true; break; } } } } catch (JSONException e) { Log.e(TAG, e.toString()); } } publishProgress(getString(liked ? R.string.unlike : R.string.like)); httpGet = new HttpGet(String.format(CHATTER_URL_COMMENTS, mChatterInstance, mSid)); httpGet.setHeader("Authorization", "OAuth " + mChatterToken); response = SonetHttpClient.httpResponse(mHttpClient, httpGet); } else { response = null; } break; } return response; } return null; } @Override protected void onProgressUpdate(String... params) { mMessage.setText(""); if (params != null) { if ((mService == TWITTER) || (mService == IDENTICA)) { mMessage.append(params[0]); } else { if (mService == LINKEDIN) { if (params[0].equals(getString(R.string.uncommentable))) { mSend.setEnabled(false); mMessage.setEnabled(false); mMessage.setText(R.string.uncommentable); } else { setCommentStatus(0, params[0]); } } else { setCommentStatus(0, params[0]); } } } mMessage.setEnabled(true); } @Override protected void onPostExecute(String response) { if (response != null) { int i2; try { JSONArray comments; mSimpleDateFormat = null; switch (mService) { case TWITTER: comments = new JSONArray(response); if ((i2 = comments.length()) > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); if (comment.getString(Sin_reply_to_status_id) == mSid) { HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, comment.getString(Sid)); commentMap.put(Entities.FRIEND, comment.getJSONObject(Suser).getString(Sname)); commentMap.put(Statuses.MESSAGE, comment.getString(Stext)); commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText( parseDate(comment.getString(Screated_at), TWITTER_DATE_FORMAT), mTime24hr)); commentMap.put(getString(R.string.like), getString(R.string.retweet)); mComments.add(commentMap); } } } else { noComments(); } break; case FACEBOOK: comments = new JSONObject(response).getJSONArray(Sdata); if ((i2 = comments.length()) > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, comment.getString(Sid)); commentMap.put(Entities.FRIEND, comment.getJSONObject(Sfrom).getString(Sname)); commentMap.put(Statuses.MESSAGE, comment.getString(Smessage)); commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(comment.getLong(Screated_time) * 1000, mTime24hr)); commentMap.put(getString(R.string.like), getString(comment.has(Suser_likes) && comment.getBoolean(Suser_likes) ? R.string.unlike : R.string.like)); mComments.add(commentMap); } } else { noComments(); } break; case MYSPACE: comments = new JSONObject(response).getJSONArray(Sentry); if ((i2 = comments.length()) > 0) { for (int i = 0; i < i2; i++) { JSONObject entry = comments.getJSONObject(i); HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, entry.getString(ScommentId)); commentMap.put(Entities.FRIEND, entry.getJSONObject(Sauthor).getString(SdisplayName)); commentMap.put(Statuses.MESSAGE, entry.getString(Sbody)); commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText( parseDate(entry.getString(SpostedDate), MYSPACE_DATE_FORMAT), mTime24hr)); commentMap.put(getString(R.string.like), ""); mComments.add(commentMap); } } else { noComments(); } break; case LINKEDIN: JSONObject jsonResponse = new JSONObject(response); if (jsonResponse.has(S_total) && (jsonResponse.getInt(S_total) != 0)) { comments = jsonResponse.getJSONArray(Svalues); if ((i2 = comments.length()) > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); JSONObject person = comment.getJSONObject(Sperson); HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, comment.getString(Sid)); commentMap.put(Entities.FRIEND, person.getString(SfirstName) + " " + person.getString(SlastName)); commentMap.put(Statuses.MESSAGE, comment.getString(Scomment)); commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(comment.getLong(Stimestamp), mTime24hr)); commentMap.put(getString(R.string.like), ""); mComments.add(commentMap); } } else { noComments(); } } break; case FOURSQUARE: comments = new JSONObject(response).getJSONObject(Sresponse).getJSONObject(Scheckin) .getJSONObject(Scomments).getJSONArray(Sitems); if ((i2 = comments.length()) > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); JSONObject user = comment.getJSONObject(Suser); HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, comment.getString(Sid)); commentMap.put(Entities.FRIEND, user.getString(SfirstName) + " " + user.getString(SlastName)); commentMap.put(Statuses.MESSAGE, comment.getString(Stext)); commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(comment.getLong(ScreatedAt) * 1000, mTime24hr)); commentMap.put(getString(R.string.like), ""); mComments.add(commentMap); } } else { noComments(); } break; case IDENTICA: comments = new JSONArray(response); if ((i2 = comments.length()) > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); if (comment.getString(Sin_reply_to_status_id) == mSid) { HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, comment.getString(Sid)); commentMap.put(Entities.FRIEND, comment.getJSONObject(Suser).getString(Sname)); commentMap.put(Statuses.MESSAGE, comment.getString(Stext)); commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText( parseDate(comment.getString(Screated_at), TWITTER_DATE_FORMAT), mTime24hr)); commentMap.put(getString(R.string.like), getString(R.string.repeat)); mComments.add(commentMap); } } } else { noComments(); } break; case GOOGLEPLUS: //TODO: load comments 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", mToken)); httpParams.add(new BasicNameValuePair("grant_type", "refresh_token")); try { httpPost.setEntity(new UrlEncodedFormEntity(httpParams)); if ((response = SonetHttpClient.httpResponse(mHttpClient, httpPost)) != null) { JSONObject j = new JSONObject(response); if (j.has(Saccess_token)) { String access_token = j.getString(Saccess_token); if ((response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(GOOGLEPLUS_ACTIVITY, GOOGLEPLUS_BASE_URL, mSid, 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: load comments commentCount = replies.getInt(StotalItems); } } } } catch (JSONException e) { Log.e(TAG, e.toString()); } } } } } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } catch (JSONException e) { Log.e(TAG, e.toString()); } break; case CHATTER: JSONObject chats = new JSONObject(response); if (chats.getInt(Stotal) > 0) { comments = chats.getJSONArray(Scomments); if ((i2 = comments.length()) > 0) { for (int i = 0; i < i2; i++) { JSONObject comment = comments.getJSONObject(i); HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, comment.getString(Sid)); commentMap.put(Entities.FRIEND, comment.getJSONObject(Suser).getString(Sname)); commentMap.put(Statuses.MESSAGE, comment.getJSONObject(Sbody).getString(Stext)); commentMap.put(Statuses.CREATEDTEXT, Sonet.getCreatedText( parseDate(comment.getString(ScreatedDate), CHATTER_DATE_FORMAT), mTime24hr)); commentMap.put(getString(R.string.like), ""); mComments.add(commentMap); } } else { noComments(); } } else { noComments(); } break; } } catch (JSONException e) { Log.e(TAG, e.toString()); } } else { noComments(); } setListAdapter(new SimpleAdapter(SonetComments.this, mComments, R.layout.comment, new String[] { Entities.FRIEND, Statuses.MESSAGE, Statuses.CREATEDTEXT, getString(R.string.like) }, new int[] { R.id.friend, R.id.message, R.id.created, R.id.like })); if (loadingDialog.isShowing()) loadingDialog.dismiss(); } private void noComments() { HashMap<String, String> commentMap = new HashMap<String, String>(); commentMap.put(Statuses.SID, ""); commentMap.put(Entities.FRIEND, ""); commentMap.put(Statuses.MESSAGE, getString(R.string.no_comments)); commentMap.put(Statuses.CREATEDTEXT, ""); commentMap.put(getString(R.string.like), ""); mComments.add(commentMap); } 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(); }
From source file:com.hichinaschool.flashcards.libanki.Sched.java
private TreeSet<Object[]> _groupChildrenMain(TreeSet<Object[]> grps, int depth) { TreeSet<Object[]> tree = new TreeSet<Object[]>(new DeckNameCompare()); // group and recurse Iterator<Object[]> it = grps.iterator(); Object[] tmp = null;// w w w . ja va2 s .c o m while (tmp != null || it.hasNext()) { Object[] head; if (tmp != null) { head = tmp; tmp = null; } else { head = it.next(); } String[] title = (String[]) head[0]; long did = (Long) head[1]; int newCount = (Integer) head[2]; int lrnCount = (Integer) head[3]; int revCount = (Integer) head[4]; TreeSet<Object[]> children = new TreeSet<Object[]>(new DeckNameCompare()); while (it.hasNext()) { Object[] o = it.next(); if (((String[]) o[0])[depth].equals(title[depth])) { // add to children children.add(o); } else { // proceed with this as head tmp = o; break; } } children = _groupChildrenMain(children, depth + 1); // tally up children counts, but skip deeper sub-decks for (Object[] ch : children) { if (((String[]) ch[0]).length == ((String[]) head[0]).length + 1) { newCount += (Integer) ch[2]; lrnCount += (Integer) ch[3]; revCount += (Integer) ch[4]; } } // limit the counts to the deck's limits JSONObject conf = mCol.getDecks().confForDid(did); JSONObject deck = mCol.getDecks().get(did); try { if (conf.getInt("dyn") == 0) { revCount = Math.max(0, Math.min(revCount, conf.getJSONObject("rev").getInt("perDay") - deck.getJSONArray("revToday").getInt(1))); newCount = Math.max(0, Math.min(newCount, conf.getJSONObject("new").getInt("perDay") - deck.getJSONArray("newToday").getInt(1))); } } catch (JSONException e) { throw new RuntimeException(e); } tree.add(new Object[] { title, did, newCount, lrnCount, revCount, children }); } TreeSet<Object[]> result = new TreeSet<Object[]>(new DeckNameCompare()); for (Object[] t : tree) { result.add(new Object[] { t[0], t[1], t[2], t[3], t[4] }); result.addAll((TreeSet<Object[]>) t[5]); } return result; }
From source file:com.hichinaschool.flashcards.libanki.Sched.java
public int _deckNewLimitSingle(JSONObject g) { try {/* ww w . j a v a2s . co m*/ if (g.getInt("dyn") != 0) { return mReportLimit; } JSONObject c = mCol.getDecks().confForDid(g.getLong("id")); return Math.max(0, c.getJSONObject("new").getInt("perDay") - g.getJSONArray("newToday").getInt(1)); } catch (JSONException e) { throw new RuntimeException(e); } }
From source file:com.hichinaschool.flashcards.libanki.Sched.java
/** * @param ease 1=no, 2=yes, 3=remove//from w w w . j a v a 2 s . c o m */ private void _answerLrnCard(Card card, int ease) { JSONObject conf = _lrnConf(card); int type; if (card.getODid() != 0 && !card.getWasNew()) { type = 3; } else if (card.getType() == 2) { type = 2; } else { type = 0; } boolean leaving = false; // lrnCount was decremented once when card was fetched int lastLeft = card.getLeft(); // immediate graduate? if (ease == 3) { _rescheduleAsRev(card, conf, true); leaving = true; // graduation time? } else if (ease == 2 && (card.getLeft() % 1000) - 1 <= 0) { _rescheduleAsRev(card, conf, false); leaving = true; } else { // one step towards graduation if (ease == 2) { // decrement real left count and recalculate left today int left = (card.getLeft() % 1000) - 1; try { card.setLeft(_leftToday(conf.getJSONArray("delays"), left) * 1000 + left); } catch (JSONException e) { throw new RuntimeException(e); } // failed } else { card.setLeft(_startingLeft(card)); boolean resched = _resched(card); if (conf.has("mult") && resched) { // review that's lapsed try { card.setIvl(Math.max(Math.max(1, (int) (card.getIvl() * conf.getDouble("mult"))), conf.getInt("minInt"))); } catch (JSONException e) { throw new RuntimeException(e); } } else { // new card; no ivl adjustment // pass } if (resched && card.getODid() != 0) { card.setODue(mToday + 1); } } int delay = _delayForGrade(conf, card.getLeft()); if (card.getDue() < Utils.now()) { // not collapsed; add some randomness delay *= (1 + (new Random().nextInt(25) / 100)); } // TODO: check, if type for second due is correct card.setDue((int) (Utils.now() + delay)); // due today? if (card.getDue() < mDayCutoff) { mLrnCount += card.getLeft() / 1000; // if the queue is not empty and there's nothing else to do, make // sure we don't put it at the head of the queue and end up showing // it twice in a row card.setQueue(1); if (!mLrnQueue.isEmpty() && mRevCount == 0 && mNewCount == 0) { long smallestDue = mLrnQueue.getFirst()[0]; card.setDue(Math.max(card.getDue(), smallestDue + 1)); } _sortIntoLrn(card.getDue(), card.getId()); } else { // the card is due in one or more days, so we need to use the day learn queue long ahead = ((card.getDue() - mDayCutoff) / 86400) + 1; card.setDue(mToday + ahead); card.setQueue(3); } } _logLrn(card, ease, conf, leaving, type, lastLeft); }
From source file:com.hichinaschool.flashcards.libanki.Sched.java
private void _rescheduleNew(Card card, JSONObject conf, boolean early) { card.setIvl(_graduatingIvl(card, conf, early)); card.setDue(mToday + card.getIvl()); try {/*from w w w . j a va2 s.c o m*/ card.setFactor(conf.getInt("initialFactor")); } catch (JSONException e) { throw new RuntimeException(e); } }