Java Code Examples for org.json.JSONException
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project android-async-http, under directory /src/com/loopj/android/http/.
Source file: JsonHttpResponseHandler.java

protected void handleSuccessJsonMessage(Object jsonResponse){ if (jsonResponse instanceof JSONObject) { onSuccess((JSONObject)jsonResponse); } else if (jsonResponse instanceof JSONArray) { onSuccess((JSONArray)jsonResponse); } else { onFailure(new JSONException("Unexpected type " + jsonResponse.getClass().getName()),(JSONObject)null); } }
Example 2
From project android_7, under directory /src/org/immopoly/android/api/.
Source file: IS24ApiService.java

/** * Gets result page number 'page' from IS24 for the given lat,lon,r * @param lat * @param lon * @param r * @param page * @return * @throws MalformedURLException * @throws JSONException */ private JSONObject loadPage(double lat,double lon,float r,int page) throws MalformedURLException, JSONException { URL url=new URL(OAuthData.SERVER + OAuthData.SEARCH_PREFIX + "search/radius.json?realEstateType=apartmentrent&pagenumber="+ page+ "&geocoordinates="+ lat+ ";"+ lon+ ";"+ r); JSONObject obj=WebHelper.getHttpData(url,true,this); if (obj == null) { throw new JSONException("Got (JSONObject) null for search result. Lat: " + lat + "Lon: "+ lon+ " R: "+ r+ " pageNr: "+ page); } return obj; }
Example 3
From project android-joedayz, under directory /Proyectos/FBConnectTest/src/com/facebook/android/.
Source file: Facebook.java

/** * This function does the heavy lifting of publishing an install. * @param fb * @param applicationId * @param context * @throws Exception */ private static void publishInstall(final Facebook fb,final String applicationId,final Context context) throws JSONException, FacebookError, MalformedURLException, IOException { String attributionId=Facebook.getAttributionId(context.getContentResolver()); SharedPreferences preferences=context.getSharedPreferences(ATTRIBUTION_PREFERENCES,Context.MODE_PRIVATE); String pingKey=applicationId + "ping"; long lastPing=preferences.getLong(pingKey,0); if (lastPing == 0 && attributionId != null) { Bundle supportsAttributionParams=new Bundle(); supportsAttributionParams.putString(APPLICATION_FIELDS,SUPPORTS_ATTRIBUTION); JSONObject supportResponse=Util.parseJson(fb.request(applicationId,supportsAttributionParams)); Object doesSupportAttribution=(Boolean)supportResponse.get(SUPPORTS_ATTRIBUTION); if (!(doesSupportAttribution instanceof Boolean)) { throw new JSONException(String.format("%s contains %s instead of a Boolean",SUPPORTS_ATTRIBUTION,doesSupportAttribution)); } if ((Boolean)doesSupportAttribution) { Bundle publishParams=new Bundle(); publishParams.putString(ANALYTICS_EVENT,MOBILE_INSTALL_EVENT); publishParams.putString(ATTRIBUTION_KEY,attributionId); String publishUrl=String.format(PUBLISH_ACTIVITY_PATH,applicationId); fb.request(publishUrl,publishParams,"POST"); SharedPreferences.Editor editor=preferences.edit(); editor.putLong(pingKey,System.currentTimeMillis()); editor.commit(); } } }
Example 4
From project activiti-webapp-rest-generic, under directory /activiti-webapp-rest/src/main/java/org/activiti/rest/builder/engine/.
Source file: ProcessEngineObjectBuilder.java

@Override public JSONObject createJsonObject(Object modelObject) throws JSONException { JSONObject result=new JSONObject(); Map<String,Object> model=getModelAsMap(modelObject); JSONUtil.putRetainNull(result,"version",model.get("version")); ProcessEngineInfo processEngineInfo=(ProcessEngineInfo)model.get("processEngineInfo"); if (processEngineInfo != null) { JSONUtil.putRetainNull(result,"name",processEngineInfo.getName()); JSONUtil.putRetainNull(result,"resourceUrl",processEngineInfo.getResourceUrl()); JSONUtil.putRetainNull(result,"exception",processEngineInfo.getException()); } return result; }
Example 5
From project agraph-java-client, under directory /src/com/franz/agraph/http/handler/.
Source file: AGJSONHandler.java

