Example usage for org.json JSONObject optString

List of usage examples for org.json JSONObject optString

Introduction

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

Prototype

public String optString(String key) 

Source Link

Document

Get an optional string associated with a key.

Usage

From source file:com.mllrsohn.videodialog.VideoDialogPlugin.java

private void playVideo(JSONObject params, final CallbackContext callbackContext) throws JSONException {

    loopVideo = params.optBoolean("loop", true);
    path = params.optString("url");

    uri = Uri.parse(path);//from   w  w w .  j  av  a  2  s  . com

    if (path.contains(ASSETS)) {
        try {
            String filepath = path.replace(ASSETS, "");
            String filename = filepath.substring(filepath.lastIndexOf("/") + 1, filepath.length());
            File fp = new File(this.cordova.getActivity().getFilesDir() + "/" + filename);

            if (!fp.exists()) {
                this.copy(filepath, filename);
            }
            uri = Uri.parse("file://" + this.cordova.getActivity().getFilesDir() + "/" + filename);
        } catch (IOException e) {
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION));
        }

    }

    // Create dialog in new thread
    cordova.getActivity().runOnUiThread(new Runnable() {
        public void run() {

            // Set Basic Dialog
            dialog = new Dialog((Context) cordova.getActivity(), android.R.style.Theme_NoTitleBar_Fullscreen);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);

            // Layout View
            RelativeLayout main = new RelativeLayout((Context) cordova.getActivity());
            main.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

            // Video View
            mVideoView = new VideoView((Context) cordova.getActivity());
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            lp.addRule(RelativeLayout.CENTER_IN_PARENT);
            mVideoView.setLayoutParams(lp);

            mVideoView.setVideoPath(uri.toString());
            mVideoView.start();
            main.addView(mVideoView);

            dialog.setContentView(main);
            dialog.getWindow().setFlags(LayoutParams.FLAG_FULLSCREEN, LayoutParams.FLAG_FULLSCREEN);
            dialog.show();

            // Close on touch
            mVideoView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "stopped"));
                    dialog.dismiss();
                    return true;
                }
            });

            // Set Looping
            mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.setLooping(loopVideo);
                }
            });

            // On Completion
            mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaplayer) {
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, "Done"));
                    dialog.dismiss();
                }
            });

        }
    });
}

From source file:com.zotoh.maedr.device.netty.RestIO.java

protected void inizWithProperties(JSONObject deviceProperties) throws Exception {
    super.inizWithProperties(deviceProperties);

    String p, h, x = trim(deviceProperties.optString("contextpath"));
    JSONArray a = deviceProperties.optJSONArray("resources");
    int len = a != null ? a.length() : 0;
    JSONObject obj;//from  w  w w  . j a va2 s  . c om
    //tstEStrArg("context-path", x);
    _context = x;
    for (int i = 0; i < len; ++i) {
        obj = a.optJSONObject(i);
        if (obj == null) {
            continue;
        }
        h = trim(obj.optString("processor"));
        p = trim(obj.optString("path"));
        //         tstEStrArg("resource-processor", h);
        tstEStrArg("resource-path", p);
        _resmap.put(p, h);
    }
}

From source file:com.chaosinmotion.securechat.server.commands.SendMessages.java

public static ReturnResult processRequest(Login.UserInfo userinfo, JSONObject requestParams)
        throws ClassNotFoundException, SQLException, IOException {
    int messageid = 0;

    JSONArray array = requestParams.optJSONArray("messages");
    int i, len = array.length();
    for (i = 0; i < len; ++i) {
        JSONObject mrecord = array.getJSONObject(i);
        String checksum = mrecord.optString("checksum");
        String message = mrecord.optString("message");
        String deviceid = mrecord.optString("deviceid");
        int destuser = mrecord.optInt("destuser");

        byte[] mdata = Base64.decode(message);

        /*/*from   w  ww.j  a v a  2 s  .com*/
         * If destuser is not provided, then this indicates that the
         * current logged in user is sending a message *to* the device's
         * owner. The 'toflag' is set, meaning the device is owned by
         * the user in userinfo, the message is being sent to the
         * destuser.
         */
        if (destuser == 0) {
            MessageQueue.getInstance().enqueue(userinfo.getUserID(), deviceid, false, mdata, checksum);
        } else {
            messageid = MessageQueue.getInstance().enqueue(destuser, deviceid, true, mdata, checksum);
        }
    }
    return new SimpleReturnResult("messageid", messageid);
}

