Example usage for org.json JSONObject has

List of usage examples for org.json JSONObject has

Introduction

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

Prototype

public boolean has(String key) 

Source Link

Document

Determine if the JSONObject contains a specific key.

Usage

From source file:org.sleeksnap.ScreenSnapper.java

public boolean convertUploadDefinition(final JSONObject uploadConfig, final Class<?> originalClass,
        final Class<?> newClass) {
    if (uploadConfig.has(originalClass.getName())) {
        uploadConfig.put(newClass.getName(), uploadConfig.remove(originalClass.getName()));
        return true;
    }/* w w w .j a  v  a2 s .  c  o  m*/
    return false;
}

From source file:org.melato.bus.otp.OTPParser.java

static JSONObject getObject(JSONObject json, String key) throws JSONException {
    if (json.has(key) && !json.isNull(key)) {
        return json.getJSONObject(key);
    }//  ww  w.j  a va 2 s. c o m
    return null;
}

From source file:de.damdi.fitness.db.parser.ExerciseTagJSONParser.java

/**
 * Parses the JSON-String to a list of {@link ExerciseTag}s.
 * /*from w  w  w.j a v a  2s .c  o  m*/
  *   
  * @param jsonString The String to parse.
  * 
  * @return A list of {@link ExerciseTag}s, null if an error occurs.
  * 
 */
@Override
public List<ExerciseTag> parse(String jsonString) {
    List<ExerciseTag> exerciseTagList = new ArrayList<ExerciseTag>();

    JSONArray jsonArray;
    try {
        jsonArray = new JSONArray(jsonString);

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject SportsEquipmentObject = jsonArray.getJSONObject(i);

            ExerciseTag exerciseTag = null;

            for (String locale : TAG_LOCALES) {
                if (SportsEquipmentObject.has(locale)) {
                    JSONObject languageObject = SportsEquipmentObject.getJSONObject(locale);

                    // name
                    String name = languageObject.getString(TAG_NAME);
                    List<String> nameList = new ArrayList<String>();
                    nameList.add(name);

                    String description = null;

                    // description   
                    if (languageObject.has(TAG_DESCRIPTION)) {
                        //JSONObject descriptionJSONObject = languageObject.getJSONObject(TAG_DESCRIPTION);

                        // description
                        description = languageObject.getString(TAG_DESCRIPTION);

                    }

                    if (exerciseTag == null) {
                        exerciseTag = new ExerciseTag(new Locale(locale), nameList, description);
                    } else {
                        exerciseTag.addNames(new Locale(locale), nameList, description);
                    }
                }
            }

            // Log.d(TAG, "Finished parsing ExerciseTag: \n" + exerciseTag.toDebugString());
            exerciseTagList.add(exerciseTag);

        }

    } catch (JSONException e) {
        Log.e(TAG, "Error during parsing JSON File.", e);
        return null;
    }

    if (exerciseTagList.isEmpty())
        throw new AssertionError("JSON parsing failed: no ExerciseTag parsed.");
    return exerciseTagList;
}

From source file:com.piusvelte.sonet.StatusDialog.java

