0

I have a json data listing all music scales and their keys.

this is how it looks like:

Scales Json

or the code view:

{
  "allScalesJson": [
    {
      "scale": "A Major",
      "keys": [
        "b",
        "a",
        "e",
        "d",
        "gs",
        "fs",
        "cs"
      ]
    },
    {
      "scale": "B Major",
      "keys": [
        "b",
        "e",
        "as",
        "gs",
        "fs",
        "ds",
        "cs"
      ]
    },
    {
      "scale": "D Major",
      "keys": [
        "b",
        "a",
        "g",
        "e",
        "d",
        "fs",
        "cs"
      ]
    }
  ]
}

I'm trying to create a method that will take keys as parameter and return all scales that contains those keys.

Example based on above json data:

List<String> returned_scales = findScalesThatContainThisKeys(Arrays.asList("a","d"));

output:

A Major, D Major

Here it is:

private List<String> findScalesThatContainThisKeys(List<String> keys_array){
    List<String> foundedScales = new ArrayList<>();
    try {
        JSONObject jsonObj = new JSONObject(loadJSONFromAsset());
        JSONArray rootElement = jsonObj.getJSONArray("allScalesJson");
        for (int i = 0; i < rootElement.length(); i++) {
            JSONObject obj = rootElement.getJSONObject(i);

            String scale = obj.getString("scale");

            // Keys is json array
            JSONArray genreArray = obj.getJSONArray("keys");
            ArrayList<String> keys = new ArrayList<>();
            for (int j = 0; j < genreArray.length(); j++) {
                // TODO: 5/12/2018
            }
        }
    }catch (Exception e){e.printStackTrace();}


    return foundedScales;
}
5
  • sorry i dont understnd this means ? " I'm trying to create a method that will take keys as parameter and return all scales that contains those keys." Commented May 12, 2018 at 4:57
  • what you exacly want to do i dont undrstand Commented May 12, 2018 at 4:59
  • @BirjuBhatt I've created an example of what I'm trying to do Commented May 12, 2018 at 5:02
  • All the items in your keys_array List should match ? or one item match is ik? Commented May 12, 2018 at 5:27
  • @AbuYousuf thanks for replay, order doesn't matter , but it should contain all the keys Commented May 12, 2018 at 5:30

4 Answers 4

1

Try this with for loops.

  private List<String> findScales(List<String> keys_array){
        List<String> foundedScales = new ArrayList<>();
        try {
            JSONObject jsonObj = new JSONObject(loadJSONFromAsset());
            JSONArray rootElement = jsonObj.getJSONArray("allScalesJson");
            ArrayList<String> scales_found = new ArrayList<>();

            for (int i = 0; i < rootElement.length(); i++) {
                JSONObject obj = rootElement.getJSONObject(i);

                String scale = obj.getString("scale");

                // Keys is json array
                JSONArray genreArray = obj.getJSONArray("keys");
                boolean all_found = true;

                for(String key: keys_array){
                   boolean found_this_key = false;
                   for (int j = 0; j < genreArray.length(); j++) {
                      if(key.equals(genreArray.getString(j))){
                          found_this_key = true;
                          break;
                      }
                   }
                   if(!found_this_key){
                        all_found = false;
                        break;
                   }
                }

                if(all_found){
                    scales_found.add(scale);
                }
            }

            return scales_found;
        }catch (Exception e){e.printStackTrace();}


        return foundedScales;
    }
Sign up to request clarification or add additional context in comments.

4 Comments

@AbuYousuf You can test it yourself. Its is checking for all keys
Sorry didn't check full code. This will also work. Got confused with loops .
Any way you can do it with one loop.
Even your answer is using 3 loops in total. Just that it is modular. Nice solution by the way..
1

Use this code:

private List<String> findScales(List<String> keys_array){
List<String> foundedScales = new ArrayList<>();
try {
    JSONObject jsonObj = new JSONObject(loadJSONFromAsset());
    JSONArray rootElement = jsonObj.getJSONArray("allScalesJson");


    for (int i = 0; i < rootElement.length(); i++) {
        JSONObject obj = rootElement.getJSONObject(i);

        String scale = obj.getString("scale");

        // Keys is json array
        JSONArray genreArray = obj.getJSONArray("keys");
        ArrayList<String> keys = new ArrayList<>();
        for (int j = 0; j < genreArray.length(); j++) {
            // TODO: 5/12/2018
            String str = genreArray.getString(j);
            keys.add(str);
        }

        if(isContainsKeys(keys_array, keys)){
           foundedScales.add(scale);
        } 
    }
}catch (Exception e){e.printStackTrace();}


  return foundedScales;
}


public boolean isContainsKeys(List<String> keys_array, List<String> keys ){
    if (keys.size() == 0) {
        return false;
    }  
    for (String s : keys_array) {
        if (!keys.contains(s)) {
            return false;
        }
    }

    return true;
}

This will ignore uppercase or lowercase issue. For that all string should be converted in one case (uppercase/lowercase)

Comments

0

try this, use Hashmap and get by key

public class MainActivity extends AppCompatActivity {


    private RequestQueue mRequestQueue;
    private StringRequest mStringRequest;
    private String url = "url";

    JSONArray jsonArray;

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

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

        mRequestQueue = Volley.newRequestQueue(this);
        //String Request initialized
        mStringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {


                try {
                    JSONObject jsonObject = new JSONObject(response);
                    jsonArray = jsonObject.getJSONArray("allScalesJson");
                    for (int i = 0; i <jsonArray.length() ; i++) {

                        jsonObject = jsonArray.getJSONObject(i);

                        meMap.put(jsonObject.getString("scale"),jsonObject.getString("keys"));

                    }

                    Toast.makeText(MainActivity.this, meMap.toString(), Toast.LENGTH_SHORT).show();
                    Toast.makeText(MainActivity.this, meMap.get("A Major"), Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        mRequestQueue.add(mStringRequest);


    }
}

1 Comment

This is not providing actual output
0

Update your code like below

private List<String> findScales(List<String> keys_array){ 
    List<String> foundedScales = new ArrayList<>(); 
    try { 
            JSONObject jsonObj = new JSONObject(loadJSONFromAsset());       

            JSONArray rootElement = jsonObj.getJSONArray("allScalesJson"); 
            for (int i = 0; i < rootElement.length(); i++) { 
                 JSONObject obj = rootElement.getJSONObject(i); 
                 String scale = obj.getString("scale"); // Keys is json array 
                JSONArray genreArray = obj.getJSONArray("keys");  
                ArrayList<String> keys = new ArrayList<>(); 
                for (int j = 0; j < genreArray.length(); j++) { 
                      if(keys_array.contains(genreArray.get(i)){
                        foundedScales.add(scale);
                     }
                } 
            } 
        }catch (Exception e) {
             e.printStackTrace();
        } 
    return foundedScales; 
}

1 Comment

This will add scale for every key

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.