1

I'm trying to do something like:

public static final JSONObject MYOBJ = new JSONObject().put("value", "expression");

but eclipse get's mad and says there's an error on the line even though the tool tip shows No solutions available

I've tried changing JSONObject to type String and still the same prob. I'm shying away from hash maps and would really like to use JSON.

** EDIT - code location **

package ...

import ...

public class MyActivity extends Activity {
    public static final JSONObject MYOBJ = new JSONObject().put("value", "expression");

    ... // onCreate etc
}
1
  • Where do you exactly put this statement? Commented Oct 31, 2011 at 23:16

2 Answers 2

6

Well it seems the JSONObject has a checked exception that must be handled. Try this

public static final JSONObject MYOBJ = new JSONObject(){
    {
        try {
            put("value", "expression");
        } catch(Exception e){
            e.printStackTrace();
        }
    }
};
Sign up to request clarification or add additional context in comments.

2 Comments

That's a pain, seems like a runtime exception would have been a better choice.
Fortunately it's not final so a delegate class that throws an RTE is diable :)
2

The result of put() is an Object. Do it in two lines and all is well.

public static final JSONObject MYOBJ = new JSONObject();
static {
  MYOBJ.put("value", "expression");
}

Note that the static final doesn't prevent the object from being changed, just that the original reference MYOBJ will always be the same object.

Edit: Ah, I was probably using a different flavor of the JSON library. Nonetheless, the above approach will probably work nicely. If the types all match, add some more parens to the original line.

6 Comments

For which JSONObject? According to this it's a JSONObject developer.android.com/reference/org/json/…
Pretty sure it's the exception ;)
@Jackson The static doesn't have anything to do with that; final means the reference won't be changed once assigned, static means it's a class variable (as opposed to instance variable).
@Dave I suppose I addressed the usage wrong, but either way I gave a +1 in regards to line 2-4.
@Jackson Oh, that; I see. Yep, static initialization block.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.