Arnaldo
Arnaldo

Reputation: 683

Android Unhandled exception: org.json.JSONException with ion

I'm now trying to get json array with ion (https://github.com/koush/ion) But I get the error: Unhandled exception: org.json.JSONException :(

My json:

[{"title":"Hello world","text":"This is the text"}]

My code:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json);

        Ion.with(MyActivity.this)
                .load(getString(R.string.json_url))
                .asJsonArray()
                .setCallback(new FutureCallback<JSONArray>() {
                    @Override
                    public void onCompleted(Exception e, JSONArray result) {
                        if (e != null) {
                            Toast.makeText(MyJson.this, "Error loading strings", Toast.LENGTH_LONG).show();
                            return;
                        }
                        JSONObject c = result.getJSONObject(0);
                        if (c.has("title")) title = c.getString("title");
                        if (c.has("text")) text = c.getString("text");


                    }
                });

    }

Can someone tell me what I did wrong, please? :(

EDIT:

Error:(48, 17) error: method setCallback in interface Future<T> cannot be applied to given types;
required: FutureCallback<JsonArray>
found: <anonymous FutureCallback<JSONArray>>
reason: actual argument <anonymous FutureCallback<JSONArray>> cannot be converted to FutureCallback<JsonArray> by method invocation conversion
where T is a type-variable:
T extends Object declared in interface Future

Upvotes: 1

Views: 1901

Answers (1)

Arnaldo
Arnaldo

Reputation: 683

I solved the problem guys :)!

I changed: JSONArray (org.json.JSONArray) to: JsonArray (com.google.gson.JsonArray)

And I added this:

JsonObject c = result.get(0).getAsJsonObject();

This is the code now:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json);

        Ion.with(MyActivity.this)
                .load(getString(R.string.json_url))
                .asJsonArray()
                .setCallback(new FutureCallback<JsonArray>() {
                    @Override
                    public void onCompleted(Exception e, JsonArray result) {
                        if (e != null) {
                            Toast.makeText(MyJson.this, "Error loading strings", Toast.LENGTH_LONG).show();
                            return;
                        }
                        JsonObject c = result.get(0).getAsJsonObject();
                        if (c.has("title")) title = c.get("title").getAsString();
                        if (c.has("text")) text = c.get("text").getAsString();


                    }
                });

    }

This solved the problem!

Upvotes: 1

Related Questions