@Override
public void onClick(final DialogInterface dialog, int which) {
    switch (which) {
    case COMMENT:
        if (mAppWidgetId != -1) {
            if (mService == GOOGLEPLUS)
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://plus.google.com")));
            else if (mService == PINTEREST) {
                if (mSid != null)
                    startActivity(new Intent(Intent.ACTION_VIEW)
                            .setData(Uri.parse(String.format(PINTEREST_PIN, mSid))));
                else
                    startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://pinterest.com")));
            } else
                startActivity(Sonet.getPackageIntent(this, SonetComments.class).setData(mData));
        } else//  ww  w.  j av a2  s .co m
            (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
        dialog.cancel();
        finish();
        break;
    case POST:
        if (mAppWidgetId != -1) {
            if (mService == GOOGLEPLUS)
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://plus.google.com")));
            else if (mService == PINTEREST)
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://pinterest.com")));
            else
                startActivity(Sonet.getPackageIntent(this, SonetCreatePost.class).setData(Uri
                        .withAppendedPath(Accounts.getContentUri(StatusDialog.this), Long.toString(mAccount))));
            dialog.cancel();
            finish();
        } else {
            // no widget sent in, dialog to select one
            String[] widgets = getAllWidgets();
            if (widgets.length > 0) {
                mDialog = (new AlertDialog.Builder(this)).setItems(widgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        // no account, dialog to select one
                        // don't limit accounts to the widget
                        Cursor c = StatusDialog.this.getContentResolver().query(
                                Accounts.getContentUri(StatusDialog.this),
                                new String[] { Accounts._ID, ACCOUNTS_QUERY }, null, null, null);
                        if (c.moveToFirst()) {
                            int iid = c.getColumnIndex(Accounts._ID),
                                    iusername = c.getColumnIndex(Accounts.USERNAME), i = 0;
                            final long[] accountIndexes = new long[c.getCount()];
                            final String[] accounts = new String[c.getCount()];
                            while (!c.isAfterLast()) {
                                long id = c.getLong(iid);
                                accountIndexes[i] = id;
                                accounts[i++] = c.getString(iusername);
                                c.moveToNext();
                            }
                            arg0.cancel();
                            mDialog = (new AlertDialog.Builder(StatusDialog.this)).setTitle(R.string.accounts)
                                    .setSingleChoiceItems(accounts, -1, new OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface arg0, int which) {
                                            startActivity(Sonet
                                                    .getPackageIntent(StatusDialog.this, SonetCreatePost.class)
                                                    .setData(Uri.withAppendedPath(
                                                            Accounts.getContentUri(StatusDialog.this),
                                                            Long.toString(accountIndexes[which]))));
                                            arg0.cancel();
                                        }
                                    }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                                        @Override
                                        public void onCancel(DialogInterface arg0) {
                                            dialog.cancel();
                                        }
                                    }).create();
                            mDialog.show();
                        } else {
                            (Toast.makeText(StatusDialog.this, getString(R.string.error_status),
                                    Toast.LENGTH_LONG)).show();
                            dialog.cancel();
                        }
                        c.close();
                        finish();
                    }
                }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface arg0) {
                        dialog.cancel();
                        finish();
                    }
                }).create();
                mDialog.show();
            } else {
                (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
                dialog.cancel();
                finish();
            }
        }
        break;
    case SETTINGS:
        if (mAppWidgetId != -1) {
            startActivity(Sonet.getPackageIntent(this, ManageAccounts.class)
                    .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId));
            dialog.cancel();
            finish();
        } else {
            // no widget sent in, dialog to select one
            String[] widgets = getAllWidgets();
            if (widgets.length > 0) {
                mDialog = (new AlertDialog.Builder(this)).setItems(widgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        startActivity(Sonet.getPackageIntent(StatusDialog.this, ManageAccounts.class)
                                .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetIds[arg1]));
                        arg0.cancel();
                        finish();
                    }
                }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface arg0) {
                        dialog.cancel();
                        finish();
                    }
                }).create();
                mDialog.show();
            } else {
                (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
                dialog.cancel();
                finish();
            }
        }
        break;
    case NOTIFICATIONS:
        startActivity(Sonet.getPackageIntent(this, SonetNotifications.class));
        dialog.cancel();
        finish();
        break;
    case REFRESH:
        if (mAppWidgetId != -1) {
            (Toast.makeText(getApplicationContext(), getString(R.string.refreshing), Toast.LENGTH_LONG)).show();
            startService(Sonet.getPackageIntent(this, SonetService.class).setAction(ACTION_REFRESH)
                    .putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { mAppWidgetId }));
            dialog.cancel();
        } else {
            // no widget sent in, dialog to select one
            String[] widgets = getAllWidgets();
            if (widgets.length > 0) {
                mDialog = (new AlertDialog.Builder(this)).setItems(widgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        (Toast.makeText(StatusDialog.this.getApplicationContext(),
                                getString(R.string.refreshing), Toast.LENGTH_LONG)).show();
                        startService(Sonet.getPackageIntent(StatusDialog.this, SonetService.class)
                                .setAction(ACTION_REFRESH).putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
                                        new int[] { mAppWidgetIds[arg1] }));
                        arg0.cancel();
                        finish();
                    }
                }).setPositiveButton(R.string.refreshallwidgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int which) {
                        // refresh all
                        (Toast.makeText(StatusDialog.this.getApplicationContext(),
                                getString(R.string.refreshing), Toast.LENGTH_LONG)).show();
                        startService(Sonet.getPackageIntent(StatusDialog.this, SonetService.class)
                                .putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, mAppWidgetIds));
                        arg0.cancel();
                        finish();
                    }
                }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface arg0) {
                        dialog.cancel();
                        finish();
                    }
                }).create();
                mDialog.show();
            } else {
                dialog.cancel();
                finish();
            }
        }
        break;
    case PROFILE:
        Cursor account;
        final AsyncTask<String, Void, String> asyncTask;
        // get the resources
        switch (mService) {
        case TWITTER:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY,
                                BuildConfig.TWITTER_SECRET, arg0[0], arg0[1]);
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                sonetOAuth.getSignedRequest(
                                        new HttpGet(String.format(TWITTER_USER, TWITTER_BASE_URL, mEsid))));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                JSONObject user = new JSONObject(response);
                                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri
                                        .parse(String.format(TWITTER_PROFILE, user.getString("screen_name")))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                loadingDialog.setMessage(getString(R.string.loading));
                loadingDialog.setCancelable(true);
                loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!asyncTask.isCancelled())
                            asyncTask.cancel(true);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case FACEBOOK:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                new HttpGet(String.format(FACEBOOK_USER, FACEBOOK_BASE_URL, mEsid,
                                        Saccess_token, arg0[0])));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW)
                                        .setData(Uri.parse((new JSONObject(response)).getString("link"))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                loadingDialog.setMessage(getString(R.string.loading));
                loadingDialog.setCancelable(true);
                loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!asyncTask.isCancelled())
                            asyncTask.cancel(true);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))));
            }
            account.close();
            break;
        case MYSPACE:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.MYSPACE_KEY,
                                BuildConfig.MYSPACE_SECRET, arg0[0], arg0[1]);
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                sonetOAuth.getSignedRequest(
                                        new HttpGet(String.format(MYSPACE_USER, MYSPACE_BASE_URL, mEsid))));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW)
                                        .setData(Uri.parse((new JSONObject(response)).getJSONObject("person")
                                                .getString("profileUrl"))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                loadingDialog.setMessage(getString(R.string.loading));
                loadingDialog.setCancelable(true);
                loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!asyncTask.isCancelled())
                            asyncTask.cancel(true);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case FOURSQUARE:
            startActivity(new Intent(Intent.ACTION_VIEW)
                    .setData(Uri.parse(String.format(FOURSQUARE_URL_PROFILE, mEsid))));
            finish();
            break;
        case LINKEDIN:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY,
                                BuildConfig.LINKEDIN_SECRET, arg0[0], arg0[1]);
                        HttpGet httpGet = new HttpGet(String.format(LINKEDIN_URL_USER, mEsid));
                        for (String[] header : LINKEDIN_HEADERS)
                            httpGet.setHeader(header[0], header[1]);
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                sonetOAuth.getSignedRequest(httpGet));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(
                                        (new JSONObject(response)).getJSONObject("siteStandardProfileRequest")
                                                .getString("url").replaceAll("\\\\", ""))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                loadingDialog.setMessage(getString(R.string.loading));
                loadingDialog.setCancelable(true);
                loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!asyncTask.isCancelled())
                            asyncTask.cancel(true);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case IDENTICA:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY,
                                BuildConfig.IDENTICA_SECRET, arg0[0], arg0[1]);
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                sonetOAuth.getSignedRequest(
                                        new HttpGet(String.format(IDENTICA_USER, IDENTICA_BASE_URL, mEsid))));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                JSONObject user = new JSONObject(response);
                                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(
                                        String.format(IDENTICA_PROFILE, user.getString("screen_name")))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                loadingDialog.setMessage(getString(R.string.loading));
                loadingDialog.setCancelable(true);
                loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!asyncTask.isCancelled())
                            asyncTask.cancel(true);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case GOOGLEPLUS:
            startActivity(new Intent(Intent.ACTION_VIEW)
                    .setData(Uri.parse(String.format(GOOGLEPLUS_PROFILE, mEsid))));
            finish();
            break;
        case PINTEREST:
            if (mEsid != null)
                startActivity(new Intent(Intent.ACTION_VIEW)
                        .setData(Uri.parse(String.format(PINTEREST_PROFILE, mEsid))));
            else
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://pinterest.com")));
            finish();
            break;
        case CHATTER:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        // need to get an instance
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()), new HttpPost(
                                        String.format(CHATTER_URL_ACCESS, BuildConfig.CHATTER_KEY, arg0[0])));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                JSONObject jobj = new JSONObject(response);
                                if (jobj.has("instance_url")) {
                                    startActivity(new Intent(Intent.ACTION_VIEW)
                                            .setData(Uri.parse(jobj.getString("instance_url") + "/" + mEsid)));
                                }
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                loadingDialog.setMessage(getString(R.string.loading));
                loadingDialog.setCancelable(true);
                loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!asyncTask.isCancelled())
                            asyncTask.cancel(true);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))));
            }
            account.close();
            break;
        }
        break;
    default:
        if ((itemsData != null) && (which < itemsData.length) && (itemsData[which] != null))
            // open link
            startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(itemsData[which])));
        else
            (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
        finish();
        break;
    }
}

