0

I'm trying to write a cordova plugin. I've the following JSON data:

JSONObject obj = {"amount":100, "desc":"blabla",id:123}

and I'm trying to iterate the JSON keys and put keys and values to intent.putExtra(key,val)

Example:

Iterator<String> iter = obj.keys();
while (iter.hasNext()) {
    key = iter.next();
    value = obj.getString(key);
    intent.putExtra(key, value);
}

With this code I get the error

error: cannot find symbol intent.putExtra(key, value);

Anyone can say me how correct iterate JSON data and execute putExtra()?

4
  • 2
    Where creating intent ? Commented Dec 27, 2016 at 8:20
  • Have a look to this. It will surely help you out. stackoverflow.com/questions/30395281/… Commented Dec 27, 2016 at 8:22
  • Create Intent object first Commented Dec 27, 2016 at 8:26
  • @soSlow please consider to accept one of the answer below if it helped to figure out the issue. Commented Dec 27, 2016 at 15:56

2 Answers 2

0

First, the json you provide is not valid. It should be something like:

{"amount":100, "desc":"blabla","id":123}

Then, as said in the comments, create an intent variable outside the for loop. And finally, you should use

Object value = obj.get(key)

because values can be Strings or Integers.

Sign up to request clarification or add additional context in comments.

Comments

0

Extension to Lino's answer.

As Intent.putExtra(String, Object) is not available, you need following modifications.

        JSONObject obj = new JSONObject("{" +
                "\"amount\": 100," +
                "\"desc\": \"blabla\"," +
                "\"id\": 123," +
                "\"id2\": 123.56" +
                "}");

        Intent intent = new Intent();
        Iterator<String> iter = obj.keys();
        while (iter.hasNext()) {
            String key = iter.next();
            Object value = obj.get(key);
            if (value instanceof Float || value instanceof Double) {
                intent.putExtra(key, (double) value);
            } else if (value instanceof Integer || value instanceof Long) {
                intent.putExtra(key, (long) value);
            } else if (value instanceof String) {
                intent.putExtra(key, (String) value);
            } /*else if (more cases go here) {

            } */
        }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.