1

I am implementing customized maps that have spinner. The spinner is populated with the users name. Upon clicking the selected item in the spinner, I want to pin the locations of it in the map. But unfortunately, I only get the users name. I wanted to get all the usersname and when I click that specific username Iwant to show all the content of array subresult in the map. Here's my JSON:

    {
    "result" :[

           {  
              "username":"sinsiri",
              "subresult":[  
                 {  
                    "latitude":"13.088847376649245",
                    "longitude":"121.0535496566772",
                    "province":"Mindoro"
                 },
                 {  
                    "latitude":"14.898346071682198",
                    "longitude":"121.42616213302608",
                    "province":"General nakar"
                 }
              ]
           },
{  
      "username":"qwerty",
      "subresult":[  
         {  
            "latitude":"6.984796116278719",
            "longitude":"122.02642351890961",
            "province":"Zamboanga"
         }
      ]
   },
   {  
      "username":"asd",
      "subresult":[  
         {  
            "latitude":"16.229997551983594",
            "longitude":"120.52623997214562",
            "province":"Baguio"
         }
      ]
   }
]

Heres My code in JSONArray in Android

     public class MapsFlagActivity extends FragmentActivity implements OnMapReadyCallback,LocationListener,GoogleMap.OnMarkerClickListener, Spinner.OnItemSelectedListener {

    private GoogleMap mMap;
    public static final String URL= BASE_URL +"location.php";
    private JSONArray results;
    public String alat, blong;
    ProgressDialog pd;
    public String lat;
    public String lon;

    //Declaring an Spinner
    public Spinner spinner;

    //An ArrayList for Spinner Items
    public ArrayList<String> students;

    //JSON Array
    public JSONArray result;

    //TextViews to display details
    public TextView textViewLatitude, latview, lonview, proview;
    public TextView textViewLongitude;
    public TextView textViewProvince;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps_flag);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        final Button refresh = findViewById(R.id.refresh);
        final Button showall = findViewById(R.id.showall);

        //Initializing the ArrayList
        students = new ArrayList<>();

        //Initializing Spinner
        spinner = findViewById(R.id.spinner);

        //Adding an Item Selected Listener to our Spinner
        //As we have implemented the class Spinner.OnItemSelectedListener to this class itself we are passing this to setOnItemSelectedListener
        spinner.setOnItemSelectedListener(this);

        //Initializing TextViews
        textViewLatitude = findViewById(R.id.textViewLatitude);
        textViewLongitude = findViewById(R.id.textViewLongitude);
        textViewProvince = findViewById(R.id.textViewProvince);
        latview = findViewById(R.id.latview);
        lonview = findViewById(R.id.lonview);
        proview = findViewById(R.id.proview);

        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                SpotsDialog dialog = new SpotsDialog(MapsFlagActivity.this, R.style.Refresh);
                dialog.show();

                //This method will fetch the data from the URL
                getData();

                dialog.dismiss();
            }
        });
    }

    public void getData(){
        textViewLatitude.setVisibility(View.VISIBLE);
        textViewLongitude.setVisibility(View.VISIBLE);
        textViewProvince.setVisibility(View.VISIBLE);
        latview.setVisibility(View.VISIBLE);
        lonview.setVisibility(View.VISIBLE);
        proview.setVisibility(View.VISIBLE);
        //Creating a string request
        StringRequest stringRequests = new StringRequest(Config.DATA_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        JSONObject jo = null;
                        try {
                            //Parsing the fetched Json String to JSON Object
                            jo = new JSONObject(response);

                            //Storing the Array of JSON String to our JSON Array
                            result = jo.getJSONArray(Config.JSON_ARRAY);

                            //Calling method getStudents to get the students from the JSON Array
                            getAnimals(result);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        //Creating a request queue
        RequestQueue requestQueue2 = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue2.add(stringRequests);
    }

    public void getAnimals(JSONArray ja){
        //Traversing through all the items in the json array
        for(int i=0;i<ja.length();i++){
            try {
                //Getting json object
                JSONObject json = ja.getJSONObject(i);

                //Adding the name of the student to array list
                students.add(json.getString(Config.TAG_COMMONNAME));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //Setting adapter to show the items in the spinner
        spinner.setAdapter(new ArrayAdapter<>(MapsFlagActivity.this, android.R.layout.simple_list_item_1, students));
    }

    //Method to get student name of a particular position
    public String getLatitude(int position){
        String name="";
        try {
            //Getting object of given index
            JSONObject json = result.getJSONObject(position);
            Toast.makeText(MapsFlagActivity.this, "Selected: " + spinner.getItemAtPosition(position), Toast.LENGTH_LONG).show();

            //Fetching name from that object
            name = json.getString(Config.TAG_LATITUDE);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Returning the name
        return name;
    }

    //Doing the same with this method as we did with getName()
    public String getLongitude(int position){
        String course="";
        try {
            JSONObject json = result.getJSONObject(position);
            course = json.getString(Config.TAG_LONGITUDE);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return course;
    }

    //Doing the same with this method as we did with getName()
    public String getProvince(int position){
        String session="";
        try {
            JSONObject json = result.getJSONObject(position);
            session = json.getString(Config.TAG_PROVINCE);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return session;
    }

    //this method will execute when we pic an item from the spinner
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {
        //Setting the values to text views for a selected item
        textViewLatitude.setText(getLatitude(position));
        textViewLongitude.setText(getLongitude(position));
        textViewProvince.setText(getProvince(position));

        try {
             lat = String.valueOf(textViewLatitude.getText().toString());
             lon = String.valueOf(textViewLongitude.getText().toString());
            mMap.clear();
        }catch(NumberFormatException e) {
            e.printStackTrace();
        }

        mMap.addMarker(new MarkerOptions()
                .position(new LatLng(Double.parseDouble(lat), Double.parseDouble(lon)))
                //.title(Double.valueOf(lat_i).toString() + "," + Double.valueOf(long_i).toString())
                .title(spinner.getSelectedItem().toString())
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN))
        );
    }

    //When no item is selected this method would execute
    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        textViewLatitude.setText("");
        textViewLongitude.setText("");
        textViewProvince.setText("");
    }
    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        /*LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/

        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(13.088847376649245,121.0535496566772), 6.0f));
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        return false;
    }

}

Heres another code for spinner

public class Config {

//JSON URL
public static final String DATA_URL = BASE_URL + "locationflag.php";

//Tags used in the JSON String
public static final String TAG_COMMONNAME= "commonname";
public static final String TAG_LATITUDE = "latitude";
public static final String TAG_LONGITUDE = "longitude";
public static final String TAG_PROVINCE = "province";

//JSON array name
public static final String JSON_ARRAY = "result";

}

2
  • 1
    Not so sure about the whole structure of the json, cause the response looks very inconsistent, but im going to asume every username has ONE subresult. Assuming this, to acces all the elements in subresult you have to query subresult first, something like this maybe: json.getJSONObject("subresult").getString(TAG_WHATEVER); Commented Feb 27, 2019 at 2:18
  • Im not so sure about this so I won't post it as an aswer, just check if this makes sense to you Commented Feb 27, 2019 at 2:21

1 Answer 1

1

This will not be a copy and paste solution but a train of thought with bits and pieces of code that will help you solve similar problems that require custom Adapters.

"I only get the users name. I wanted to get all the users name and the content of all the subresult array in JSON"

  1. you need to create a POJO class named Student

` import java.util.ArrayList;

public class Student {
private String username;
private ArrayList<Subresult> subresult;

public Student(String username, ArrayList<Subresult> subresult) {
    this.username = username;
    this.subresult = subresult;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public ArrayList<Subresult> getSubresult() {
    return subresult;
}

public void setSubresult(ArrayList<Subresult> subresult) {
    this.subresult = subresult;
}

public static class Subresult {
    private String latitude;
    private String longitude;
    private String province;

    public String getLatitude() {
        return latitude;
    }

    public void setLatitude(String latitude) {
        this.latitude = latitude;
    }

    public String getLongitude() {
        return longitude;
    }

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }
}

} `

  1. update the getStudent method to include the missing subresults

`Spinner spinner;

   ArrayList<Student> students = new ArrayList<>();

   public void getStudents(JSONArray ja) {
    for (int i = 0; i < ja.length(); i++) {
        try {
            //Getting json object
            JSONObject json = ja.getJSONObject(i);
            JSONArray subresults = json.getJSONArray(Config.SUBRESULTS);
            for (int ii = 0; ii < subresults.length(); ii++) {
                JSONObject json_data = subresults.getJSONObject(ii);
                String latitude = json_data.getString("latitude");
                String longitude = json_data.getString("longitude");
                String province = json_data.getString("province");


                // Adding the student object with name and subresult array to student array list
                students.add(new Student(json.getString(Config.TAG_USERNAME), new Student.Subresult(latitude, longitude, province));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    // Create an adapter named 'StudentAdapter' set custom adapter to the spinner
    spinner.setAdapter(new StudentAdapter(students, context));
}`
  1. create a custom student adapter

PS: please do look up any terms I used you are not familar with, happy coding.

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

Comments

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.