From source file:net.freifunk.android.discover.model.Community.java

public void populate(final RequestQueue rq, final CommunityReady communityReady) {

    rq.add(new JsonObjectRequest(getDetailUrl(), null, new Response.Listener<JSONObject>() {
        @Override/*  w w w  .  j  av  a 2s.  c  om*/
        public void onResponse(JSONObject jsonObject) {
            try {
                setApiName(jsonObject.getString("name"));
                setApi(jsonObject.getString("api"));
                if (jsonObject.has("metacommunity"))
                    setMetacommunity(jsonObject.getString("metacommunity"));

                JSONObject location = jsonObject.getJSONObject("location");
                setAddressCity(location.getString("city"));
                if (location.has("address")) {
                    JSONObject address = jsonObject.getJSONObject("address");
                    if (address.has("Name"))
                        setAddressName(address.getString("Name"));

                    if (address.has("Street"))
                        setAddressStreet(address.getString("Street"));

                    if (address.has("Zipcode"))
                        setAddressZipcode(address.getString("Zipcode"));
                }
                setLat(location.getDouble("lat"));
                setLon(location.getDouble("lon"));
                setUrl(jsonObject.getString("url"));
                Log.d(TAG, getCommunity().toString());
                communityReady.ready(getCommunity());
            } catch (JSONException e) {
                Log.e(TAG, e.toString());
            }

        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            Log.e(TAG, volleyError.toString());
        }
    }));
}