@Override public void handleResponse(HttpMethod method) throws IOException, AGHttpException { try { InputStream response=getInputStream(method); result=new JSONObject(streamToString(response)); } catch ( JSONException e) { throw new AGHttpException(e); } }
Example 6
From project AlarmApp-Android, under directory /src/org/alarmapp/web/.
Source file: HttpWebClient.java

private AuthToken getAuthToken(String name,String password) throws WebException { HashMap<String,String> data=new HashMap<String,String>(); data.put("username",name); data.put("password",password); data.put("purpose","AlarmApp Android"); String response=HttpUtil.request(url("web_service/auth_token/generate/"),data,null); LogEx.verbose("auth_token/generate returned " + response); try { JSONObject json=new JSONObject(response); AuthToken auth=new AuthTokenData(json.getString("auth_token"),DateUtil.parse(json.getString("expired"))); LogEx.verbose("Assigned Auth Token: " + auth); return auth; } catch ( JSONException e) { throw new WebException(JSON_ERROR,e); } }
Example 7
From project Alerte-voirie-android, under directory /src/com/fabernovel/alertevoirie/data/.
Source file: CategoryProvider.java

@Override public boolean onCreate(){ DataInputStream in=new DataInputStream(getContext().getResources().openRawResource(R.raw.categories)); try { byte[] buffer=new byte[in.available()]; in.read(buffer); categories=(JSONObject)new JSONTokener(new String(buffer)).nextValue(); } catch ( IOException e) { e.printStackTrace(); } catch ( JSONException e) { Log.e("Alerte Voirie","JSON error",e); } return true; }
Example 8
From project Amantech, under directory /Android/CloudAppStudioAndroid/src/com/cloudappstudio/activities/.
Source file: ViewEntriesActivity.java

@Override protected Integer doInBackground(Integer... params){ CloudViewEntryParser parser=new CloudViewEntryParser(id); try { viewEntries=parser.parseFromCloud(app.getAppName(),view.getViewName()); } catch ( IllegalStateException e) { return -1; } catch ( IOException e) { return -1; } catch ( JSONException e) { return -1; } return 0; }
Example 9
From project andlytics, under directory /src/com/github/andlyticsproject/admob/.
Source file: AdmobRequest.java

public static String login(String email,String password) throws NetworkException, AdmobInvalidTokenException, AdmobGenericException, AdmobInvalidRequestException, AdmobRateLimitExceededException { String token=null; String params="client_key=" + clientKey + "&email="+ URLEncoder.encode(email)+ "&password="+ URLEncoder.encode(password); try { Log.d(TAG,email + " admob login request"); JSONArray data=getResponse("auth","login",params,true,true); token=data.getJSONObject(0).getString("token"); } catch ( JSONException e) { throw new AdmobGenericException(e); } return token; }
Example 10
From project android-bankdroid, under directory /src/com/liato/bankdroid/banking/banks/.
Source file: Skandiabanken.java

