List of usage examples for org.json JSONObject getString
public String getString(String key) throws JSONException
From source file:com.provision.alarmemi.paper.fragments.SetAlarmFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) { mActivity.setOnLifeCycleChangeListener(this); isChanged = isCloud = false;//from w w w . j av a2s . com // Override the default content view. root = (ViewGroup) super.onCreateView(inflater, container, bundle); final ImageView moreAlarm = (ImageView) root.findViewById(R.id.more_alarm); FragmentChangeActivity.moreAlarm = moreAlarm; moreAlarm.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (menu.isMenuShowing()) { menu.showContent(); } else { menu.showMenu(true); } } }); // Make the entire view selected when focused. moreAlarm.setOnFocusChangeListener(new View.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { v.setSelected(hasFocus); } }); addPreferencesFromResource(R.xml.alarm_prefs); myUUID = SplashActivity.myUUID; // Get each preference so we can retrieve the value later. mLabel = findPreference("label"); mLabel.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { showEditTextPreference(mLabel.getKey(), mLabel.getTitle(), mLabelText); return true; } }); Preference.OnPreferenceChangeListener preferceChangedListener = new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference p, Object newValue) { isChanged = true; return true; } }; mEnabledPref = (CheckBoxPreference) findPreference("enabled"); mEnabledPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if (!isCloud) { isChanged = true; if ((Boolean) newValue) showCategory(); else hideCategory(); return true; } if ((Boolean) newValue) { try { tempjson = new JSONArray("[]"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } selectedDevice = ""; for (int i = 0; i < json.length(); i++) { if (UIDitems[i].toString().equals(myUUID)) checkedItems[i] = true; if (checkedItems[i]) { Map<String, String> map = new HashMap<String, String>(); map.put("name", URLDecoder.decode(items[i].toString())); map.put("uid", UIDitems[i].toString()); tempjson.put(map); selectedDevice += items[i] + ", "; } } if (!selectedDevice.equals("")) selectedDevice = selectedDevice.substring(0, selectedDevice.length() - 2); } else { try { tempjson = new JSONArray("[]"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } selectedDevice = ""; for (int i = 0; i < json.length(); i++) { if (UIDitems[i].toString().equals(myUUID)) checkedItems[i] = false; if (checkedItems[i]) { Map<String, String> map = new HashMap<String, String>(); map.put("name", URLDecoder.decode(items[i].toString())); map.put("uid", UIDitems[i].toString()); tempjson.put(map); selectedDevice += items[i] + ", "; } } if (!selectedDevice.equals("")) selectedDevice = selectedDevice.substring(0, selectedDevice.length() - 2); } mForest.setSummary(selectedDevice); isChanged = true; return true; } }); mTimePref = findPreference("time"); mVibratePref = (CheckBoxPreference) findPreference("vibrate"); mVibratePref.setOnPreferenceChangeListener(preferceChangedListener); mRepeatPref = findPreference("setRepeat"); mRepeatPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { String[] values = new String[] { DateUtils.getDayOfWeekString(Calendar.MONDAY, DateUtils.LENGTH_LONG), DateUtils.getDayOfWeekString(Calendar.TUESDAY, DateUtils.LENGTH_LONG), DateUtils.getDayOfWeekString(Calendar.WEDNESDAY, DateUtils.LENGTH_LONG), DateUtils.getDayOfWeekString(Calendar.THURSDAY, DateUtils.LENGTH_LONG), DateUtils.getDayOfWeekString(Calendar.FRIDAY, DateUtils.LENGTH_LONG), DateUtils.getDayOfWeekString(Calendar.SATURDAY, DateUtils.LENGTH_LONG), DateUtils.getDayOfWeekString(Calendar.SUNDAY, DateUtils.LENGTH_LONG) }; Intent intent = new Intent(mActivity, RepeatListPreference.class); intent.putExtra("key", mRepeatPref.getKey()); intent.putExtra("title", mRepeatPref.getTitle()); intent.putExtra("lists", values); intent.putExtra("multi", true); startActivity(intent); return true; } }); mForestName = findPreference("forest_name"); mForest = findPreference("forest"); mColorPref = (AmbilWarnaPreference) findPreference("color"); prefs = mActivity.getSharedPreferences("forest", mActivity.MODE_PRIVATE); Intent i = mActivity.setAlarmGetIntent; mId = i.getIntExtra(Alarms.ALARM_ID, -1); alarm = null; if (mId == -1) { // No alarm id means create a new alarm. alarm = new Alarm(); isChanged = true; } else { // * load alarm details from database alarm = Alarms.getAlarm(mActivity.getContentResolver(), mId); // Bad alarm, bail to avoid a NPE. if (alarm == null) { finish(); return root; } isCloud = wasCloud = alarm.cloudEnabled; } mOriginalAlarm = alarm; if (wasCloud) { try { Log.e("url", " : " + alarm.cloudName); json = new JSONArray(prefs.getString(alarm.cloudName + "_registeredDevice", "")); String cloud_uid = alarm.cloudUID; if (cloud_uid.equals("")) cloud_uid = "[]"; Log.e("url", cloud_uid); tempjson = new JSONArray(cloud_uid); items = new String[json.length()]; UIDitems = new CharSequence[json.length()]; checkedItems = new boolean[json.length()]; for (int j = 0; j < json.length(); j++) { JSONObject jsonObj = json.getJSONObject(j); items[j] = jsonObj.getString("name"); UIDitems[j] = jsonObj.getString("uid"); checkedItems[j] = alarm.cloudUID.contains(jsonObj.getString("uid")); } } catch (Exception e) { Log.e("url", e.toString()); } selectedDevice = alarm.cloudDevices; mForestName.setEnabled(false); } else { if (prefs.getString("name", "").length() > 0) { names = prefs.getString("name", "").substring(1).split("\\|"); nameCheckedIndex = -1; } else mForestName.setEnabled(false); mForest.setEnabled(false); } memi_count = alarm.memiCount; snooze_strength = alarm.snoozeStrength; snooze_count = alarm.snoozeCount; updatePrefs(mOriginalAlarm); mTimePref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference arg0) { showTimePicker(); return false; } }); mForestName.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { showListPreference(mForestName.getKey(), mForestName.getTitle(), names, String.valueOf(nameCheckedIndex), false); return true; } }); mForest.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference arg0) { showListPreference(mForest.getKey(), mForest.getTitle(), items, booleanArrayToString(checkedItems), true); return true; } }); mColorPref.setOnPreferenceChangeListener(preferceChangedListener); // We have to do this to get the save/cancel buttons to highlight on // their own. ((ListView) root.findViewById(android.R.id.list)).setItemsCanFocus(true); // Attach actions to each button. View.OnClickListener back_click = new View.OnClickListener() { public void onClick(View v) { DontSaveDialog(false, null, false); } }; ImageView b = (ImageView) root.findViewById(R.id.back); b.setOnClickListener(back_click); b = (ImageView) root.findViewById(R.id.logo); b.setOnClickListener(back_click); b = (ImageView) root.findViewById(R.id.alarm_save); b.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { saveAlarm(); } }); b = (ImageView) root.findViewById(R.id.alarm_delete); if (mId == -1) { b.setEnabled(false); } else { b.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { deleteAlarm(); } }); } // The last thing we do is pop the time picker if this is a new alarm. if (mId == -1) { // Assume the user hit cancel mTimePickerCancelled = true; showTimePicker(); } if (!isCloud && !alarm.enabled) hideCategory(); FragmentChangeActivity.OnNotifyArrived.sendEmptyMessage(0); return root; }
From source file:com.provision.alarmemi.paper.fragments.SetAlarmFragment.java
public static void onActivityResult(String key, String which_str) { if (mForestName.getKey().equals(key)) { int which = Integer.parseInt(which_str); mForestName.setSummary(names[which]); String json_string = prefs.getString(names[which] + "_registeredDevice", ""); if (json_string.equals("")) json_string = "[]"; try {//from w w w. j ava 2 s. c o m json = new JSONArray(json_string); tempjson = new JSONArray("[]"); items = new String[json.length()]; UIDitems = new CharSequence[json.length()]; checkedItems = new boolean[json.length()]; for (int j = 0; j < json.length(); j++) { JSONObject jsonObj = json.getJSONObject(j); items[j] = jsonObj.getString("name"); UIDitems[j] = jsonObj.getString("uid"); checkedItems[j] = alarm.cloudUID.contains(jsonObj.getString("uid")); } } catch (JSONException e) { e.printStackTrace(); } nameCheckedIndex = which; selectedDevice = ""; if (mEnabledPref.isChecked()) { for (int i = 0; i < json.length(); i++) { if (UIDitems[i].toString().equals(myUUID)) checkedItems[i] = true; if (checkedItems[i]) { Map<String, String> map = new HashMap<String, String>(); map.put("name", URLDecoder.decode(items[i].toString())); map.put("uid", UIDitems[i].toString()); tempjson.put(map); selectedDevice += items[i] + ", "; } } } else { for (int i = 0; i < json.length(); i++) { if (UIDitems[i].toString().equals(myUUID)) checkedItems[i] = false; if (checkedItems[i]) { Map<String, String> map = new HashMap<String, String>(); map.put("name", URLDecoder.decode(items[i].toString())); map.put("uid", UIDitems[i].toString()); tempjson.put(map); selectedDevice += items[i] + ", "; } } } if (!selectedDevice.equals("")) selectedDevice = selectedDevice.substring(0, selectedDevice.length() - 2); mForest.setSummary(selectedDevice); mForest.setEnabled(true); isChanged = isCloud = true; } else if (mForest.getKey().equals(key)) { String[] str_array = which_str.split("\\|"); boolean[] values = new boolean[str_array.length]; for (int i = 0; i < str_array.length; i++) { values[i] = str_array[i].equals("1"); } checkedItems = values; boolean hasMyDevice = false; try { tempjson = new JSONArray("[]"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } selectedDevice = ""; for (int i = 0; i < json.length(); i++) { if (values[i]) { if (UIDitems[i].toString().equals(myUUID)) hasMyDevice = true; Map<String, String> map = new HashMap<String, String>(); map.put("name", URLDecoder.decode(items[i].toString())); map.put("uid", UIDitems[i].toString()); tempjson.put(map); selectedDevice += items[i] + ", "; } } if (!selectedDevice.equals("")) selectedDevice = selectedDevice.substring(0, selectedDevice.length() - 2); mForest.setSummary(selectedDevice); mEnabledPref.setChecked(hasMyDevice); isChanged = true; } else if (mLabel.getKey().equals(key)) { mLabelText = which_str; mLabel.setSummary(which_str); isChanged = true; } }
From source file:com.example.pyrkesa.shwc.OngoingNotificationListenerService.java
@Override public void onDataChanged(DataEventBuffer dataEvents) { final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents); final String ACTION_DEMAND = "ACTION_DEMAND"; String EXTRA_CMD = "EXTRA_CMD"; dataEvents.close();/*w ww. j a va2 s. c om*/ if (!mGoogleApiClient.isConnected()) { ConnectionResult connectionResult = mGoogleApiClient.blockingConnect(30, TimeUnit.SECONDS); if (!connectionResult.isSuccess()) { Log.e(TAG, "Service failed to connect to GoogleApiClient."); return; } } for (DataEvent event : events) { if (event.getType() == DataEvent.TYPE_CHANGED) { String path = event.getDataItem().getUri().getPath(); if (PATH.equals(path)) { // Get the data out of the event DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem()); //final String title = dataMapItem.getDataMap().getString(KEY_TITLE); final String room_devices = dataMapItem.getDataMap().getString(KEY_ROOM_DEVICES); final String room_name = dataMapItem.getDataMap().getString(KEY_ROOM_NAME); // Asset asset = dataMapItem.getDataMap().getAsset(KEY_BACKGROUND); try { JSONObject roomJSON = new JSONObject(room_devices); JSONArray devicesArray = roomJSON.getJSONArray("devices"); String firstPageText = "quipements :"; ArrayList<Device> devicess = new ArrayList<Device>(); for (int i = 0; i < devicesArray.length(); i++) { JSONObject d = devicesArray.getJSONObject(i); Device device = new Device(d.getString("id"), d.getString("name"), d.getInt("type"), d.getString("status")); String Newline = System.getProperty("line.separator"); firstPageText += Newline; firstPageText += device.name; devicess.add(device); } if (firstPageText.equalsIgnoreCase("quipements :")) { firstPageText = "Aucun quipement"; } Bitmap background = BitmapFactory.decodeResource(this.getResources(), R.drawable.bg_distance); NotificationCompat.WearableExtender notifExtender = new NotificationCompat.WearableExtender(); for (Device d : devicess) { try { notifExtender.addAction(d.getAction(OngoingNotificationListenerService.this)); } catch (Exception e) { Log.e("Erreur get Action :", e.getMessage()); } } NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setContentTitle("Pice : " + roomJSON.getString("name")) .setContentText(firstPageText).setSmallIcon(R.drawable.mini_logo) .extend(notifExtender.setBackground(background)).setOngoing(true); // Build the notification and show it NotificationManager notificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE); notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build()); } catch (Throwable t) { Log.e("JSON_WEAR_SHWC", "Could not parse malformed JSON: " + room_devices + t.getMessage()); } } else { Log.d(TAG, "Unrecognized path: " + path); } } } }
From source file:com.zaizi.alfresco.crowd.authentication.filter.CrowdSSOFilter.java
/** * <p>/*w w w . ja v a2 s . co m*/ * The filter checks if a crowd cookie exists in the request in order to try to authenticate automatically * the user * </p> * * @param request * The request * @param response * The response * @param chain * The filter chain containing the rest of the configured filters */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String endpoint = this.frameworkUtils.getEndpoint(ENDPOINT_ID).getEndpointUrl(); /* Create a Remote client for the configured endpoint id */ RemoteClient remote = createRemoteClient(endpoint, httpRequest.getSession(true)); /* Manages the cookies */ CookieManager cookieManager = new CookieManager(); String cookieValue = null; Boolean crowdCookiePresent = false; try { cookieValue = cookieManager.getCookieValue(httpRequest, CROWD_COOKIE_NAME).toString(); crowdCookiePresent = true; } catch (CookieNotFoundException e) { logger.debug("Crowd cookie not found in the request"); } /* If authenticated, trying to enable SSO if it is not enabled yet */ if (AuthenticationUtil.isAuthenticated(httpRequest)) { // Checks if Crowd Cookie exists. If not, trying to create a Crowd token to enable SSO if (!crowdCookiePresent) { enableSSO(remote, cookieManager, httpRequest, httpResponse); } /* Continue the filter chain */ chain.doFilter(httpRequest, response); return; } /* If not authenticated and no cookie present, continue the chain */ if (!crowdCookiePresent) { chain.doFilter(httpRequest, httpResponse); return; } /* Cookie present. Trying to create Share session */ try { /* Call the validation token endpoint */ Response resp = remote.call(String.format(CROWD_TOKEN_VALIDATION_URL, cookieValue)); /* JSON Response */ JSONObject jsonResp = new JSONObject(resp.getResponse()); /* If it is a valid response... */ if (jsonResp.getBoolean(VALID_KEY)) { // Use the token and user to create the session in the connector and share String alfTicket = jsonResp.getString(ALF_TICKET_KEY); String userId = jsonResp.getString(USER_KEY); /* Set credentials in the connector and login the user in Share */ setUserCredentialsInConnector(httpRequest.getSession(), alfTicket, userId); AuthenticationUtil.login(httpRequest, httpResponse, userId); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } chain.doFilter(httpRequest, httpResponse); }
From source file:com.zaizi.alfresco.crowd.authentication.filter.CrowdSSOFilter.java
/** * <p>Enable the SSO, obtaining a Crowd token for the already authenticated user and putting it into a Crowd cookie<p> * /*from w ww . j a va 2s . c om*/ * @param remote the {@code RemoteClient} object to communicate with Alfresco * @param cookieManager the {@code CookieManager} object used to obtain and create cookies * @param request the {@code HttpServletRequest} object * @param response the {@code HttpServletResponse} object where put the token to */ private void enableSSO(RemoteClient remote, CookieManager cookieManager, HttpServletRequest request, HttpServletResponse response) { Response resp = remote.call(CROWD_GET_TOKEN); try { JSONObject jsonResponse = new JSONObject(resp.getResponse()); if (jsonResponse.has(TOKEN_KEY)) cookieManager.putCookieValue(request, response, CROWD_COOKIE_NAME, -1, jsonResponse.getString(TOKEN_KEY)); } catch (JSONException e) { logger.debug("Unable to process the response"); } }
From source file:com.example.wmgps.MainActivity.java
/** Called when the user clicks the Send button */ public void sendMessage(View view) { /*Intent intent = new Intent(this, DisplayMessageActivity.class); EditText editText = (EditText) findViewById(R.id.edit_message); String message = editText.getText().toString(); intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent);*/// ww w. java 2 s .co m /*EditText editText = (EditText) findViewById(R.id.edit_message); String message = editText.getText().toString(); TextView output = (TextView) findViewById(R.id.welcome); output.setText(message);*/ /*Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(URL)); startActivity(browserIntent); */ TextView hiddenText = (TextView) findViewById(R.id.Hidden11); if (Misc.isNullTrimmedString(hiddenText.getText().toString())) { TextView output = (TextView) findViewById(R.id.welcome1); boolean without_connection = true; Map<String, ArrayList<String>> typeAndValueOfTag = new LinkedHashMap<String, ArrayList<String>>(); // Insertion order must be followed String response = Misc.EMPTY_STRING; String welcome1String = "*******************Connected*************************"; try { response = new RetrieveFeedTask().execute(new String[] {}).get(); } catch (Exception e) { response = Misc.EMPTY_STRING; Log.e("Exception ", e.getMessage()); Log.e("Exception ", e.getLocalizedMessage()); Log.e("Exception ", e.getStackTrace().toString()); } if (Misc.isNullTrimmedString(response)) { // welcome1String = "***Loading Static, couldn't connect***"; response = "{\"window\":{\"elements\":[{\"type\":\"hidden\",\"name\":\"sourceAction\"},{\"type\":\"label\",\"value\":\"Warehouse Management\"}," + "{\"type\":\"break\"},{\"type\":\"label\",\"value\":\"--------- ----------\"},{\"type\":\"break\"}, {\"type\":\"label\",\"value\":\" User ID: \"}," + "{\"type\":\"entry\",\"name\":\"j_username\",\"value\":\"\",\"maxLength\":15,\"dispLength\":10," + "\"setHidden\":[{\"hiddenName\":\"sourceAction\",\"hiddenValue\":\"username\"}],\"focus\":true}," + "{\"type\":\"break\"},{\"type\":\"label\",\"value\":\"Password: \"}," + "{\"type\":\"entry\",\"name\":\"j_password\",\"value\":\"\",\"hideInput\":true,\"maxLength\":14,\"dispLength\":10,\"focus\":false}," + "{\"type\":\"keybinding\",\"value\":\"CTRL-X\",\"URL\":\"\",\"keyDescription\":\"CTRL-X Exit\"}," + "{\"type\":\"keybinding\",\"value\":\"CTRL-L\",\"URL\":\"/scopeRF/RFLogin/RFLegal.jsp\",\"keyDescription\":\"CTRL-L License Agreement\"}]" + ",\"submit\":\"/scopeRF/RFLogin/ProcessLogin.jsp\"}}"; } StringBuffer finalEncodedString = new StringBuffer(Misc.EMPTY_STRING); int currentOutputTag = R.id.Hidden1; int currentInputTag = R.id.edit_message; // Renderer::decodeConfig() if (!Misc.isNullTrimmedString(response)) { try { JSONObject jsonObj = new JSONObject(response); for (Iterator iterator = jsonObj.keys(); iterator.hasNext();) { String name = (String) iterator.next(); JSONObject jsonObj1 = jsonObj.getJSONObject(name); for (Iterator iterator1 = jsonObj1.keys(); iterator1.hasNext();) { String name1 = (String) iterator1.next(); if ("elements".equals(name1)) { JSONArray jsonArr = jsonObj1.getJSONArray(name1); boolean userName = false; boolean password = false; for (int i = 0; i < jsonArr.length(); i++) { JSONObject temp = jsonArr.getJSONObject(i); String initialValue = null; String initialName = null; String initialLabel = null; if (!temp.isNull("name") && temp.getString("name").equals("j_password")) { initialName = "j_password"; } else if (!temp.isNull("name") && temp.getString("name").equals("j_username")) { initialName = "j_username"; } for (Iterator iterator2 = temp.keys(); iterator2.hasNext();) { String tempName = (String) iterator2.next(); String tempValue = (String) temp.getString(tempName); if (tempName.equals("type")) { if (tempValue.equals("label") || tempValue.equals("entry")) { initialLabel = tempValue; } } else if (tempName.equals("value")) { initialValue = tempValue; } /* if(tempName.equals("label")) { if(Misc.isNullTrimmedString(initialValue)) initialLabel = tempName; else { typeAndValueOfTag.put("output",initialValue); initialValue = Misc.EMPTY_STRING; continue; } } else if(tempName.equals("value")) { if(Misc.isNullTrimmedString(initialName) && Misc.isNullTrimmedString(initialLabel)) { initialValue = tempValue; } else if(!Misc.isNullTrimmedString(initialLabel) && initialLabel.equals("label")) { typeAndValueOfTag.put("output",tempValue); initialValue = Misc.EMPTY_STRING; continue; } else if(!Misc.isNullTrimmedString(initialLabel) && initialLabel.equals("entry")) { if(!Misc.isNullTrimmedString(initialName) && initialName.equals("name")) typeAndValueOfTag.put("input",tempValue); else initialValue = tempValue; } } else if(tempName.equals("entry")) { if(Misc.isNullTrimmedString(initialValue) || Misc.isNullTrimmedString(initialLabel)) { initialName = tempName; } else typeAndValueOfTag.put("input",initialValue); finalEncodedString.append(" " + tempName + " " + tempValue + " ----- "); }*/ } if (initialLabel != null) { if (initialLabel.equals("label")) { if (initialValue.equals(" User ID: ")) { TextView output1 = (TextView) findViewById(R.id.userNameText); output1.setText(initialValue); output1.setVisibility(View.VISIBLE); userName = true; password = false; } else if (initialValue.equals("Password: ")) { TextView output1 = (TextView) findViewById(R.id.passwordText); output1.setText(initialValue); output1.setVisibility(View.VISIBLE); password = true; userName = false; } else { TextView output1 = (TextView) findViewById(currentOutputTag++); output1.setText(initialValue); output1.setVisibility(View.VISIBLE); userName = false; password = false; } } else if (initialLabel.equals("entry")) { if ("j_password".equals(initialName)) { EditText input = ((EditText) findViewById(R.id.passwordEdit)); input.setVisibility(View.VISIBLE); if (Misc.isNullTrimmedString(initialValue)) { input.setText(""); input.setHint("Please enter password"); } } else if ("j_username".equals(initialName)) { EditText input = ((EditText) findViewById(R.id.userNameEdit)); input.setVisibility(View.VISIBLE); if (Misc.isNullTrimmedString(initialValue)) { input.setText(""); input.setHint("Please enter username"); } } else { EditText input = ((EditText) findViewById(currentInputTag++)); input.setVisibility(View.VISIBLE); if (Misc.isNullTrimmedString(initialValue)) { input.setText(""); input.setHint("Please enter value"); } else input.setText(initialValue); } } } /*if(initialLabel != null) { List<String> listOfValues; if(typeAndValueOfTag.containsKey(initialLabel)) { listOfValues = typeAndValueOfTag.get(initialLabel); listOfValues.add(initialValue); } typeAndValueOfTag.put(initialLabel,initialValue); }*/ } } else { // Here, just the URL would get processed. So don't use. // output.setText(" " + name + " " + jsonObj1.getString(name1)); } } } TextView welcome1 = (TextView) findViewById(R.id.welcome1); welcome1.setText(welcome1String); // processUIDisplay(typeAndValueOfTag); /*if(finalEncodedString.length() == 0) finalEncodedString.append("Could not process"); output.setText(finalEncodedString.toString()); TextView output2 = (TextView) findViewById(R.id.Hidden1); output2.setText("Hidden one is enabled"); output2.setVisibility(View.VISIBLE);*/ } catch (JSONException e) { Log.e("Exception ", e.getMessage()); Log.e("Exception ", e.getLocalizedMessage()); Log.e("Exception ", e.getStackTrace().toString()); } } hiddenText.setText("validated user"); /* {"window":{"elements":[{"type":"hidden","name":"sourceAction"},{"type":"label","value":"Warehouse Management"}, {"type":"break"},{"type":"label","value":"--------- ----------"},{"type":"break"}, {"type":"label","value":" User ID: "}, {"type":"entry","name":"j_username","value":"","maxLength":15,"dispLength":10, "setHidden":[{"hiddenName":"sourceAction","hiddenValue":"username"}],"focus":true}, {"type":"break"},{"type":"label","value":"Password: "}, {"type":"entry","name":"j_password","value":"","hideInput":true,"maxLength":14,"dispLength":10,"focus":false}, {"type":"keybinding","value":"CTRL-X","URL":"","keyDescription":"CTRL-X Exit"}, {"type":"keybinding","value":"CTRL-L","URL":"/scopeRF/RFLogin/RFLegal.jsp","keyDescription":"CTRL-L License Agreement"}] ,"submit":"/scopeRF/RFLogin/ProcessLogin.jsp"}}*/ } else { List outputList = verifyUser(); if (!Misc.isNullList(outputList)) { String sessionId = (String) outputList.get(0); String userType = (String) outputList.get(1); Intent intent = new Intent(this, MenuActivity.class); if (!Misc.isNullTrimmedString(sessionId) && !Misc.isNullTrimmedString(userType) && Integer.parseInt(sessionId) > 0) { if (userType.equals(Constants.WORKER)) { MenuActivity.sessionId = Misc.EMPTY_STRING; TextView error = (TextView) findViewById(R.id.ErrorText); error.setText(Misc.EMPTY_STRING); error.setVisibility(View.GONE); intent.putExtra(Constants.USER_TYPE, Constants.WORKER); intent.putExtra(Constants.SESSION_ID, sessionId); } else { TextView error = (TextView) findViewById(R.id.ErrorText); error.setText(Misc.EMPTY_STRING); error.setVisibility(View.GONE); intent.putExtra(Constants.USER_TYPE, Constants.SUPERVISOR); intent.putExtra(Constants.SESSION_ID, sessionId); } } // goto Maps screen // Get the message from the intent startActivity(intent); } else { TextView error = (TextView) findViewById(R.id.ErrorText); error.setText("Invalid Username/Password"); error.setVisibility(View.VISIBLE); } } return; }
From source file:com.citrus.sdk.CitrusActivity.java
private void prepaidPayment(String response, String error) { TransactionResponse transactionResponse = null; if (!android.text.TextUtils.isEmpty(response)) { try {/*ww w. j a v a 2 s. c o m*/ JSONObject redirect = new JSONObject(response); if (!android.text.TextUtils.isEmpty(redirect.getString("redirectUrl"))) { setCookie(); mPaymentWebview.loadUrl(redirect.getString("redirectUrl")); if (mPaymentOption != null) { EventsManager.logWebViewEvents(CitrusActivity.this, WebViewEvents.OPEN, mPaymentOption.getAnalyticsPaymentType()); //analytics event } } else { transactionResponse = new TransactionResponse(TransactionResponse.TransactionStatus.FAILED, response, mTransactionId); sendResult(transactionResponse); } } catch (JSONException e) { e.printStackTrace(); } } else { transactionResponse = new TransactionResponse(TransactionResponse.TransactionStatus.FAILED, error, mTransactionId); sendResult(transactionResponse); } }
From source file:com.sonoport.freesound.response.mapping.Mapper.java
/** * Extract a named value from a {@link JSONObject}. This method checks whether the value exists and is not an * instance of <code>JSONObject.NULL</code>. * * @param jsonObject The {@link JSONObject} being processed * @param field The field to retrieve/*from www .ja v a 2 s . co m*/ * @param fieldType The data type of the field * @return The field value (or null if not found) * * @param <T> The data type to return */ @SuppressWarnings("unchecked") protected <T extends Object> T extractFieldValue(final JSONObject jsonObject, final String field, final Class<T> fieldType) { T fieldValue = null; if ((jsonObject != null) && jsonObject.has(field) && !jsonObject.isNull(field)) { try { if (fieldType == String.class) { fieldValue = (T) jsonObject.getString(field); } else if (fieldType == Integer.class) { fieldValue = (T) Integer.valueOf(jsonObject.getInt(field)); } else if (fieldType == Long.class) { fieldValue = (T) Long.valueOf(jsonObject.getLong(field)); } else if (fieldType == Float.class) { fieldValue = (T) Float.valueOf(Double.toString(jsonObject.getDouble(field))); } else if (fieldType == JSONArray.class) { fieldValue = (T) jsonObject.getJSONArray(field); } else if (fieldType == JSONObject.class) { fieldValue = (T) jsonObject.getJSONObject(field); } else { fieldValue = (T) jsonObject.get(field); } } catch (final JSONException | ClassCastException e) { // TODO Log a warning } } return fieldValue; }
From source file:org.tomdroid.sync.web.OAuthConnection.java
public Uri getAuthorizationUrl(String server) throws UnknownHostException { String url = ""; // this method shouldn't have been called if (isAuthenticated()) return null; rootApi = server + "/api/1.0/"; AnonymousConnection connection = new AnonymousConnection(); String response = connection.get(rootApi); JSONObject jsonResponse; try {/*from w ww. j ava 2s .c om*/ jsonResponse = new JSONObject(response); accessTokenUrl = jsonResponse.getString("oauth_access_token_url"); requestTokenUrl = jsonResponse.getString("oauth_request_token_url"); authorizeUrl = jsonResponse.getString("oauth_authorize_url"); } catch (JSONException e) { e.printStackTrace(); return null; } OAuthProvider provider = getProvider(); try { // the argument is the callback used when the remote authorization is complete url = provider.retrieveRequestToken(consumer, "tomdroid://sync"); requestToken = consumer.getToken(); requestTokenSecret = consumer.getTokenSecret(); oauth10a = provider.isOAuth10a(); accessToken = ""; accessTokenSecret = ""; saveConfiguration(); } catch (OAuthMessageSignerException e1) { e1.printStackTrace(); return null; } catch (OAuthNotAuthorizedException e1) { e1.printStackTrace(); return null; } catch (OAuthExpectationFailedException e1) { e1.printStackTrace(); return null; } catch (OAuthCommunicationException e1) { e1.printStackTrace(); return null; } TLog.i(TAG, "Authorization URL : {0}", url); return Uri.parse(url); }
From source file:com.streaming.sweetplayer.fragment.ArtistFragment.java
private void getSongsList(ArrayList<HashMap<String, String>> parseList, String url) { JSONParser jsonParser = new JSONParser(); JSONArray jsonArray;//from w ww . jav a 2s.c o m try { JSONObject json = jsonParser.getJSONFromUrl(url); if (json != null) { jsonArray = json.getJSONArray(mJsonItem); int array_length = jsonArray.length(); if (isSongsView) { for (int i = 0; i < array_length; i++) { HashMap<String, String> map = new HashMap<String, String>(); JSONObject jsonObject = jsonArray.getJSONObject(i); map.put(Config.ID, jsonObject.getString(Config.ID)); map.put(Config.ARTIST, jsonObject.getString(Config.ARTIST)); map.put(Config.NAME, jsonObject.getString(Config.SONG)); map.put(Config.MP3, jsonObject.getString(Config.MP3)); map.put(Config.DURATION, jsonObject.getString(Config.DURATION)); map.put(Config.URL, jsonObject.getString(Config.URL)); map.put(Config.IMAGE, mImageForDB); parseList.add(map); } } else { for (int i = 0; i < array_length; i++) { HashMap<String, String> map = new HashMap<String, String>(); JSONObject jsonObject = jsonArray.getJSONObject(i); map.put(Config.ID, jsonObject.getString(Config.ID)); map.put(Config.ALBUM, jsonObject.getString(Config.ALBUM)); map.put(Config.SONGS_ITEM, jsonObject.getString(Config.SONGS_ITEM)); map.put(Config.IMAGE, jsonObject.getString(Config.IMAGE)); map.put(Config.URL, jsonObject.getString(Config.URL)); parseList.add(map); } } } } catch (JSONException e) { e.printStackTrace(); } }