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.asd.littleprincesbeauty.data.TaskList.java

@Override
public void setContentByLocalJSON(JSONObject js) {
    if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
        Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
    }/*from w  ww . ja va2  s . co  m*/

    try {
        JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);

        if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
            String name = folder.getString(NoteColumns.SNIPPET);
            setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
        } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
            if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
                setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
            else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
                setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE);
            else
                Log.e(TAG, "invalid system folder");
        } else {
            Log.e(TAG, "error type");
        }
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }
}

From source file:cc.redpen.server.api.RedPenConfigurationResourceTest.java

@Test
public void versionIsReturned() throws Exception {
    JSONObject response = (JSONObject) resource.getRedPens("").getEntity();
    assertEquals(RedPen.VERSION, response.getString("version"));
}

From source file:cc.redpen.server.api.RedPenConfigurationResourceTest.java

@Test
public void redPenFields() throws Exception {
    JSONObject response = (JSONObject) resource.getRedPens(null).getEntity();
    JSONObject redpens = response.getJSONObject("redpens");

    JSONObject ja = redpens.getJSONObject("ja");
    assertEquals("ja", ja.getString("lang"));
    assertEquals("zenkaku", ja.getString("variant"));
    assertEquals(JapaneseTokenizer.class.getName(), ja.getString("tokenizer"));
    assertTrue(!ja.getString("validators").isEmpty());
    assertTrue(!ja.getString("symbols").isEmpty());
}

From source file:com.etalio.android.EtalioBase.java

private void parseEtalioTokenError(EtalioHttpException e) throws EtalioTokenException {
    try {//from  ww  w . j a  v a 2 s . c  om
        String message = e.getMessage();
        JSONObject json = new JSONObject(message);
        throw new EtalioTokenException(json.getString("error"));
    } catch (JSONException ej) {
        throw new EtalioTokenException(EtalioTokenException.TokensErrorResponse.INVALID_REQUEST);
    }
}

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