@Override public Urllib login() throws LoginException, BankException { urlopen=new Urllib(); HashMap<String,String> headers=urlopen.getHeaders(); headers.put(HTTP_HEADER_SMARTREFILL_APPLICATION_ID,"se.skandiabanken.android.wallet"); headers.put(HTTP_HEADER_SMARTREFILL_APPLICATION_VERSION,"9"); headers.put(HTTP_HEADER_SMARTREFILL_COUNTRY_CODE,countryCode); headers.put(HTTP_HEADER_SMARTREFILL_CUSTOMER_OWNER,customerOwner); headers.put(HTTP_HEADER_SMARTREFILL_DEVICE_ID,getDeviceId()); headers.put(HTTP_HEADER_SMARTREFILL_INFLOW,INFLOW_ANDROID); urlopen.setUserAgent(null); String loginUrl=getBaseUrlWithCustomerOwner() + "/login"; List<NameValuePair> postData=new ArrayList<NameValuePair>(); postData.add(new BasicNameValuePair("username",username)); postData.add(new BasicNameValuePair("password",password)); try { String loginResponse=urlopen.open(loginUrl,postData); JSONObject obj=new JSONObject(loginResponse); customerId=(int)obj.getLong("id"); urlopen.addHeader("x-smartrefill-customer","" + customerId); } catch ( HttpResponseException e) { if (e.getStatusCode() == 401) throw new BankException("Inloggning misslyckad fel anv?ndarnamn eller l?senord"); else throw new BankException("Http fel (" + e.getStatusCode() + ") "+ e.getMessage()); } catch ( ClientProtocolException e) { throw new BankException("ClientProtocolException " + e.getMessage()); } catch ( IOException e) { throw new BankException("IOException " + e.getMessage()); } catch ( JSONException e) { throw new BankException("Ov?ntat svarsformat " + e.getMessage()); } return urlopen; }
Example 11
From project android-flash-cards, under directory /src/org/thomasamsler/android/flashcards/fragment/.
Source file: SetupFragment.java

@Override protected void onPostExecute(JSONObject jsonObject){ try { mProgressBar.setVisibility(ProgressBar.GONE); if (null == jsonObject) { Toast.makeText(getActivity().getApplicationContext(),R.string.view_cards_fetch_remote_error,Toast.LENGTH_LONG).show(); return; } try { String responseType=jsonObject.getString(FIELD_RESPONSE_TYPE); if (null != responseType && RESPONSE_OK.equals(responseType)) { Toast.makeText(getActivity().getApplicationContext(),R.string.setup_save_user_name_success,Toast.LENGTH_SHORT).show(); SharedPreferences sharedPreferences=getActivity().getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE); SharedPreferences.Editor editor=sharedPreferences.edit(); editor.putString(PREFERENCE_FCEX_USER_NAME,jsonObject.getString(FIELD_FC_ARG)); editor.commit(); ((MainApplication)getActivity().getApplication()).doAction(ACTION_SHOW_CARD_SETS,Boolean.TRUE); } else if (null != responseType && RESPONSE_ERROR.equals(responseType)) { Toast.makeText(getActivity().getApplicationContext(),R.string.setup_save_user_name_error,Toast.LENGTH_LONG).show(); } else { Toast.makeText(getActivity().getApplicationContext(),R.string.setup_save_user_name_failure,Toast.LENGTH_LONG).show(); } } catch ( JSONException e) { Log.e(LOG_TAG,"JSONException",e); } } catch ( Exception e) { Log.e(LOG_TAG,"General Exception",e); } }
Example 12
From project android-sdk, under directory /src/main/java/com/mobeelizer/mobile/android/types/.
Source file: FileFieldTypeHelper.java

@Override public void setValueFromDatabaseToMap(final Cursor cursor,final Map<String,String> values,final MobeelizerFieldAccessor field,final Map<String,String> options){ int columnIndex=cursor.getColumnIndex(field.getName() + _GUID); if (cursor.isNull(columnIndex)) { values.put(field.getName(),null); } else { try { JSONObject json=new JSONObject(); json.put(JSON_GUID,cursor.getString(columnIndex)); json.put(JSON_NAME,cursor.getString(cursor.getColumnIndex(field.getName() + _NAME))); values.put(field.getName(),json.toString()); } catch ( JSONException e) { throw new IllegalStateException(e.getMessage(),e); } } }
Example 13
From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/facebook/extpack/com/facebook/android/.
Source file: Util.java

