在Array中解析JSONArray并在Android的Spinner中显示数据

时间:2019-02-27 00:55:43

标签: android

我正在实现带有微调器的自定义地图。微调器中将填充用户名。单击微调器中的选定项目后,我想将其固定在地图上。但不幸的是,我只得到用户名。我想获得所有的用户名,当我单击该特定的用户名时,我想在地图上显示数组子结果的所有内容。 这是我的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"
         }
      ]
   }
]

在Android的JSONArray中找到我的代码

     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;
    }

}

还有另一个用于微调器的代码

公共类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";

}

1 个答案:

答案 0 :(得分:0)

这不是复制和粘贴的解决方案,而是一小段代码,可以帮助您解决需要自定义适配器的类似问题。

“我只获取用户名。我想获取JSON中所有用户名和所有子结果数组的内容”

  1. 您需要创建一个名为Student的POJO类

`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. 更新getStudent方法以包括缺少的子结果

`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. 创建自定义学生适配器

PS:请务必查找我使用的所有术语,因为您不熟悉它们,编码愉快。