private SearchBookContentsResult parseResult(JSONObject json) {
    try {/*from w  ww.j ava  2  s.  c  o  m*/
        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"));
        if (date == null)
            return null;

        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:widgets.Graphical_Info.java

@SuppressLint("HandlerLeak")
public Graphical_Info(tracerengine Trac, Activity context, int id, int dev_id, String name,
        final String state_key, String url, final String usage, int update, int widgetSize, int session_type,
        final String parameters, int place_id, String place_type, SharedPreferences params) {
    super(context, Trac, id, name, "", usage, widgetSize, session_type, place_id, place_type, mytag, container);
    this.Tracer = Trac;
    this.context = context;
    this.dev_id = dev_id;
    this.id = id;
    this.usage = usage;
    this.state_key = state_key;
    this.update = update;
    this.wname = name;
    this.url = url;
    this.myself = this;
    this.session_type = session_type;
    this.parameters = parameters;
    this.place_id = place_id;
    this.place_type = place_type;
    this.params = params;
    setOnClickListener(this);

    mytag = "Graphical_Info (" + dev_id + ")";
    metrics = getResources().getDisplayMetrics();
    //Label Text size according to the screen size
    size10 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, metrics);
    size5 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, metrics);

    Tracer.e(mytag, "New instance for name = " + wname + " state_key = " + state_key);
    login = params.getString("http_auth_username", null);
    password = params.getString("http_auth_password", null);

    //state key//from   w w  w .  ja  v a 2s  .c om
    state_key_view = new TextView(context);
    state_key_view.setText(state_key);
    state_key_view.setTextColor(Color.parseColor("#333333"));

    //value
    value = new TextView(context);
    value.setTextSize(28);
    value.setTextColor(Color.BLACK);
    animation = new AlphaAnimation(0.0f, 1.0f);
    animation.setDuration(1000);

    if (with_graph) {

        //feature panel 2 which will contain graphic
        featurePan2 = new LinearLayout(context);
        featurePan2.setLayoutParams(
                new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        featurePan2.setGravity(Gravity.CENTER_VERTICAL);
        featurePan2.setPadding(5, 10, 5, 10);
        //canvas
        canvas = new Graphical_Info_View(Tracer, context, params);
        canvas.dev_id = dev_id;
        canvas.state_key = state_key;
        canvas.url = url;
        canvas.update = update;

        LayoutInflater layoutInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        featurePan2_buttons = layoutInflater.inflate(R.layout.graph_buttons, null);
        View v = null;

        v = featurePan2_buttons.findViewById(R.id.bt_prev);
        if (v != null)
            v.setOnClickListener(canvas);

        v = featurePan2_buttons.findViewById(R.id.bt_next);
        if (v != null)
            v.setOnClickListener(canvas);

        v = featurePan2_buttons.findViewById(R.id.bt_year);
        if (v != null)
            v.setOnClickListener(canvas);

        v = featurePan2_buttons.findViewById(R.id.bt_month);
        if (v != null)
            v.setOnClickListener(canvas);

        v = featurePan2_buttons.findViewById(R.id.bt_week);
        if (v != null)
            v.setOnClickListener(canvas);

        v = featurePan2_buttons.findViewById(R.id.bt_day);
        if (v != null)
            v.setOnClickListener(canvas);

        v = featurePan2_buttons.findViewById(R.id.period);
        if (v != null)
            canvas.dates = (TextView) v;

        //background_stats.addView(canvas);
        featurePan2.addView(canvas);
    }

    LL_featurePan.addView(value);
    LL_infoPan.addView(state_key_view);

    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 9999) {
                //Message from widgetupdate
                //state_engine send us a signal to notify value changed
                if (session == null)
                    return;

                String loc_Value = session.getValue();
                Tracer.d(mytag, "Handler receives a new value <" + loc_Value + ">");
                try {
                    float formatedValue = 0;
                    if (loc_Value != null)
                        formatedValue = Round(Float.parseFloat(loc_Value), 2);
                    try {
                        //Basilic add, number feature has a unit parameter
                        JSONObject jparam = new JSONObject(parameters.replaceAll("&quot;", "\""));
                        String test_unite = jparam.getString("unit");
                        value.setText(formatedValue + " " + test_unite);
                    } catch (JSONException e) {
                        if (state_key.equalsIgnoreCase("temperature") == true)
                            value.setText(formatedValue + " C");
                        else if (state_key.equalsIgnoreCase("pressure") == true)
                            value.setText(formatedValue + " hPa");
                        else if (state_key.equalsIgnoreCase("humidity") == true)
                            value.setText(formatedValue + " %");
                        else if (state_key.equalsIgnoreCase("percent") == true)
                            value.setText(formatedValue + " %");
                        else if (state_key.equalsIgnoreCase("visibility") == true)
                            value.setText(formatedValue + " km");
                        else if (state_key.equalsIgnoreCase("chill") == true)
                            value.setText(formatedValue + " C");
                        else if (state_key.equalsIgnoreCase("speed") == true)
                            value.setText(formatedValue + " km/h");
                        else if (state_key.equalsIgnoreCase("drewpoint") == true)
                            value.setText(formatedValue + " C");
                        else if (state_key.equalsIgnoreCase("condition-code") == true)
                            //Add try catch to avoid other case that make #1794
                            try {
                                value.setText(Graphics_Manager.Names_conditioncodes(getContext(),
                                        (int) formatedValue));
                            } catch (Exception e1) {
                                value.setText(loc_Value);
                            }
                        else
                            value.setText(loc_Value);
                    }
                    value.setAnimation(animation);
                } catch (Exception e) {
                    // It's probably a String that could'nt be converted to a float
                    Tracer.d(mytag, "Handler exception : new value <" + loc_Value + "> not numeric !");
                    try {
                        Tracer.d(mytag, "Try to get value translate from R.STRING");
                        value.setText(
                                Graphics_Manager.getStringIdentifier(getContext(), loc_Value.toLowerCase()));
                    } catch (Exception e1) {
                        Tracer.d(mytag, "Nothing in R.STRING for " + loc_Value);
                        value.setText(loc_Value);
                    }
                }
                //To have the icon colored as it has no state
                IV_img.setBackgroundResource(Graphics_Manager.Icones_Agent(usage, 2));
            } else if (msg.what == 9998) {
                // state_engine send us a signal to notify it'll die !
                Tracer.d(mytag, "state engine disappeared ===> Harakiri !");
                session = null;
                realtime = false;
                removeView(LL_background);
                myself.setVisibility(GONE);
                if (container != null) {
                    container.removeView(myself);
                    container.recomputeViewAttributes(myself);
                }
                try {
                    finalize();
                } catch (Throwable t) {
                } //kill the handler thread itself
            }
        }

    };

    //================================================================================
    /*
     * New mechanism to be notified by widgetupdate engine when our value is changed
     * 
     */
    WidgetUpdate cache_engine = WidgetUpdate.getInstance();
    if (cache_engine != null) {
        session = new Entity_client(dev_id, state_key, mytag, handler, session_type);
        if (Tracer.get_engine().subscribe(session)) {
            realtime = true; //we're connected to engine
            //each time our value change, the engine will call handler
            handler.sendEmptyMessage(9999); //Force to consider current value in session
        }

    }
    //================================================================================
    //updateTimer();   //Don't use anymore cyclic refresh....   

}