/** * Parse a server response into a JSON Object. This is a basic implementation using org.json.JSONObject representation. More sophisticated applications may wish to do their own parsing. The parsed JSON is checked for a variety of error fields and a FacebookException is thrown if an error condition is set, populated with the error message and error type or code if available. * @param response - string representation of the response * @return the response as a JSON Object * @throws JSONException - if the response is not valid JSON * @throws FacebookError - if an error condition is set */ public static JSONObject parseJson(String response) throws JSONException, FacebookError { if (response.equals("false")) { throw new FacebookError("request failed"); } if (response.equals("true")) { response="{value : true}"; } JSONObject json=new JSONObject(response); if (json.has("error")) { JSONObject error=json.getJSONObject("error"); throw new FacebookError(error.getString("message"),error.getString("type"),0); } if (json.has("error_code") && json.has("error_msg")) { throw new FacebookError(json.getString("error_msg"),"",Integer.parseInt(json.getString("error_code"))); } if (json.has("error_code")) { throw new FacebookError("request failed","",Integer.parseInt(json.getString("error_code"))); } if (json.has("error_msg")) { throw new FacebookError(json.getString("error_msg")); } if (json.has("error_reason")) { throw new FacebookError(json.getString("error_reason")); } return json; }
Example 14
From project Android-SyncAdapter-JSON-Server-Example, under directory /src/com/example/android/samplesync/client/.
Source file: NetworkUtilities.java

/** * Fetches the list of friend data updates from the server * @param account The account being synced. * @param authtoken The authtoken stored in AccountManager for this account * @param lastUpdated The last time that sync was performed * @return list The list of updates received from the server. */ public static List<User> fetchFriendUpdates(Account account,String authtoken,Date lastUpdated) throws JSONException, ParseException, IOException, AuthenticationException { final ArrayList<User> friendList=new ArrayList<User>(); final ArrayList<NameValuePair> params=new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_USERNAME,account.name)); params.add(new BasicNameValuePair(PARAM_PASSWORD,authtoken)); if (lastUpdated != null) { final SimpleDateFormat formatter=new SimpleDateFormat("yyyy/MM/dd HH:mm"); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); params.add(new BasicNameValuePair(PARAM_UPDATED,formatter.format(lastUpdated))); } Log.i(TAG,params.toString()); HttpEntity entity=null; entity=new UrlEncodedFormEntity(params); final HttpPost post=new HttpPost(FETCH_FRIEND_UPDATES_URI); post.addHeader(entity.getContentType()); post.setEntity(entity); maybeCreateHttpClient(); final HttpResponse resp=mHttpClient.execute(post); final String response=EntityUtils.toString(resp.getEntity()); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { final JSONArray friends=new JSONArray(response); Log.d(TAG,response); for (int i=0; i < friends.length(); i++) { friendList.add(User.valueOf(friends.getJSONObject(i))); } } else { if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { Log.e(TAG,"Authentication exception in fetching remote contacts"); throw new AuthenticationException(); } else { Log.e(TAG,"Server error in fetching remote contacts: " + resp.getStatusLine()); throw new IOException(); } } return friendList; }
Example 15
From project android-tether, under directory /facebook/src/com/facebook/android/.
Source file: Util.java

/** * Parse a server response into a JSON Object. This is a basic implementation using org.json.JSONObject representation. More sophisticated applications may wish to do their own parsing. The parsed JSON is checked for a variety of error fields and a FacebookException is thrown if an error condition is set, populated with the error message and error type or code if available. * @param response - string representation of the response * @return the response as a JSON Object * @throws JSONException - if the response is not valid JSON * @throws FacebookError - if an error condition is set */ public static JSONObject parseJson(String response) throws JSONException, FacebookError { if (response.equals("false")) { throw new FacebookError("request failed"); } if (response.equals("true")) { response="{value : true}"; } JSONObject json=new JSONObject(response); if (json.has("error")) { JSONObject error=json.getJSONObject("error"); throw new FacebookError(error.getString("message"),error.getString("type"),0); } if (json.has("error_code") && json.has("error_msg")) { throw new FacebookError(json.getString("error_msg"),"",Integer.parseInt(json.getString("error_code"))); } if (json.has("error_code")) { throw new FacebookError("request failed","",Integer.parseInt(json.getString("error_code"))); } if (json.has("error_msg")) { throw new FacebookError(json.getString("error_msg")); } if (json.has("error_reason")) { throw new FacebookError(json.getString("error_reason")); } return json; }
Example 16
From project android-xbmcremote, under directory /src/org/xbmc/android/util/.
Source file: HostFactory.java

