List of usage examples for org.json JSONException getMessage
public String getMessage()
From source file:org.jboss.aerogear.cordova.push.PushPlugin.java
@Override public boolean execute(String action, JSONArray data, final CallbackContext callbackContext) { Log.v(TAG, "execute: action=" + action); foreground = true;/* w ww. j a v a 2 s . c o m*/ if (REGISTER.equals(action)) { Log.v(TAG, "execute: data=" + data.toString()); try { context = callbackContext; JSONObject pushConfig = parseConfig(data); saveConfig(pushConfig); cordova.getThreadPool().execute(new Runnable() { @Override public void run() { register(callbackContext); } }); } catch (JSONException e) { callbackContext.error(e.getMessage()); return false; } if (cachedMessage != null) { Log.v(TAG, "sending cached extras"); sendMessage(cachedMessage); cachedMessage = null; } return true; } else if (UNREGISTER.equals(action)) { unRegister(callbackContext); return true; } else { callbackContext.error("Invalid action : " + action); } return false; }
From source file:com.example.quadros_10084564.sunshine_v2.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. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us.//from w w w .j a v a 2 s . com */ 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); } int inserted = 0; // add to database if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); } Log.d(LOG_TAG, "FetchWeatherTask Complete. " + inserted + " Inserted"); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } }
From source file:fr.cph.stock.android.activity.ErrorActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.error);/*from w w w . j a v a2 s .c o m*/ String msg = getIntent().getExtras().getString("data"); login = getIntent().getExtras().getString("login"); password = getIntent().getExtras().getString("password"); try { JSONObject json = new JSONObject(msg); error = (TextView) findViewById(R.id.error_message); error.setText(json.optString("error")); } catch (JSONException e) { Log.e(TAG, e.getMessage(), e); } Button button = (Button) findViewById(R.id.retry_button); button.setOnClickListener(new ErrorButtonOnClickListener(this, login, password)); EasyTracker.getInstance().setContext(this); }
From source file:com.jumpbyte.mobile.plugin.ChildBrowser.java
/** * Display a new browser with the specified URL. * * @param url The url to load. * @param jsonObject /* w w w .j ava2s . c o m*/ */ public String showWebPage(final String url, JSONObject options) { // Determine if we should hide the location bar. if (options != null) { showLocationBar = options.optBoolean("showLocationBar", true); showAddressBar = options.optBoolean("showAddressBar", true); } // Create dialog in new thread Runnable runnable = new Runnable() { /** * Convert our DIP units to Pixels * * @return int */ private int dpToPixels(int dipValue) { int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue, ctx.getContext().getResources().getDisplayMetrics()); return value; } public void run() { // Let's create the main dialog dialog = new Dialog(ctx.getContext(), android.R.style.Theme_NoTitleBar); dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog; dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(true); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { public void onDismiss(DialogInterface dialog) { try { JSONObject obj = new JSONObject(); obj.put("type", CLOSE_EVENT); sendUpdate(obj, false); } catch (JSONException e) { Log.d(LOG_TAG, "Should never happen"); } } }); // Main container layout LinearLayout main = new LinearLayout(ctx.getContext()); main.setOrientation(LinearLayout.VERTICAL); // Toolbar layout RelativeLayout toolbar = new RelativeLayout(ctx.getContext()); toolbar.setLayoutParams( new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, this.dpToPixels(44))); toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2)); toolbar.setHorizontalGravity(Gravity.LEFT); toolbar.setVerticalGravity(Gravity.TOP); // Action Button Container layout RelativeLayout actionButtonContainer = new RelativeLayout(ctx.getContext()); actionButtonContainer.setLayoutParams( new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); actionButtonContainer.setHorizontalGravity(Gravity.LEFT); actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL); actionButtonContainer.setId(1); // Back button ImageButton back = new ImageButton(ctx.getContext()); RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT); back.setLayoutParams(backLayoutParams); back.setContentDescription("Back Button"); back.setId(2); try { back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png")); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } back.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goBack(); } }); // Forward button ImageButton forward = new ImageButton(ctx.getContext()); RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2); forward.setLayoutParams(forwardLayoutParams); forward.setContentDescription("Forward Button"); forward.setId(3); try { forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png")); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } forward.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goForward(); } }); // Edit Text Box edittext = new EditText(ctx.getContext()); RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1); textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5); edittext.setLayoutParams(textLayoutParams); edittext.setId(4); edittext.setSingleLine(true); edittext.setText(url); edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI); edittext.setImeOptions(EditorInfo.IME_ACTION_GO); edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE edittext.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { navigate(edittext.getText().toString()); return true; } return false; } }); if (!showAddressBar) { edittext.setVisibility(EditText.INVISIBLE); } // Close button ImageButton close = new ImageButton(ctx.getContext()); RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); close.setLayoutParams(closeLayoutParams); forward.setContentDescription("Close Button"); close.setId(5); try { close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png")); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } close.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { closeDialog(); } }); // WebView webview = new WebView(ctx.getContext()); webview.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); webview.setWebChromeClient(new WebChromeClient()); WebViewClient client = new ChildBrowserClient(edittext); webview.setWebViewClient(client); WebSettings settings = webview.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setBuiltInZoomControls(true); settings.setPluginsEnabled(true); settings.setDomStorageEnabled(true); webview.loadUrl(url); webview.setId(6); webview.getSettings().setLoadWithOverviewMode(true); webview.getSettings().setUseWideViewPort(true); webview.requestFocus(); webview.requestFocusFromTouch(); // Add the back and forward buttons to our action button container layout actionButtonContainer.addView(back); actionButtonContainer.addView(forward); // Add the views to our toolbar toolbar.addView(actionButtonContainer); toolbar.addView(edittext); toolbar.addView(close); // Don't add the toolbar if its been disabled if (getShowLocationBar()) { // Add our toolbar to our main view/layout main.addView(toolbar); } // Add our webview to our main view/layout main.addView(webview); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.FILL_PARENT; lp.height = WindowManager.LayoutParams.FILL_PARENT; dialog.setContentView(main); dialog.show(); dialog.getWindow().setAttributes(lp); } private Bitmap loadDrawable(String filename) throws java.io.IOException { InputStream input = ctx.getAssets().open(filename); return BitmapFactory.decodeStream(input); } }; this.ctx.runOnUiThread(runnable); return ""; }
From source file:com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPush.java
/** * Get the list of tags//from ww w .ja v a 2s.co m * * @param listener Mandatory listener class. When the list of tags are * successfully retrieved the {@link MFPPushResponseListener} * .onSuccess method is called with the list of tagNames * {@link MFPPushResponseListener}.onFailure method is called * otherwise */ public void getTags(final MFPPushResponseListener<List<String>> listener) { MFPPushUrlBuilder builder = new MFPPushUrlBuilder(applicationId); String path = builder.getTagsUrl(); MFPPushInvoker invoker = MFPPushInvoker.newInstance(appContext, path, Request.GET, clientSecret); invoker.setResponseListener(new ResponseListener() { @Override public void onSuccess(Response response) { logger.info("MFPPush:getTags() - Successfully retreived tags. The response is: " + response.toString()); List<String> tagNames = new ArrayList<String>(); try { String responseText = response.getResponseText(); JSONArray tags = (JSONArray) (new JSONObject(responseText)).get(TAGS); Log.d("JSONArray of tags is: ", tags.toString()); int tagsCnt = tags.length(); for (int tagsIdx = 0; tagsIdx < tagsCnt; tagsIdx++) { Log.d("Adding tag: ", tags.getJSONObject(tagsIdx).toString()); tagNames.add(tags.getJSONObject(tagsIdx).getString(NAME)); } listener.onSuccess(tagNames); } catch (JSONException e) { logger.error("MFPPush: getTags() - Error while retrieving tags. Error is: " + e.getMessage()); listener.onFailure(new MFPPushException(e)); } } @Override public void onFailure(Response response, Throwable throwable, JSONObject jsonObject) { //Error while subscribing to tags. errorString = null; statusCode = 0; if (response != null) { errorString = response.getResponseText(); statusCode = response.getStatus(); } else if (errorString == null && throwable != null) { errorString = throwable.toString(); } else if (errorString == null && jsonObject != null) { errorString = jsonObject.toString(); } listener.onFailure(new MFPPushException(errorString, statusCode)); } }); invoker.execute(); }
From source file:com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPush.java
/** * Get the list of tags subscribed to/*from w w w . ja va2 s.c o m*/ * * @param listener Mandatory listener class. When the list of tags subscribed to * are successfully retrieved the {@link MFPPushResponseListener} * .onSuccess method is called with the list of tagNames * {@link MFPPushResponseListener}.onFailure method is called * otherwise */ public void getSubscriptions(final MFPPushResponseListener<List<String>> listener) { MFPPushUrlBuilder builder = new MFPPushUrlBuilder(applicationId); String path = builder.getSubscriptionsUrl(deviceId, null); MFPPushInvoker invoker = MFPPushInvoker.newInstance(appContext, path, Request.GET, clientSecret); invoker.setResponseListener(new ResponseListener() { @Override public void onSuccess(Response response) { List<String> tagNames = new ArrayList<String>(); try { JSONArray tags = (JSONArray) (new JSONObject(response.getResponseText())).get(SUBSCRIPTIONS); int tagsCnt = tags.length(); for (int tagsIdx = 0; tagsIdx < tagsCnt; tagsIdx++) { tagNames.add(tags.getJSONObject(tagsIdx).getString(TAG_NAME)); } listener.onSuccess(tagNames); } catch (JSONException e) { logger.error( "MFPPush: getSubscriptions() - Failure while getting subscriptions. Failure response is: " + e.getMessage()); listener.onFailure(new MFPPushException(e)); } } @Override public void onFailure(Response response, Throwable throwable, JSONObject jsonObject) { //Error while subscribing to tags. errorString = null; statusCode = 0; if (response != null) { errorString = response.getResponseText(); statusCode = response.getStatus(); } else if (errorString == null && throwable != null) { errorString = throwable.toString(); } else if (errorString == null && jsonObject != null) { errorString = jsonObject.toString(); } listener.onFailure(new MFPPushException(errorString, statusCode)); } }); invoker.execute(); }
From source file:com.hotstar.player.adplayer.feeds.ReferencePlayerFeedAdapter.java
/** * Returns an instance of the ReferencePlayerFeedAdapter after parsing the * JSON feed/*from w w w .j a va2 s. c o m*/ * * @param jsonFeed * - feed response in JSON format to be parsed * @return ReferencePlayerFeedAdapter - an instance of the * ReferencePlayerFeedAdapter that will iterate through the JSON * content list response * @throws FeedParsingException * - if there is an error parsing the JSON feed */ public static ReferencePlayerFeedAdapter getInstance(String jsonFeed) throws FeedParsingException { if (jsonFeed == null) { return null; } try { JSONObject object = new JSONObject(jsonFeed); JSONArray entries = object.getJSONArray(NAME_ENTRIES); return new ReferencePlayerFeedAdapter(entries); } catch (JSONException e) { AdVideoApplication.logger.e(LOG_TAG + "::getInstance", "Error parsing content list: " + e.getMessage()); throw new FeedParsingException(); } }
From source file:com.hotstar.player.adplayer.feeds.ReferencePlayerFeedAdapter.java
/** * Returns the ReferencePlayerFeedItemAdapter that represents a single * content item from the Primetime reference implementation JSON input feed * /*from w w w . j av a2 s. c o m*/ * @return ReferencePlayerFeedItemAdapter - the adapter that will be used * for retrieving specific data for a given content item */ protected ReferencePlayerFeedItemAdapter getEntry() { try { if (entryIndex < entries.length()) { return new ReferencePlayerFeedItemAdapter(entries.getJSONObject(entryIndex)); } } catch (JSONException e) { AdVideoApplication.logger.e(LOG_TAG + "::getEntry", "Error parsing content list: " + e.getMessage()); } return null; }
From source file:com.chess.genesis.net.SyncClient.java
@Override public boolean handleMessage(final Message msg) { final JSONObject json = (JSONObject) msg.obj; try {/*from www . j a v a2 s.c o m*/ if (json.getString("result").equals("error")) { callback.sendMessage(Message.obtain(callback, MSG, json)); error = true; return true; } } catch (final JSONException e) { throw new RuntimeException(e.getMessage(), e); } switch (msg.what) { case NetworkClient.GAME_STATUS: game_status(json); break; case NetworkClient.GAME_INFO: game_info(json); break; case NetworkClient.GAME_DATA: game_data(json); break; case NetworkClient.SYNC_GAMIDS: if (gameType == Enums.ONLINE_GAME) sync_active(json); else sync_archive(json); break; case NetworkClient.SYNC_GAMES: sync_recent(json); break; case NetworkClient.SYNC_MSGS: saveMsgs(json); break; } // release lock lock--; return true; }
From source file:com.chess.genesis.net.SyncClient.java
@Override public synchronized void run() { switch (syncType) { case FULL_SYNC: gameType = Enums.ONLINE_GAME;//w w w . ja v a 2 s . c om net.sync_gameids("active"); net.run(); trylock(); gameType = Enums.ARCHIVE_GAME; net.sync_gameids("archive"); net.run(); trylock(); net.sync_msgs(0); net.run(); trylock(); break; case REGULAR_SYNC: final Pref pref = new Pref(context); final long mtime = pref.getLong(R.array.pf_lastmsgsync); final long gtime = pref.getLong(R.array.pf_lastgamesync); net.sync_games(gtime); net.run(); trylock(); net.sync_msgs(mtime); net.run(); trylock(); break; case ACTIVE_SYNC: gameType = Enums.ONLINE_GAME; net.sync_gameids("active"); net.run(); trylock(); break; case ARCHIVE_SYNC: gameType = Enums.ARCHIVE_GAME; net.sync_gameids("archive"); net.run(); trylock(); break; case MSG_SYNC: net.sync_msgs(0); net.run(); trylock(); break; } if (!error) { final JSONObject json = new JSONObject(); try { json.put("result", "ok"); json.put("reason", "gamelist updated"); } catch (final JSONException e) { throw new RuntimeException(e.getMessage(), e); } callback.sendMessage(Message.obtain(callback, MSG, json)); } }