From source file:com.rapid.actions.Rapid.java

private List<SOAElementRestriction> getRestrictions(JSONArray jsonRestrictions) throws JSONException {
    // check we have something
    if (jsonRestrictions == null) {
        return null;
    } else {//from ww  w . j  a  va 2s . c  om
        // instantiate the list we're making
        List<SOAElementRestriction> restrictions = new ArrayList<SOAElementRestriction>();
        // loop what we got
        for (int i = 0; i < jsonRestrictions.length(); i++) {
            // fetch this item
            JSONObject jsonRestriction = jsonRestrictions.getJSONObject(i);
            // get the type
            String type = jsonRestriction.getString("type").trim();
            // get the value
            String value = jsonRestriction.optString("value");

            // check the type and construct appropriate restriction            
            if ("MinOccursRestriction".equals(type))
                restrictions.add(new MinOccursRestriction(Integer.parseInt(value)));
            if ("MaxOccursRestriction".equals(type))
                restrictions.add(new MaxOccursRestriction(Integer.parseInt(value)));
            if ("MinLengthRestriction".equals(type))
                restrictions.add(new MinLengthRestriction(Integer.parseInt(value)));
            if ("MaxLengthRestriction".equals(type))
                restrictions.add(new MaxLengthRestriction(Integer.parseInt(value)));
            if ("EnumerationRestriction".equals(type))
                restrictions.add(new EnumerationRestriction(value));

        }
        return restrictions;
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.LinkObj.java

public void handleDirectMessage(Context context, Contact from, JSONObject obj) {
    String mimeType = obj.optString(MIME_TYPE);
    Uri uri = Uri.parse(obj.optString(URI));
    if (fileAvailable(mimeType, uri)) {
        Intent i = new Intent();
        i.setAction(Intent.ACTION_VIEW);
        i.addCategory(Intent.CATEGORY_DEFAULT);
        i.setType(mimeType);//from w w w.j  av a 2s . c  o m
        i.setData(uri);
        i.putExtra(Intent.EXTRA_TEXT, uri);

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, i,
                PendingIntent.FLAG_CANCEL_CURRENT);
        (new PresenceAwareNotify(context)).notify("New content from Musubi", "New Content from Musubi",
                mimeType + "  " + uri, contentIntent);
    } else {
        Log.w(TAG, "Received file, failed to handle: " + uri);
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.LinkObj.java

public void render(Context context, ViewGroup frame, Obj obj, boolean allowInteractions) {
    JSONObject content = obj.getJson();
    TextView valueTV = new TextView(context);
    String title;/*  w  w w  . j a  v a 2 s .c  om*/
    if (content.has(TITLE)) {
        title = "Link: " + content.optString(TITLE);
    } else {
        title = content.optString(URI);
    }
    valueTV.setText(title);
    valueTV.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT));
    valueTV.setGravity(Gravity.TOP | Gravity.LEFT);
    if (Linkify.addLinks(valueTV, Linkify.ALL)) {
        if (!allowInteractions)
            valueTV.setMovementMethod(null);
    }

    frame.addView(valueTV);
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.LinkObj.java

@Override
public void activate(Context context, SignedObj obj) {
    JSONObject content = obj.getJson();
    //linkify should have picked it up already but if we are in TV mode we
    //still need to activate
    Intent intent = new Intent(Intent.ACTION_VIEW);
    String text = content.optString(URI);
    //some shared links come in with two lines of text "title\nuri"
    //for example google maps does this and passes that same value as both the
    //uri and title

    //launch the first thing that looks like a link
    Matcher m = p.matcher(text);/*w  w w.j av  a  2s. co m*/
    while (m.find()) {
        Uri uri = Uri.parse(m.group());
        String scheme = uri.getScheme();

        if (scheme != null && (scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https"))) {
            String type = content.optString(MIME_TYPE);
            if (type != null && type.length() > 0) {
                intent.setDataAndType(uri, type);
            } else {
                intent.setData(uri);
            }
            if (!(context instanceof Activity)) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            try {
                context.startActivity(intent);
            } catch (ActivityNotFoundException e) {
                String msg;
                if (type != null)
                    msg = "A third party application that supports " + type + " is required.";
                else
                    msg = "A third party application that supports " + uri.getScheme() + " is required.";
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
            return;
        }
    }
}

From source file:com.hhunj.hhudata.SearchBookContentsActivity.java

private void handleSearchResults(JSONObject json) {
    try {/*from w  w w  .  ja  v  a  2 s . c om*/

        String s = json.toString();
        int count = json.getInt("number_of_results");
        headerView.setText("Found " + (count == 1 ? "1 result" : count + " results"));
        if (count > 0) {
            JSONArray results = json.getJSONArray("search_results");

            SearchBookContentsResult.setQuery(queryTextView.getText().toString());
            List<SearchBookContentsResult> items = new ArrayList<SearchBookContentsResult>(count);
            for (int x = 0; x < count; x++) {

                items.add(parseResult(results.getJSONObject(x)));

            }
            //...

            //....
            updatedb(items);

            //
            resultListView.setOnItemClickListener(new BrowseBookListener(this, items));
            //
            resultListView.setAdapter(new SearchBookContentsAdapter(this, items));

        } else //
        {

            //....
            //

            String searchable = json.optString("searchable");
            if ("false".equals(searchable)) {
                headerView.setText(R.string.msg_sbc_book_not_searchable);
            }
            resultListView.setAdapter(null);
        }

    } catch (JSONException e) {

        //....
        //...

        Log.w(TAG, "Bad JSON from book search", e);
        resultListView.setAdapter(null);
        headerView.setText(R.string.msg_sbc_failed);
    }
}

From source file:com.hhunj.hhudata.SearchBookContentsActivity.java

private SearchBookContentsResult parseResult(JSONObject json) {
    try {/*  w w  w . j  a  v a2 s.  com*/
        String pageId = json.getString("page_id");
        String pageNumber = json.getString("page_number");
        if (pageNumber.length() > 0) {
            // pageNumber = getString(R.string.msg_sbc_page) + ' ' + pageNumber;
        } else {
            // This can happen for text on the jacket, and possibly other reasons.
            //pageNumber = getString(R.string.msg_sbc_unknown_page);
            pageNumber = null;
        }

        // Remove all HTML tags and encoded characters. Ideally the server would do this.
        String snippet = json.optString("snippet_text");
        boolean valid = true;
        if (snippet.length() > 0) {
            snippet = TAG_PATTERN.matcher(snippet).replaceAll("");
            snippet = LT_ENTITY_PATTERN.matcher(snippet).replaceAll("<");
            snippet = GT_ENTITY_PATTERN.matcher(snippet).replaceAll(">");
            snippet = QUOTE_ENTITY_PATTERN.matcher(snippet).replaceAll("'");
            snippet = QUOT_ENTITY_PATTERN.matcher(snippet).replaceAll("\"");
        } else {
            snippet = '(' + getString(R.string.msg_sbc_snippet_unavailable) + ')';
            valid = false;
        }
        //new Date(+/\d+/.exec(value)[1]);

        Date date = JsonToDateTime(json.getString("rectime"));
        return new SearchBookContentsResult(pageId, pageNumber, snippet, valid, date);

    } catch (JSONException e) {

        Date date = new Date();
        // Never seen in the wild, just being complete.
        return new SearchBookContentsResult(getString(R.string.msg_sbc_no_page_returned), "", "", false, date);
    }

}

From source file:org.apache.cordova.contacts.ContactAccessorSdk5.java

/**
 * This method takes the fields required and search options in order to produce an
 * array of contacts that matches the criteria provided.
 * @param fields an array of items to be used as search criteria
 * @param options that can be applied to contact searching
 * @return an array of contacts//www .  j  av a  2 s.c o  m
 */
@Override
public JSONArray search(JSONArray fields, JSONObject options) {
    // Get the find options
    String searchTerm = "";
    int limit = Integer.MAX_VALUE;
    boolean multiple = true;

    if (options != null) {
        searchTerm = options.optString("filter");
        if (searchTerm.length() == 0) {
            searchTerm = "%";
        } else {
            searchTerm = "%" + searchTerm + "%";
        }

        try {
            multiple = options.getBoolean("multiple");
            if (!multiple) {
                limit = 1;
            }
        } catch (JSONException e) {
            // Multiple was not specified so we assume the default is true.
        }
    } else {
        searchTerm = "%";
    }

    //Log.d(LOG_TAG, "Search Term = " + searchTerm);
    //Log.d(LOG_TAG, "Field Length = " + fields.length());
    //Log.d(LOG_TAG, "Fields = " + fields.toString());

    // Loop through the fields the user provided to see what data should be returned.
    HashMap<String, Boolean> populate = buildPopulationSet(options);

    // Build the ugly where clause and where arguments for one big query.
    WhereOptions whereOptions = buildWhereClause(fields, searchTerm);

    // Get all the id's where the search term matches the fields passed in.
    Cursor idCursor = mApp.getActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI,
            new String[] { ContactsContract.Data.CONTACT_ID }, whereOptions.getWhere(),
            whereOptions.getWhereArgs(), ContactsContract.Data.CONTACT_ID + " ASC");

    // Create a set of unique ids
    Set<String> contactIds = new HashSet<String>();
    int idColumn = -1;
    while (idCursor.moveToNext()) {
        if (idColumn < 0) {
            idColumn = idCursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);
        }
        contactIds.add(idCursor.getString(idColumn));
    }
    idCursor.close();

    // Build a query that only looks at ids
    WhereOptions idOptions = buildIdClause(contactIds, searchTerm);

    // Determine which columns we should be fetching.
    HashSet<String> columnsToFetch = new HashSet<String>();
    columnsToFetch.add(ContactsContract.Data.CONTACT_ID);
    columnsToFetch.add(ContactsContract.Data.RAW_CONTACT_ID);
    columnsToFetch.add(ContactsContract.Data.MIMETYPE);

    if (isRequired("displayName", populate)) {
        columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);
    }
    if (isRequired("name", populate)) {
        columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME);
        columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
        columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME);
        columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.PREFIX);
        columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredName.SUFFIX);
    }
    if (isRequired("phoneNumbers", populate)) {
        columnsToFetch.add(ContactsContract.CommonDataKinds.Phone._ID);
        columnsToFetch.add(ContactsContract.CommonDataKinds.Phone.NUMBER);
        columnsToFetch.add(ContactsContract.CommonDataKinds.Phone.TYPE);
    }
    if (isRequired("emails", populate)) {
        columnsToFetch.add(ContactsContract.CommonDataKinds.Email._ID);
        columnsToFetch.add(ContactsContract.CommonDataKinds.Email.DATA);
        columnsToFetch.add(ContactsContract.CommonDataKinds.Email.TYPE);
    }
    if (isRequired("addresses", populate)) {
        columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal._ID);
        columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.TYPE);
        columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS);
        columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.STREET);
        columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.CITY);
        columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.REGION);
        columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE);
        columnsToFetch.add(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY);
    }
    if (isRequired("organizations", populate)) {
        columnsToFetch.add(ContactsContract.CommonDataKinds.Organization._ID);
        columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.TYPE);
        columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.DEPARTMENT);
        columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.COMPANY);
        columnsToFetch.add(ContactsContract.CommonDataKinds.Organization.TITLE);
    }
    if (isRequired("ims", populate)) {
        columnsToFetch.add(ContactsContract.CommonDataKinds.Im._ID);
        columnsToFetch.add(ContactsContract.CommonDataKinds.Im.DATA);
        columnsToFetch.add(ContactsContract.CommonDataKinds.Im.TYPE);
    }
    if (isRequired("note", populate)) {
        columnsToFetch.add(ContactsContract.CommonDataKinds.Note.NOTE);
    }
    if (isRequired("nickname", populate)) {
        columnsToFetch.add(ContactsContract.CommonDataKinds.Nickname.NAME);
    }
    if (isRequired("urls", populate)) {
        columnsToFetch.add(ContactsContract.CommonDataKinds.Website._ID);
        columnsToFetch.add(ContactsContract.CommonDataKinds.Website.URL);
        columnsToFetch.add(ContactsContract.CommonDataKinds.Website.TYPE);
    }
    if (isRequired("birthday", populate)) {
        columnsToFetch.add(ContactsContract.CommonDataKinds.Event.START_DATE);
        columnsToFetch.add(ContactsContract.CommonDataKinds.Event.TYPE);
    }
    if (isRequired("photos", populate)) {
        columnsToFetch.add(ContactsContract.CommonDataKinds.Photo._ID);
    }

    // Do the id query
    Cursor c = mApp.getActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI,
            columnsToFetch.toArray(new String[] {}), idOptions.getWhere(), idOptions.getWhereArgs(),
            ContactsContract.Data.CONTACT_ID + " ASC");

    JSONArray contacts = populateContactArray(limit, populate, c);
    return contacts;
}