/** * Parses a JSON-formatted string into a Host object. * @param str a JSON string * @return a Host object that represents str, or null if an error occurred */ public static Host getHostFromJson(String str){ try { JSONObject json=(JSONObject)new JSONTokener(str).nextValue(); Host host=new Host(); host.name=json.getString("name"); host.addr=json.getString("addr"); host.port=json.getInt("port"); host.user=json.getString("user"); host.pass=json.getString("pass"); host.esPort=json.getInt("esPort"); host.timeout=json.getInt("timeout"); host.wifi_only=json.getBoolean("wifi_only"); host.access_point=json.getString("access_point"); host.mac_addr=json.getString("mac_addr"); host.wol_wait=json.getInt("wol_wait"); host.wol_port=json.getInt("wol_port"); return host; } catch ( JSONException e) { Log.e(TAG,"Error in parseJson",e); return null; } }
Example 17
From project AndroidBillingLibrary, under directory /AndroidBillingLibrary/src/net/robotmedia/billing/.
Source file: BillingController.java

/** * Parse all purchases from the JSON data received from the Market Billing service. * @param data JSON data received from the Market Billing service. * @return list of purchases. * @throws JSONException if the data couldn't be properly parsed. */ private static List<Transaction> parsePurchases(JSONObject data) throws JSONException { ArrayList<Transaction> purchases=new ArrayList<Transaction>(); JSONArray orders=data.optJSONArray(JSON_ORDERS); int numTransactions=0; if (orders != null) { numTransactions=orders.length(); } for (int i=0; i < numTransactions; i++) { JSONObject jElement=orders.getJSONObject(i); Transaction p=Transaction.parse(jElement); purchases.add(p); } return purchases; }
Example 18
From project androidquery, under directory /demo/src/com/androidquery/test/async/.
Source file: AjaxLoadingActivity.java

public void cookieCb(String url,JSONObject jo,AjaxStatus status){ JSONObject result=new JSONObject(); try { result.putOpt("cookies",jo.optJSONObject("cookies")); } catch ( JSONException e) { } showResult(result,status); }
Example 19
From project androidTileMapEditor_1, under directory /src/it/sineo/android/tileMapEditor/.
Source file: TileMap.java

/** * Returns a JSON representation of this map. No transient data is stored. * @return */ public String toJSON(){ JSONObject o=new JSONObject(); try { o.put("name",name); o.put("rows",rows); o.put("columns",columns); o.put("scale",scale); o.put("xOff",xOff); o.put("yOff",yOff); for (int idxRow=0; idxRow < rows; idxRow++) { for (int idxCol=0; idxCol < columns; idxCol++) { if (tilePaths[idxRow][idxCol] != null) { o.put("paths_" + idxRow + "_"+ idxCol,tilePaths[idxRow][idxCol]); o.put("angles_" + idxRow + "_"+ idxCol,tileAngles[idxRow][idxCol]); } } } } catch ( JSONException jsonex) { jsonex.printStackTrace(); } String json=o.toString(); return json; }
Example 20
From project androidtracks, under directory /src/org/sfcta/cycletracks/.
Source file: TripUploader.java