From source file:com.whizzosoftware.hobson.dto.property.PropertyContainerDTO.java

private PropertyContainerDTO(JSONObject json) {
    if (json.has(JSONAttributes.CCLASS)) {
        containerClass = new PropertyContainerClassDTO.Builder(json.getJSONObject(JSONAttributes.CCLASS))
                .build();/* w  ww. j a v  a 2s .c  om*/
    }
    if (json.has(JSONAttributes.VALUES)) {
        values = new HashMap<>();
        JSONObject jp = json.getJSONObject(JSONAttributes.VALUES);
        for (Object o : jp.keySet()) {
            String key = o.toString();
            Object v = jp.get(key);
            if (JSONObject.NULL.equals(v)) {
                values.put(key, null);
            } else if (v instanceof Serializable || v instanceof JSONArray || v instanceof JSONObject) {
                values.put(key, v);
            } else {
                throw new HobsonRuntimeException("Invalid property value for " + key + ": " + v);
            }
        }
    }
}

From source file:com.google.android.apps.body.LayersLoader.java

/** Synchronously loads a single layer. */
private Render.DrawGroup[] load(Context context, int layerResource) {
    // TODO(thakis): this method is kinda ugly.
    // TODO(thakis): if we can bundle the resource files, rewrite them so that no conversion
    //               needs to happen at load time. The utf8 stuff is clever, but mostly overhead
    //               for local files.

    // Timers for different loading phases.
    float jsonReadS = 0;
    float jsonParseS = 0;
    float textureS = 0;
    float fileReadS = 0;
    float fileDecodeS = 0;
    float colorBufferS = 0;

    Render.DrawGroup[] drawGroups = null;

    long jsonReadStartNS = System.nanoTime();
    JSONObject object = loadJsonResource(context, layerResource);
    jsonReadS = (System.nanoTime() - jsonReadStartNS) / 1e9f;

    long jsonParseStartNS = System.nanoTime();
    Map<Integer, List<Loader>> toBeLoaded = new HashMap<Integer, List<Loader>>();
    try {/*from w  w w  .  j  a v  a2 s  .  com*/
        JSONArray dataDrawGroups = object.getJSONArray("draw_groups");
        drawGroups = new Render.DrawGroup[dataDrawGroups.length()];
        for (int i = 0; i < drawGroups.length; ++i) {
            if (mCancelled)
                return null;

            JSONObject drawGroup = dataDrawGroups.getJSONObject(i);
            drawGroups[i] = new Render.DrawGroup();
            if (drawGroup.has("texture"))
                drawGroups[i].texture = drawGroup.getString("texture");
            else if (drawGroup.has("diffuse_color")) {
                JSONArray color = drawGroup.getJSONArray("diffuse_color");
                drawGroups[i].diffuseColor = new float[3];
                for (int j = 0; j < 3; ++j)
                    drawGroups[i].diffuseColor[j] = (float) color.getDouble(j);
            }
            JSONArray draws = drawGroup.getJSONArray("draws");
            drawGroups[i].draws = new ArrayList<Render.Draw>(draws.length());
            for (int j = 0; j < draws.length(); ++j) {
                JSONObject jsonDraw = draws.getJSONObject(j);
                Render.Draw draw = new Render.Draw();
                draw.geometry = jsonDraw.getString("geometry");
                draw.offset = jsonDraw.getJSONArray("range").getInt(0);
                draw.count = jsonDraw.getJSONArray("range").getInt(1);
                drawGroups[i].draws.add(draw);
            }
            long textureReadStartNS = System.nanoTime();
            loadTexture(mContext, drawGroups[i]);
            textureS += (System.nanoTime() - textureReadStartNS) / 1e9f;

            String indices = drawGroup.getString("indices");
            FP.FPEntry indicesFP = FP.get(indices);
            if (toBeLoaded.get(indicesFP.file) == null)
                toBeLoaded.put(indicesFP.file, new ArrayList<Loader>());
            toBeLoaded.get(indicesFP.file).add(new IndexLoader(drawGroups[i], indicesFP));

            String attribs = drawGroup.getString("attribs");
            FP.FPEntry attribsFP = FP.get(attribs);
            if (toBeLoaded.get(attribsFP.file) == null)
                toBeLoaded.put(attribsFP.file, new ArrayList<Loader>());
            toBeLoaded.get(attribsFP.file).add(new AttribLoader(drawGroups[i], attribsFP));

            drawGroups[i].numIndices = drawGroup.getInt("numIndices");
        }
    } catch (JSONException e) {
        Log.e("Body", e.toString());
    }
    jsonParseS = (System.nanoTime() - jsonParseStartNS) / 1e9f - textureS;

    for (int resource : toBeLoaded.keySet()) {
        if (mCancelled)
            return null;

        long fileReadStartNS = System.nanoTime();
        char[] data = new char[0];
        InputStream is = mContext.getResources().openRawResource(resource);
        try {
            // Comment from the ApiDemo content/ReadAsset.java in the Android SDK:
            // "We guarantee that the available method returns the total
            //  size of the asset...  of course, this does mean that a single
            //  asset can't be more than 2 gigs."
            data = new char[is.available()];
            Reader in = new InputStreamReader(is, "UTF-8");
            in.read(data, 0, data.length);
        } catch (UnsupportedEncodingException e) {
            Log.e("Body", e.toString());
        } catch (IOException e) {
            Log.e("Body", e.toString());
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                Log.e("Body", e.toString());
            }
        }
        fileReadS += (System.nanoTime() - fileReadStartNS) / 1.0e9f;
        long fileDecodeStartNS = System.nanoTime();
        for (Loader l : toBeLoaded.get(resource)) {
            if (mCancelled)
                return null;

            l.load(data);
        }
        fileDecodeS += (System.nanoTime() - fileDecodeStartNS) / 1.0e9f;
    }

    long colorBufferStartNS = System.nanoTime();
    for (Render.DrawGroup drawGroup : drawGroups) {
        if (mCancelled)
            return null;
        createColorBuffer(drawGroup);
    }
    colorBufferS = (System.nanoTime() - colorBufferStartNS) / 1e9f;

    Log.i("Body", "JSON read: " + jsonReadS + ", JSON parse: " + jsonParseS + ", texture: " + textureS
            + ", res read: " + fileReadS + ", res decode: " + fileDecodeS + ", colorbuf: " + colorBufferS);

    return drawGroups;
}

