1

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...

AI.
  • 934
  • 2
  • 14
  • 30
  • just print the size of forms inside getFrom(JSONArray j,String value). and clear the data beforing adding to the list forms.clear(); – Sree Reddy Menon Feb 17 '16 at 16:57
  • @SreeReddyMenon I add `Log.e("SIZE",froms.size()+"");` inside try block but log did not display – AI. Feb 17 '16 at 17:20
  • okey. now do the same thing inside catch. is it printing system.err..kind of stuff.? – Sree Reddy Menon Feb 17 '16 at 17:26
  • @SreeReddyMenon no. The problem is I use Toast to display the size, but no Toast is showing. – AI. Feb 17 '16 at 17:35
  • @SreeReddyMenon Can you teach me the second method ? clear list – AI. Feb 17 '16 at 17:41
  • please debug yourself. i think here it is repeating i think. i am not sure. try log the form value inside if condition.. just log everything. you will get. if (froms.get(i).equalsIgnoreCase(value)) { position = i; break; } – Sree Reddy Menon Feb 17 '16 at 18:18
  • Please add to your question what the JSON response looks like – OneCricketeer Feb 18 '16 at 07:43
  • @cricket_007 sorry sir..how to show the JSON response? which line – AI. Feb 18 '16 at 08:05
  • ... I don't know how to explain this... Whatever this variable equals, go to that address on your computer in the browser `Configs.FROM_URL`. Copy all the content, then paste it into an edit to your question, not the comments. I also didn't say *line* – OneCricketeer Feb 18 '16 at 12:42
  • @cricket_007 this is what I get when I paste the url to browser. The spinner in the data duplicated but in the table location, it still has two data only – AI. Feb 18 '16 at 15:56
  • Put `froms.clear()` at the beiginning of both `getFrom()` methods. And I recommend using `JsonObjectRequest` instead of StringRequest since you are expecting JSON responses – OneCricketeer Feb 18 '16 at 16:00
  • do you fixed it? @AI. – Swaminathan V Feb 18 '16 at 16:19
  • @cricket_007 If I select `OFFICE`, then return to A, then B again. I see `NONE` and `OFFICE` in spinner. That's fine. If I select `NONE`, then return to to then B again, the spinner has `NONE` only – AI. Feb 18 '16 at 16:23
  • @RaguSwaminathan no, fixing... – AI. Feb 18 '16 at 16:23
  • Why is there a break statement inside the loop. That will exit that loop as soon as you hit the first matching element, thus stopping anymore elements to be added to `froms` – OneCricketeer Feb 18 '16 at 16:40
  • @cricket_007 what is the correct way ? – AI. Feb 18 '16 at 16:47
  • remove that if statement entirely and do `position = froms.indexOf(value)` – OneCricketeer Feb 18 '16 at 16:54
  • @cricket_007 thanks you sir it works, but do you have any idea why sometimes it will display the selected item first but sometimes not? – AI. Feb 18 '16 at 17:18
  • I don't know what you're trying to do.... All I can see is a JSON object being loaded into a Spinner, then you want to set the position of the correct string. ... If that is all you want to do, this answer looks like what you want http://stackoverflow.com/a/4228121/2308683 – OneCricketeer Feb 18 '16 at 17:22
  • @cricket_007 yes sir, I want the selected item display in spinner first when listView in A is clicked. Sometimes it works but sometimes not. And I have used that answer – AI. Feb 18 '16 at 17:25

2 Answers2

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));
}
Marcin D
  • 918
  • 7
  • 14
  • do you have any idea why sometimes it will display the selected item first but sometimes not? – AI. Feb 18 '16 at 17:19
  • seems like you set the adapter twice, for no reason. You also do this after you find the location of your value, so maybe you set a different adapter with a different index of the value you re choosing. You should really call this "travelFrom.setAdapter(new ArrayAdapter(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));" only once at initialization – Marcin D Feb 18 '16 at 17:22
  • @cricket answer worked as the data in `spinner` will not duplicated now – AI. Feb 18 '16 at 17:29
  • simple clear your arraylist before getting responce data tq u marcin d – suresh madaparthi Apr 20 '23 at 06:46
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);
    }
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245