Example usage for org.json JSONObject getString

List of usage examples for org.json JSONObject getString

Introduction

In this page you can find the example usage for org.json JSONObject getString.

Prototype

public String getString(String key) throws JSONException 

Source Link

Document

Get the string associated with a key.

Usage

From source file:com.wms.ezyoukuuploader.sdk.task.YoukuVideoUploadTask.java

@Override
protected String doInBackground(String... params) { // params[0] is file name, params[1] is video title, params[2] is description
    YoukuUploader youkuUploader = activity.getYoukuUploader();

    HashMap<String, String> parameters = new HashMap<>();
    String accessToken = SharedPreferenceUtil.getPreferenceItemByName(activity,
            SharedPreferenceUtil.YoukuAccessToken);
    parameters.put(YoukuConstants.PARAM_ACCESS_TOKEN, accessToken);

    HashMap<String, String> uploadInfo = new HashMap<>();
    uploadInfo.put("file_name", params[0]);
    uploadInfo.put("title", params[1]);
    uploadInfo.put("description", params[2]);
    uploadInfo.put("tags", "EZYoukuUploader");

    youkuUploader.upload(parameters, uploadInfo, new IUploadResponseHandler() {

        @Override//from  w  w w.  j ava  2s  . c  o m
        public void onStart() {
            activity.toggleUploadingFlag(true);
            activity.toggleWidgetsEnabled(false);
            activity.resetProgress();
            Toast.makeText(activity, activity.getString(R.string.startUploadingVideo), Toast.LENGTH_LONG)
                    .show();
        }

        @Override
        public void onSuccess(JSONObject response) {
            activity.getTextViewProgress().setText("100%");
            try {
                String videoId = response.getString("video_id");
                activity.getTextViewVideoUrl().setText("http://v.youku.com/v_show/id_" + videoId);
            } catch (JSONException e) {
                // URL will not be updated
            }

            activity.toggleWidgetsEnabled(true);
            activity.preventUploadingSameVideo();
            Toast.makeText(activity, activity.getString(R.string.videoUploadCompleted), Toast.LENGTH_LONG)
                    .show();
        }

        @Override
        public void onProgressUpdate(int counter) {
            activity.getProgressBarUploadVideo().setProgress(counter);
            if (counter < 10) {
                activity.getTextViewProgress().setText(" 0" + counter + "%");
            } else {
                activity.getTextViewProgress().setText(" " + counter + "%");
            }
        }

        @Override
        public void onFailure(JSONObject errorResponse) {
            activity.toggleWidgetsEnabled(true);
            DialogUtil.showExceptionAlertDialog(activity, activity.getString(R.string.videoUploadFailedTitle),
                    activity.getString(R.string.videoUploadFailed));
        }

        @Override
        public void onFinished() {
            activity.toggleUploadingFlag(false);
        }
    });

    return null;
}

From source file:com.mobiperf_library.util.MeasurementJsonConvertor.java

