0

I´m new to programming and android and some problems with JsonObject/JsonArray, I know Im close but missing something .

After trying some solutions and tuts, I have no errors ! , even If I try others api I get it all right , but in this case the app is closing .

OK, I use this api , this is all the response

{ "target": "MXN", "success": true, "rate": 13.1035, "source": "USD", "amount": 13.1, "message": "" }

I understand my error is in the “cannot be converted to JSONObject”, but I don´t know how to fix it ? Any Ideas ?

my logcat

org.json.JSONException: Value MXN at target of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:100)
at org.json.JSONObject.getJSONObject(JSONObject.java:578)
at com.example.androidjsonparser.MainActivity$ProgressTask.doInBackground(MainActivity.java:106)
at com.eaxmple.androidjsonparser.MainActivity$ProgressTask.doInBackground(MainActivity.java:1)

MainActivity

package com.example.androidjsonparser;

import java.util.ArrayList;...

public class MainActivity extends ListActivity {
private Context context;

private static String url = "http://currency-api.appspot.com/api/USD/MXN.json?key=24c050085728994c96582a3000b9673f55370909";

private static final String TAG_TARGET = "target";
private static final String TAG_RATE = "rate";
private static final String TAG_SOURCE = "source";
private static final String TAG_AMOUNT = "amount";
private static final String TAG_MESSAGE = "";

ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();

ListView lv ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new ProgressTask(MainActivity.this).execute();
}

private class ProgressTask extends AsyncTask<String, Void, Boolean> {
    private ProgressDialog dialog;

    private ListActivity activity;

    // private List<Message> messages;
    public ProgressTask(ListActivity activity) {
        this.activity = activity;
        context = activity;
        dialog = new ProgressDialog(context);
    }

    /** progress dialog to show user that the backup is processing. */

    /** application context. */
    private Context context;

    protected void onPreExecute() {
        this.dialog.setMessage("Progress start");
        this.dialog.show();
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        ListAdapter adapter = new SimpleAdapter(context, jsonlist,
                R.layout.list_item, new String[] { TAG_TARGET, TAG_RATE,
                TAG_SOURCE, TAG_AMOUNT }, new int[] {
                R.id.target, R.id.rate, R.id.source,
                R.id.amount });

        setListAdapter(adapter);

        // selecting single ListView item
         lv = getListView();

    }

    protected Boolean doInBackground(final String... args) {

        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        for (int i = 0; i < json.length(); i++) {
            try {                   
                JSONObject c = json.getJSONObject(TAG_TARGET);

                String target = c.getString(TAG_TARGET);
                String rate = c.getString(TAG_RATE);
                String source = c.getString(TAG_SOURCE);
                String amount = c.getString(TAG_AMOUNT);                    
                String message = c.getString(TAG_MESSAGE);

                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_TARGET, target);
                map.put(TAG_RATE, rate);
                map.put(TAG_SOURCE, source);
                map.put(TAG_AMOUNT, amount);

                map.put(TAG_MESSAGE, message);

                jsonlist.add(map);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return null;

    }

}

}

And my JsonParser

package com.example.androidjsonparser;

import java.io.BufferedReader;...

public class JSONParser {  

static InputStream is = null;
static JSONObject jarray = null;
static String json = "";

// constructor
public JSONParser() {  

}

public JSONObject getJSONFromUrl(String url) {

       StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
          HttpResponse response = client.execute(httpGet);
          StatusLine statusLine = response.getStatusLine();
          int statusCode = statusLine.getStatusCode();
          if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
              builder.append(line);
            }
          } else {
            Log.e("==>", "Failed to download file");
          }
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }

    // try parse the string to a JSON object
    try {
        jarray = new JSONObject( builder.toString());
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jarray;

}
 }
3
  • 1
    what is line 106 MainActivity2.java? Commented Jan 8, 2014 at 7:49
  • why you have for statement for JSONObject? Commented Jan 8, 2014 at 7:50
  • Raghunandan , Thanks ! .. just trying something, this is the actual code now Commented Jan 8, 2014 at 8:44

1 Answer 1

1

I think because when you do this:

JSONObject c = json.getJSONObject(TAG_TARGET);

You're not getting a JSON object, but the value for the key TAG_TARGET.. which is not a JSON object but a string..

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

1 Comment

You´re right the whole object it´s what he gets from the jParser.getJSONFromUrl(url); from that point on primo should use the json.getString(value) (or any other desired type) for getting the values.

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.