Spinner data duplicated when list is clicked

2019-08-15 06:06发布

问题:

In Activity B there has a spinner where the data were get from MySQL (Table location).

Activity B

private ArrayList<String> froms;
private JSONArray resultFrom;

public void addItemsOnFrom() {

    travelFrom = (Spinner) findViewById(R.id.travelFrom);
    StringRequest stringRequest = new StringRequest(Configs.FROM_URL,
            new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    JSONObject j = null;
                    try {
                        //Parsing the fetched Json String to JSON Object
                        j = new JSONObject(response);

                        //Storing the Array of JSON String to our JSON Array
                        resultFrom = j.getJSONArray(Configs.JSON_ARRAY);

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

                }
            });

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

    //Adding request to the queue
    requestQueue.add(stringRequest);
}

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

            //Adding the name of the student to array list
            froms.add(json.getString(Configs.TAG_LOCATION));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //Setting adapter to show the items in the spinner
    travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));
}

When save button is clicked, it will return the selected value(OFFICE) to Activity A listView. And in Activity A, when the list is pressed, it will intent to Activity B. In this time, the spinner in Activity B will display the selected item first(OFFICE).

**Table location**  // table location has 2 data
NONE 
OFFICE

Assume OFFICE is selected in B. When list is clicked, I want OFFICE display first in spinner B.

Code in Activity B for display OFFICE first.

if(getIntent().getExtras()!=null)
{ 
    final String from = getIntent().getStringExtra("from");
    selectedItemFrom(from);
}

public void selectedItemFrom(final String value)// display  OFFICE first
{
    travelFrom = (Spinner) findViewById(R.id.travelFrom);
    StringRequest stringRequest = new StringRequest(Configs.FROM_URL,
            new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    JSONObject j = null;
                    try {
                        //Parsing the fetched Json String to JSON Object
                        j = new JSONObject(response);

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

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

                }
            });

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

    //Adding request to the queue
    requestQueue.add(stringRequest);
}

private void getFrom(JSONArray j, String value) {
    int position = 0;
    //Traversing through all the items in the json array
    for (int i = 0; i < j.length(); i++) {
        try {
            //Getting json object
            JSONObject json = j.getJSONObject(i);
            //Adding the name of the student to array list
            froms.add(json.getString(Configs.TAG_LOCATION));
            if (froms.get(i).equalsIgnoreCase(value)) {

                position = i;
                //Toast.makeText(getApplicationContext(),position+"",Toast.LENGTH_LONG).show();
                break;
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));
    travelFrom.setSelection(position);
}

The OFFICE can display first, but the problem is when I checked the spinner B, it shows NONE,OFFICE,NONE OFFICE ..Why the spinner data will get duplicated ? Thanks

I think problem is in this line travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));...But how to solve??? Anyone?

And sometimes the spinner will display the selected item first but sometimes it will not...What are the better way to write?

Edit

{"result":[{"name":"NONE"},{"name":"OFFICE"}]}

I put forms.clear in beginning of both getFrom method now. But the problem is when I select NONE and return to A, then goes to B again,the spinner now has NONE only...

回答1:

Please try something like this.

This activity will expect a Intent with the key "from" that is set to either "NONE" or "OFFICE". If the intent does not have the data, then it will default to whatever was inserted into the Spinner first.

public class MainActivity extends AppCompatActivity {

    private Spinner travelFrom;
    private ArrayAdapter<String> mSpinnerAdapter;
    private List<String> mSpinnerData;

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

        String from = null;
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            from = extras.getString("from");
        }

        setupFromSpinner(from);
    }

    private void setupFromSpinner(final String value) {
        travelFrom = (Spinner) findViewById(R.id.travelFrom);
        mSpinnerData = new ArrayList<String>();
        mSpinnerAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, mSpinnerData);
        mSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        travelFrom.setAdapter(mSpinnerAdapter);

        JsonObjectRequest req = new JsonObjectRequest(Configs.FROM_URL,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        mSpinnerData.clear();
                        try {
                            JSONArray resultFrom = response.getJSONArray("result");
                            for (int i = 0; i < resultFrom.length(); i++) {
                                JSONObject fromObj = resultFrom.getJSONObject(i);
                                String name = fromObj.getString("name");
                                mSpinnerData.add(name);
                            }
                            mSpinnerAdapter.notifyDataSetChanged();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        if (value != null) {
                            int position = mSpinnerAdapter.getPosition(value);
                            travelFrom.setSelection(position);
                        } else {
                            travelFrom.setSelection(0);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }
        );

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

        //Adding request to the queue
        requestQueue.add(req);
    }
}


回答2:

add froms.clear() to this piece of code;

private void getFrom(JSONArray j) {
    //Traversing through all the items in the json array
    froms.clear();
    for (int i = 0; i < j.length(); i++) {
        try {
            //Getting json object
            JSONObject json = j.getJSONObject(i);

            //Adding the name of the student to array list
            froms.add(json.getString(Configs.TAG_LOCATION));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //Setting adapter to show the items in the spinner
    travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));
}