单击列表时,Spinner数据重复

时间:2016-02-17 16:33:25

标签: java android json listview spinner

在活动B中有一个spinner,其中的数据来自MySQL(表格位置)。

活动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));
}

点击保存button后,它会将所选值(OFFICE)返回到活动A listView。在活动A中,当按下列表时,它将意图活动B.此时,活动B中的微调器将首先显示所选项目(OFFICE)。

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

假设在B中选择了OFFICE。当点击列表时,我想首先在spinner B中显示OFFICE。

活动B 中的代码,首先显示OFFICE。

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

OFFICE可以先显示,但问题是当我检查微调器B时,显示NONE,OFFICE,NONE OFFICE ..为什么微调器数据会重复?感谢

我认为问题出在这一行travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms)); ......但是如何解决?任何人吗?

有时微调器会首先显示所选项目,但有时它不会......有什么更好的写法?

修改

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

我现在在两个getFrom方法的开头放置forms.clear。但问题是当我选择NONE并返回A,然后再次转到B时,微调器现在只有NONE ...

2 个答案:

答案 0 :(得分:1)

将froms.clear()添加到这段代码中;

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

答案 1 :(得分:1)

请尝试这样的事情。

此活动预计会设置为"from""NONE"的密钥"OFFICE"的意图。如果intent没有数据,那么它将默认为先插入Spinner的内容。

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