From source file:weathernotificationservice.wns.activities.MainActivity.java

private ParseResult parseTodayJson(String result) {
    try {//from w  w  w  . j ava  2s. c o m
        JSONObject reader = new JSONObject(result);

        final String code = reader.optString("cod");
        if ("404".equals(code)) {
            return ParseResult.CITY_NOT_FOUND;
        }

        String city = reader.getString("name");
        String country = "";
        JSONObject countryObj = reader.optJSONObject("sys");
        if (countryObj != null) {
            country = countryObj.getString("country");
            todayWeather.setSunrise(countryObj.getString("sunrise"));
            todayWeather.setSunset(countryObj.getString("sunset"));
        }
        todayWeather.setCity(city);
        todayWeather.setCountry(country);

        JSONObject coordinates = reader.getJSONObject("coord");
        if (coordinates != null) {
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
            sp.edit().putFloat("latitude", (float) coordinates.getDouble("lon"))
                    .putFloat("longitude", (float) coordinates.getDouble("lat")).commit();
        }

        JSONObject main = reader.getJSONObject("main");

        todayWeather.setTemperature(main.getString("temp"));
        todayWeather.setDescription(reader.getJSONArray("weather").getJSONObject(0).getString("description"));
        JSONObject windObj = reader.getJSONObject("wind");
        todayWeather.setWind(windObj.getString("speed"));
        if (windObj.has("deg")) {
            todayWeather.setWindDirectionDegree(windObj.getDouble("deg"));
        } else {
            Log.e("parseTodayJson", "No wind direction available");
            todayWeather.setWindDirectionDegree(null);
        }
        todayWeather.setPressure(main.getString("pressure"));
        todayWeather.setHumidity(main.getString("humidity"));

        JSONObject rainObj = reader.optJSONObject("rain");
        String rain;
        if (rainObj != null) {
            rain = getRainString(rainObj);
        } else {
            JSONObject snowObj = reader.optJSONObject("snow");
            if (snowObj != null) {
                rain = getRainString(snowObj);
            } else {
                rain = "0";
            }
        }
        todayWeather.setRain(rain);

        final String idString = reader.getJSONArray("weather").getJSONObject(0).getString("id");
        todayWeather.setId(idString);
        todayWeather.setIcon(
                setWeatherIcon(Integer.parseInt(idString), Calendar.getInstance().get(Calendar.HOUR_OF_DAY)));

        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this)
                .edit();
        editor.putString("lastToday", result);
        editor.commit();

    } catch (JSONException e) {
        Log.e("JSONException Data", result);
        e.printStackTrace();
        return ParseResult.JSON_EXCEPTION;
    }

    return ParseResult.OK;
}