private JSONObject getCoordsJSON(long tripId) throws JSONException { SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); mDb.openReadOnly(); Cursor tripCoordsCursor=mDb.fetchAllCoordsForTrip(tripId); Map<String,Integer> fieldMap=new HashMap<String,Integer>(); fieldMap.put(TRIP_COORDS_TIME,tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_TIME)); fieldMap.put(TRIP_COORDS_LAT,tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_LAT)); fieldMap.put(TRIP_COORDS_LON,tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_LGT)); fieldMap.put(TRIP_COORDS_ALT,tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ALT)); fieldMap.put(TRIP_COORDS_SPEED,tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_SPEED)); fieldMap.put(TRIP_COORDS_HACCURACY,tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ACC)); fieldMap.put(TRIP_COORDS_VACCURACY,tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ACC)); JSONObject tripCoords=new JSONObject(); while (!tripCoordsCursor.isAfterLast()) { JSONObject coord=new JSONObject(); coord.put(TRIP_COORDS_TIME,df.format(tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_TIME)))); coord.put(TRIP_COORDS_LAT,tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_LAT)) / 1E6); coord.put(TRIP_COORDS_LON,tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_LON)) / 1E6); coord.put(TRIP_COORDS_ALT,tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_ALT))); coord.put(TRIP_COORDS_SPEED,tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_SPEED))); coord.put(TRIP_COORDS_HACCURACY,tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_HACCURACY))); coord.put(TRIP_COORDS_VACCURACY,tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_VACCURACY))); tripCoords.put(coord.getString("rec"),coord); tripCoordsCursor.moveToNext(); } tripCoordsCursor.close(); mDb.close(); return tripCoords; }
Example 21
From project android_packages_apps_QuickSearchBox, under directory /src/com/android/quicksearchbox/google/.
Source file: GoogleSuggestClient.java

@Override public String getSuggestionQuery(){ try { return mSuggestions.getString(getPosition()); } catch ( JSONException e) { Log.w(LOG_TAG,"Error parsing response: " + e); return null; } }
Example 22
From project android_packages_apps_Superuser, under directory /src/com/noshufou/android/su/service/.
Source file: UpdaterService.java

public boolean populate(JSONArray jsonArray){ try { int myVersionCode=getPackageManager().getPackageInfo(getPackageName(),0).versionCode; JSONObject manifest=null; for (int i=0; i < jsonArray.length(); i++) { manifest=jsonArray.getJSONObject(i); if (manifest.getInt("min-apk-version") <= myVersionCode) break; } if (manifest == null) return false; version=manifest.getString("version"); versionCode=manifest.getInt("version-code"); String abi=Build.CPU_ABI.split("-")[0]; JSONObject binaryInfo=manifest.getJSONObject(abi); binaryUrl=binaryInfo.getString("binary"); binaryMd5=binaryInfo.getString("binary-md5sum"); } catch ( JSONException e) { return false; } catch ( NameNotFoundException e) { Log.e(TAG,"Divided by zero...",e); return false; } if (version == null || versionCode == 0 || binaryUrl == null || binaryMd5 == null) { return false; } return true; }
Example 23
From project Android_Pusher, under directory /src/com/emorym/android_pusher/.
Source file: Pusher.java

private void sendSubscribeMessage(PusherChannel channel){ if (!isConnected()) return; try { String eventName=PUSHER_EVENT_SUBSCRIBE; JSONObject eventData=new JSONObject(); eventData.put("channel",channel.getName()); if (channel.isPrivate()) { String authInfo=authenticate(channel.getName()); eventData.put("auth",authInfo); } sendEvent(eventName,eventData,null); Log.d(LOG_TAG,"subscribed to channel " + channel.getName()); } catch ( JSONException e) { e.printStackTrace(); } }
Example 24
From project androlog, under directory /androlog/src/main/java/de/akquinet/android/androlog/reporter/.
Source file: Report.java

/** * Creates the report as a JSON Object. * @return the json object containing the report. */ public JSONObject getReportAsJSON(){ JSONObject report=new JSONObject(); try { addReportHeader(report); addApplicationData(report); addDeviceData(report); addLog(report); } catch ( JSONException e) { e.printStackTrace(); } return report; }
Example 25
From project andstatus, under directory /src/org/andstatus/app/account/.
Source file: AccountSettings.java