public static MeasurementTask makeMeasurementTaskFromJson(JSONObject json) throws IllegalArgumentException {
    try {/*from  w  w w.jav  a2 s. co m*/
        String type = String.valueOf(json.getString("type"));
        Class taskClass = MeasurementTask.getTaskClassForMeasurement(type);
        Method getDescMethod = taskClass.getMethod("getDescClass");
        // The getDescClassForMeasurement() is static and takes no arguments
        Class descClass = (Class) getDescMethod.invoke(null, (Object[]) null);
        MeasurementDesc measurementDesc = (MeasurementDesc) gson.fromJson(json.toString(), descClass);

        Object cstParam = measurementDesc;
        Constructor<MeasurementTask> constructor = taskClass.getConstructor(MeasurementDesc.class);
        return constructor.newInstance(cstParam);
    } catch (JSONException e) {
        throw new IllegalArgumentException(e);
    } catch (SecurityException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (NoSuchMethodException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (IllegalArgumentException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (InstantiationException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (IllegalAccessException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (InvocationTargetException e) {
        Logger.w(e.toString());
        throw new IllegalArgumentException(e);
    }
}

From source file:org.everit.json.schema.IntegrationTest.java

@Parameters(name = "{2}")
public static List<Object[]> params() {
    List<Object[]> rval = new ArrayList<>();
    Reflections refs = new Reflections("org.everit.json.schema.draft4", new ResourcesScanner());
    Set<String> paths = refs.getResources(Pattern.compile(".*\\.json"));
    for (String path : paths) {
        if (path.indexOf("/optional/") > -1 || path.indexOf("/remotes/") > -1) {
            continue;
        }/*from ww w .j av a 2  s .  c  o  m*/
        String fileName = path.substring(path.lastIndexOf('/') + 1);
        JSONArray arr = loadTests(IntegrationTest.class.getResourceAsStream("/" + path));
        for (int i = 0; i < arr.length(); ++i) {
            JSONObject schemaTest = arr.getJSONObject(i);
            JSONArray testcaseInputs = schemaTest.getJSONArray("tests");
            for (int j = 0; j < testcaseInputs.length(); ++j) {
                JSONObject input = testcaseInputs.getJSONObject(j);
                Object[] params = new Object[5];
                params[0] = "[" + fileName + "]/" + schemaTest.getString("description");
                params[1] = schemaTest.get("schema");
                params[2] = "[" + fileName + "]/" + input.getString("description");
                params[3] = input.get("data");
                params[4] = input.getBoolean("valid");
                rval.add(params);
            }
        }
    }
    return rval;
}

From source file:net.mandaria.radioreddit.apis.RedditAPI.java

public static RedditAccount login(Context context, String username, String password) {
    RedditAccount account = new RedditAccount();

    try {/*from   w  ww .  j  ava2s. c om*/
        String url = context.getString(R.string.reddit_login) + "/" + username;

        // post values
        ArrayList<NameValuePair> post_values = new ArrayList<NameValuePair>();

        BasicNameValuePair user = new BasicNameValuePair("user", username);
        post_values.add(user);

        BasicNameValuePair passwd = new BasicNameValuePair("passwd", password);
        post_values.add(passwd);

        BasicNameValuePair api_type = new BasicNameValuePair("api_type", "json");
        post_values.add(api_type);

        String outputLogin = HTTPUtil.post(context, url, post_values);

        JSONTokener reddit_login_tokener = new JSONTokener(outputLogin);
        JSONObject reddit_login_json = new JSONObject(reddit_login_tokener);

        JSONObject json = reddit_login_json.getJSONObject("json");

        if (json.getJSONArray("errors").length() > 0) {
            String error = json.getJSONArray("errors").getJSONArray(0).getString(1);

            account.ErrorMessage = error;
        } else {
            JSONObject data = json.getJSONObject("data");

            // success!
            String cookie = data.getString("cookie");
            String modhash = data.getString("modhash");

            account.Username = username;
            account.Cookie = cookie;
            account.Modhash = modhash;
            account.ErrorMessage = "";
        }
    } catch (Exception ex) {
        // We fail to get the streams...
        CustomExceptionHandler ceh = new CustomExceptionHandler(context);
        ceh.sendEmail(ex);

        ex.printStackTrace();

        account.ErrorMessage = ex.toString();
    }

    return account;
}

From source file:net.mandaria.radioreddit.apis.RedditAPI.java

public static String updateModHash(Context context) {
    // Calls me.json to get the current modhash for the user
    String output = "";
    boolean errorGettingModHash = false;

    try {//  w w  w. j av a2  s  . com
        try {
            output = HTTPUtil.get(context, context.getString(R.string.reddit_me));
        } catch (Exception ex) {
            ex.printStackTrace();
            errorGettingModHash = true;
            // For now, not used. It is acceptable to error out and not alert the user
            // radiosong.ErrorMessage = "Unable to connect to reddit";//context.getString(R.string.error_RadioRedditServerIsDownNotification);
        }

        if (!errorGettingModHash && output.length() > 0) {
            JSONTokener reddit_me_tokener = new JSONTokener(output);
            JSONObject reddit_me_json = new JSONObject(reddit_me_tokener);

            JSONObject data = reddit_me_json.getJSONObject("data");

            String modhash = data.getString("modhash");

            return modhash;
        } else {
            return null;
        }
    } catch (Exception ex) {
        //         CustomExceptionHandler ceh = new CustomExceptionHandler(context);
        //         ceh.sendEmail(ex);

        ex.printStackTrace();

        return null;
    }
}

From source file:io.github.runassudo.launchert.InstallShortcutReceiver.java

public static void removeFromInstallQueue(SharedPreferences sharedPrefs, ArrayList<String> packageNames) {
    if (packageNames.isEmpty()) {
        return;/* w  w  w.  j  ava  2  s  . c om*/
    }
    synchronized (sLock) {
        Set<String> strings = sharedPrefs.getStringSet(APPS_PENDING_INSTALL, null);
        if (DBG) {
            Log.d(TAG, "APPS_PENDING_INSTALL: " + strings + ", removing packages: " + packageNames);
        }
        if (strings != null) {
            Set<String> newStrings = new HashSet<String>(strings);
            Iterator<String> newStringsIter = newStrings.iterator();
            while (newStringsIter.hasNext()) {
                String json = newStringsIter.next();
                try {
                    JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
                    Intent launchIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);
                    String pn = launchIntent.getPackage();
                    if (pn == null) {
                        pn = launchIntent.getComponent().getPackageName();
                    }
                    if (packageNames.contains(pn)) {
                        newStringsIter.remove();
                    }
                } catch (org.json.JSONException e) {
                    Log.d(TAG, "Exception reading shortcut to remove: " + e);
                } catch (java.net.URISyntaxException e) {
                    Log.d(TAG, "Exception reading shortcut to remove: " + e);
                }
            }
            sharedPrefs.edit().putStringSet(APPS_PENDING_INSTALL, new HashSet<String>(newStrings)).commit();
        }
    }
}

From source file:io.github.runassudo.launchert.InstallShortcutReceiver.java

private static ArrayList<PendingInstallShortcutInfo> getAndClearInstallQueue(SharedPreferences sharedPrefs) {
    synchronized (sLock) {
        Set<String> strings = sharedPrefs.getStringSet(APPS_PENDING_INSTALL, null);
        if (DBG)/*from  w w w.j a  v  a 2  s.  com*/
            Log.d(TAG, "Getting and clearing APPS_PENDING_INSTALL: " + strings);
        if (strings == null) {
            return new ArrayList<PendingInstallShortcutInfo>();
        }
        ArrayList<PendingInstallShortcutInfo> infos = new ArrayList<PendingInstallShortcutInfo>();
        for (String json : strings) {
            try {
                JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
                Intent data = Intent.parseUri(object.getString(DATA_INTENT_KEY), 0);
                Intent launchIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);
                String name = object.getString(NAME_KEY);
                String iconBase64 = object.optString(ICON_KEY);
                String iconResourceName = object.optString(ICON_RESOURCE_NAME_KEY);
                String iconResourcePackageName = object.optString(ICON_RESOURCE_PACKAGE_NAME_KEY);
                if (iconBase64 != null && !iconBase64.isEmpty()) {
                    byte[] iconArray = Base64.decode(iconBase64, Base64.DEFAULT);
                    Bitmap b = BitmapFactory.decodeByteArray(iconArray, 0, iconArray.length);
                    data.putExtra(Intent.EXTRA_SHORTCUT_ICON, b);
                } else if (iconResourceName != null && !iconResourceName.isEmpty()) {
                    Intent.ShortcutIconResource iconResource = new Intent.ShortcutIconResource();
                    iconResource.resourceName = iconResourceName;
                    iconResource.packageName = iconResourcePackageName;
                    data.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
                }
                data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent);
                PendingInstallShortcutInfo info = new PendingInstallShortcutInfo(data, name, launchIntent);
                infos.add(info);
            } catch (org.json.JSONException e) {
                Log.d(TAG, "Exception reading shortcut to add: " + e);
            } catch (java.net.URISyntaxException e) {
                Log.d(TAG, "Exception reading shortcut to add: " + e);
            }
        }
        sharedPrefs.edit().putStringSet(APPS_PENDING_INSTALL, new HashSet<String>()).commit();
        return infos;
    }
}

From source file:com.dzt.uberclone.HomeFragment.java

private void showDriverData(String json) {
    try {/* w w  w  .  j  a va2  s. c o m*/
        JSONObject jsonObject = new JSONObject(json);
        driverid = jsonObject.getString("driver_id");
        String name = jsonObject.getString("driver_name");
        String lastname = jsonObject.getString("driver_last_name");
        String vehicle = jsonObject.getString("vehicle");
        String plate = jsonObject.getString("license_plate");
        currentRideId = jsonObject.getString("rideid");

        StringBuilder sb = new StringBuilder();
        sb.append("Your driver is ");
        sb.append(name);
        sb.append(" " + lastname);
        sb.append("\n");
        sb.append(vehicle);
        sb.append(" " + plate);

        statusText.setVisibility(View.VISIBLE);
        statusText.setText(sb.toString());

        removeUbers();
        trackDriver();
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

From source file:com.dzt.uberclone.HomeFragment.java

private void handleDriverTracking(String json) {
    try {/*from ww  w. ja v a2 s .c  om*/
        JSONObject jsonObject = new JSONObject(json);
        if (jsonObject.has("fee")) {
            trackDriverBoolean = false;
            double initialLat = jsonObject.getDouble("initial_lat");
            double initialLng = jsonObject.getDouble("initial_lng");
            double finalLat = jsonObject.getDouble("final_lat");
            double finalLng = jsonObject.getDouble("final_lng");
            String distance = jsonObject.getString("distance");
            String time = jsonObject.getString("time");
            String fee = jsonObject.getString("fee");
            String finalFee = jsonObject.getString("final_fee");

            Bundle params = new Bundle();
            params.putString("originText", initialLat + "," + initialLng);
            params.putString("destinationText", finalLat + "," + finalLng);
            params.putString("timeText", time);
            params.putString("distanceText", distance);
            params.putString("feeText", fee);
            params.putString("finalFeeText", finalFee);
            params.putString("rideId", currentRideId);
            /*
                    
            StringBuilder sb = new StringBuilder();
            sb.append("You went from ");
            sb.append(initialLat);
            sb.append(",");
            sb.append(initialLng);
            sb.append(" to ");
            sb.append(finalLat);
            sb.append(",");
            sb.append(finalLng);
            sb.append(". Your time was ");
            sb.append(time);
            sb.append(" minutes and rode a distance of ");
            sb.append(distance);
            sb.append(" KM. Your fee is $");
            sb.append(fee);
            sb.append(" and your adjusted fee is $");
            sb.append(finalFee);
                    
            Log.i("ride details", sb.toString());
            Toast.makeText(getActivity(), sb.toString(), Toast.LENGTH_LONG).show();
                    
            */

            Intent intent = new Intent(getActivity(), RideDetailsActivity.class);
            intent.putExtras(params);
            startActivity(intent);
            getActivity().finish();

        } else {
            double lat = jsonObject.getDouble("latitude");
            double lng = jsonObject.getDouble("longitude");
            addAssignedUberMarker(lat, lng);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.funzio.pure2D.particles.nova.vo.MotionTrailVO.java

public static MotionTrailVO create(final JSONObject json) throws JSONException {
    if (!json.has("type")) {
        return null;
    }/*www  .ja v a2  s.c o  m*/

    final String type = json.getString("type");

    if (type.equalsIgnoreCase(SHAPE)) {
        return new MotionTrailShapeVO(json);
    } else {
        return null;
    }
}