From source file:com.microsoft.speech.tts.OxfordAuthentication.java

private void HttpPost(String AccessTokenUri, String requestDetails) {
    InputStream inSt = null;/*from   w w  w  .  j a  v  a  2s . c o  m*/
    HttpsURLConnection webRequest = null;

    this.token = null;
    //Prepare OAuth request
    try {
        URL url = new URL(AccessTokenUri);
        webRequest = (HttpsURLConnection) url.openConnection();
        webRequest.setDoInput(true);
        webRequest.setDoOutput(true);
        webRequest.setConnectTimeout(5000);
        webRequest.setReadTimeout(5000);
        webRequest.setRequestProperty("content-type", "application/x-www-form-urlencoded");
        webRequest.setRequestMethod("POST");

        byte[] bytes = requestDetails.getBytes();
        webRequest.setRequestProperty("content-length", String.valueOf(bytes.length));
        webRequest.connect();

        DataOutputStream dop = new DataOutputStream(webRequest.getOutputStream());
        dop.write(bytes);
        dop.flush();
        dop.close();

        inSt = webRequest.getInputStream();
        InputStreamReader in = new InputStreamReader(inSt);
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }

        bufferedReader.close();
        in.close();
        inSt.close();
        webRequest.disconnect();

        // parse the access token from the json format
        String result = strBuffer.toString();
        JSONObject jsonRoot = new JSONObject(result);
        this.token = new OxfordAccessToken();

        if (jsonRoot.has("access_token")) {
            this.token.access_token = jsonRoot.getString("access_token");
        }

        if (jsonRoot.has("token_type")) {
            this.token.token_type = jsonRoot.getString("token_type");
        }

        if (jsonRoot.has("expires_in")) {
            this.token.expires_in = jsonRoot.getString("expires_in");
        }

        if (jsonRoot.has("scope")) {
            this.token.scope = jsonRoot.getString("scope");
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception error", e);
    }
}

From source file:org.openhab.habdroid.model.OpenHABItem.java

public OpenHABItem(JSONObject jsonObject) {
    try {//from w w w. ja v a  2 s.com
        if (jsonObject.has("type"))
            this.setType(jsonObject.getString("type"));
        if (jsonObject.has("groupType"))
            this.setGroupType(jsonObject.getString("groupType"));
        if (jsonObject.has("name"))
            this.setName(jsonObject.getString("name"));
        if (jsonObject.has("state")) {
            if (jsonObject.getString("state").equals("NULL") || jsonObject.getString("state").equals("UNDEF")
                    || jsonObject.getString("state").equalsIgnoreCase("undefined")) {
                this.setState(null);
            } else {
                this.setState(jsonObject.getString("state"));
            }
        }
        if (jsonObject.has("link"))
            this.setLink(jsonObject.getString("link"));
    } catch (JSONException e) {
        e.printStackTrace();
    }
}