@Override protected JSONObject doInBackground(Void... arg0){ JSONObject jso=null; int what=MSG_NONE; String message=""; if (!skip) { what=MSG_ACCOUNT_INVALID; try { if (state.myAccount.verifyCredentials(true)) { what=MSG_ACCOUNT_VALID; } } catch ( ConnectionException e) { what=MSG_CONNECTION_EXCEPTION; message=e.toString(); } catch ( ConnectionAuthenticationException e) { what=MSG_ACCOUNT_INVALID; } catch ( ConnectionCredentialsOfOtherUserException e) { what=MSG_CREDENTIALS_OF_OTHER_USER; } catch ( ConnectionUnavailableException e) { what=MSG_SERVICE_UNAVAILABLE_ERROR; } catch ( SocketTimeoutException e) { what=MSG_SOCKET_TIMEOUT_EXCEPTION; } } try { jso=new JSONObject(); jso.put("what",what); jso.put("message",message); } catch ( JSONException e) { e.printStackTrace(); } return jso; }
Example 26
From project andtweet, under directory /src/com/xorcode/andtweet/.
Source file: AndTweetService.java

/** * TODO: Delete unnecessary lines... This is in the UI thread, so we can mess with the UI * @return ok */ protected void onPostExecute(JSONObject jso){ String message=null; if (jso != null) { try { int what=jso.getInt("what"); message=jso.getString("message"); switch (what) { case 0: break; } } catch ( JSONException e) { e.printStackTrace(); } } startEndStuff(false,this,message); }
Example 27
From project ANE-In-App-Purchase, under directory /NativeAndroid/src/com/freshplanet/inapppurchase/.
Source file: BillingService.java

/** * Verifies that the data was signed with the given signature, and calls {@link ResponseHandler#purchaseResponse(Context,PurchaseState,String,String,long)}for each verified purchase. * @param startId an identifier for the invocation instance of this service * @param signedData the signed JSON string (signed, not encrypted) * @param signature the signature for the data, signed with the private key */ private void purchaseStateChanged(int startId,String signedData,String signature){ Log.e("BillingService","purchaseStateChanged " + signedData + " . "+ signature); JSONObject jsonObject=new JSONObject(); try { JSONObject obj=new JSONObject(); obj.put("signedData",signedData); obj.put("signature",signature); obj.put("startId",startId); jsonObject.put("receipt",obj); } catch ( JSONException e) { e.printStackTrace(); } try { jsonObject.put("receiptType","GooglePlay"); } catch ( JSONException e) { e.printStackTrace(); } Log.e(TAG,jsonObject.toString()); if (Extension.context != null) { Extension.context.dispatchStatusEventAsync("PURCHASE_SUCCESSFUL",jsonObject.toString()); } else { Log.e(TAG,"context is null"); } }
Example 28
From project Anki-Android, under directory /src/com/ichi2/anki/.
Source file: AnkiDroidProxy.java

public int connect(){ if (mDecks == null) { String decksString=getDecks(); try { JSONObject jsonDecks=new JSONObject(decksString); if ("OK".equalsIgnoreCase(jsonDecks.getString("status"))) { mDecks=jsonDecks.getJSONObject("decks"); Log.i(AnkiDroidApp.TAG,"Server decks = " + mDecks.toString()); mTimestamp=jsonDecks.getDouble("timestamp"); Log.i(AnkiDroidApp.TAG,"Server timestamp = " + mTimestamp); return LOGIN_OK; } else if ("invalidUserPass".equalsIgnoreCase(jsonDecks.getString("status"))) { return LOGIN_INVALID_USER_PASS; } } catch ( JSONException e) { Log.i(AnkiDroidApp.TAG,"JSONException = " + e.getMessage()); } } return LOGIN_OK; }