2

So I'm trying to get all the keys within a specific JSON Object but only the last key is obtained.

   public void setUpSearch(JSONObject data_json){

    Iterator<String> keys = data_json.keys();
    while (keys.hasNext()) {
        //get the key
        String key = keys.next();
        scripts = new ArrayList<String>();
        scripts.add(key);
        Log.i(TAG, key);
        Log.i(TAG, String.valueOf(scripts));
    }

Logtagging key shows all keys (around 300 of em), however logtagging scripts shows only the last one.

Any help will be highly appreciated.

2
  • Also, please do remember to accept your answers (all of them) if they have given you satisfactory answers (by clicking on the tick mark on the left of the answers), it would be helpful to the community – Commented Jun 27, 2015 at 17:22
  • I will :-) accept em Commented Jun 27, 2015 at 17:23

1 Answer 1

3

Because there is a BUG in your code. ArrayList initialization should be outside loop, otherwise you're overwriting previous one every time.

Use below code:

public void setUpSearch(JSONObject data_json){

    Iterator<String> keys = data_json.keys();
     scripts = new ArrayList<String>();

    while (keys.hasNext()) {
        //get the key
        String key = keys.next();
        scripts.add(key);
        Log.i(TAG, key);
        Log.i(TAG, String.valueOf(scripts));
    }
Sign up to request clarification or add additional context in comments.

1 Comment

It worked like a charm. Ill accept your answer in 10 min

Your Answer

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