From source file:com.md87.charliebravo.commands.DefineCommand.java

public void execute(final InputHandler handler, Response response, String line)
        throws MalformedURLException, IOException, JSONException {
    URL url = new URL("http://apps.md87.co.uk/services/wiktionary/?query="
            + URLEncoder.encode(line, Charset.defaultCharset().name()));
    URLConnection connection = url.openConnection();
    connection.addRequestProperty("Referer", "http://chris.smith.name/");

    String input;//  w w  w.j a v  a 2s  .c om
    StringBuilder builder = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    while ((input = reader.readLine()) != null) {
        builder.append(input);
    }

    JSONObject json = new JSONObject(builder.toString());
    if (json.getInt("responseStatus") != 200) {
        throw new IOException(json.getString("responseDetails"));
    }

    if (json.getJSONArray("responseData").length() == 0) {
        response.sendMessage("There were no results for '" + line + "'", true);
    } else {
        final StringBuilder res = new StringBuilder();
        res.append("there ");

        if (json.getJSONArray("responseData").length() == 1) {
            res.append("was 1 match");
        } else {
            res.append("were ");
            res.append(json.getJSONArray("responseData").length());
            res.append(" matches");
        }

        res.append(" for '");
        res.append(line);
        res.append("'");

        if (json.getJSONArray("responseData").length() == 1) {
            res.append(". It is ");
        } else {
            res.append(". Result 1 is ");
        }

        final String name = json.getJSONArray("responseData").getJSONObject(0).getString("title");

        res.append('\'');
        res.append(name);
        res.append("', which has ");

        final int defs = json.getJSONArray("responseData").getJSONObject(0).getJSONArray("definitions")
                .length();
        res.append(defs);

        res.append(" definition");

        if (defs != 1) {
            res.append("s, the first of which is");
        }

        res.append(": ");

        res.append(json.getJSONArray("responseData").getJSONObject(0).getJSONArray("definitions").get(0));

        response.sendMessage(res.toString());
        response.addFollowup(new NextWordFollowup(json.getJSONArray("responseData"), 1));
        response.addFollowup(new NextDefinitionFollowup(
                json.getJSONArray("responseData").getJSONObject(0).getJSONArray("definitions"), 1,
                new NextWordFollowup(json.getJSONArray("responseData"), 1)));
    }
}

From source file:to.networld.fbtosemweb.fb.FacebookAgentHandler.java

public FacebookAgent getFacebookAgent() throws IOException, JSONException {
    JSONObject entryObject = this.getContent(this.FB_ME_URL);
    return new FacebookAgent(entryObject.getString("id"), entryObject);
}

From source file:to.networld.fbtosemweb.fb.FacebookAgentHandler.java

public Vector<FacebookLikesEntry> getLikesConcepts() throws IOException, JSONException {
    Vector<FacebookLikesEntry> resultEntries = new Vector<FacebookLikesEntry>();
    JSONObject likesObject = this.getContent(this.FB_LIKES_URL);
    JSONArray likesEntries = likesObject.getJSONArray("data");
    for (int count = 0; count < likesEntries.length(); count++) {
        JSONObject jsonEntry = (JSONObject) likesEntries.get(count);
        FacebookLikesEntry likesEntry = new FacebookLikesEntry(jsonEntry.getString("id"),
                jsonEntry.getString("name"), jsonEntry.getString("category"),
                jsonEntry.getString("created_time"));
        resultEntries.add(likesEntry);/*from   w ww .j a va2  s.c o m*/
    }
    return resultEntries;
}

From source file:to.networld.fbtosemweb.fb.FacebookAgentHandler.java

public Vector<FacebookFriendEntry> getFriends() throws IOException, JSONException {
    Vector<FacebookFriendEntry> resultEntries = new Vector<FacebookFriendEntry>();
    JSONObject likesObject = this.getContent(this.FB_FRIENDS_URL);
    JSONArray likesEntries = likesObject.getJSONArray("data");
    for (int count = 0; count < likesEntries.length(); count++) {
        JSONObject jsonEntry = (JSONObject) likesEntries.get(count);
        FacebookFriendEntry friendEntry = new FacebookFriendEntry(jsonEntry.getString("id"),
                jsonEntry.getString("name"));
        resultEntries.add(friendEntry);//from w w w. j  a v a  2 s. co m
    }
    return resultEntries;
}