How to select spinner in dropdown to perform edit operation?

时间:2018-02-03 08:56:02

标签: android

I want to know how to select spinner to perform edit operation. I am getting only text after setting the text but I am not getting selected spinner to perform update operation. I have already added data in list and want to update the data. so three spinner is there. so I am not able to set spinner data to edit.

        //party_Adater

            @Override
            public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

                v = LayoutInflater.from (parent.getContext ())
                        .inflate (R.layout.item,parent,false);
                return new ViewHolder (v);


            }

            @Override
            public void onBindViewHolder(ViewHolder holder, final int position) {

                final Item item = itemList.get (position);


                holder.party_id.setText (item.getPartyId ());
                holder.party_name.setText (item.getPartyName ());
                holder.party_cat.setText (item.getPartyCategory ());
                holder.party_add.setText (item.getAddressLine1 ());
                holder.party_count.setText (item.getCountry ());
                holder.party_state.setText (item.getState ());
                holder.party_city.setText (item.getCity ());
                holder.party_pin.setText (item.getPostalCode ());
                holder.party_add2.setText (item.getAddressLine2 ());
                holder.party_type.setText (item.getPartyType ());



                holder.itemView.setOnClickListener (new View.OnClickListener ( ) {
                    @Override
                    public void onClick(View view) {
                        //final String id = item.getPartyId ();
                        goToUpdateActivity (item);

                    }
                });


            }

            private void goToUpdateActivity(Item item) {
                Intent intent = new Intent (context, MainInfoActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra ("Party_id", item.getPartyId ());
                intent.putExtra ("party_name",item.getPartyName ());
                intent.putExtra ("party_cat",item.getPartyCategory ());
                intent.putExtra ("party_add",item.getAddressLine1 ());
                intent.putExtra ("party_add2",item.getAddressLine2 ());
                intent.putExtra ("party_count",item.getCountry ());
                intent.putExtra ("party_state",item.getState ());
                intent.putExtra ("party_city", item.getCity ());
                intent.putExtra ("party_pin",item.getPostalCode ());
                intent.putExtra ("party_type",item.getPartyType ());
                context.startActivity (intent);
            }

        //Maininfoactivity

        //here I am getting text value but not getting Spinner Value to update

       //I am getting value from party adapter here

          Intent g = getIntent ();
                receivedPartyId =  g.getStringExtra ("party_id");
                abc = g.getStringExtra ("party_name");
               CompanyInputName.setText (abc);
                CompanyInputAddress.setText (g.getStringExtra ("party_add"));
                CompanyInputPincode.setText (g.getStringExtra ("party_pin"))

         String abcd = g.getStringExtra ("party_count");
                SpinnerCountry.setSelection(((ArrayAdapter<String>)SpinnerCountry.getAdapter()).getPosition(abcd));

    // Maininfoactivity


                package com.example.jjjj.dashboard.app;


import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.basgeekball.awesomevalidation.AwesomeValidation;
import com.basgeekball.awesomevalidation.ValidationStyle;
import com.example.jjjj.dashboard.R;
import com.example.jjjj.dashboard.model.Category_Model;
import com.example.jjjj.dashboard.model.CityObject;
import com.example.jjjj.dashboard.model.CountryObject;
import com.example.jjjj.dashboard.model.StateObject;
import com.toptoche.searchablespinnerlibrary.SearchableSpinner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainInfoActivity extends AppCompatActivity {

    private RequestQueue mrequestQueue;
    private ArrayList <CountryObject> country_list = new ArrayList <> ();
    private ArrayList <Category_Model> categoryList = new ArrayList <> ();
    private ArrayList <StateObject> state_List = new ArrayList <> ();
    private ArrayList <CityObject> city_List = new ArrayList <CityObject> ();
    ArrayAdapter <CountryObject> CountryAdapter;
    ArrayAdapter<StateObject> StateAdapter;
    ArrayAdapter<Category_Model> category_modelArrayAdapter;
    ArrayAdapter <CityObject> cityObjectArrayAdapter;
    private AwesomeValidation awesomeValidation;
    String receivedPartyId, abc;
    int  spinnerpostion;


    private static final String TAG = MainInfoActivity.class.getName ( );



    EditText CompanyInputName, CompanyInputAddress, CompanyInputPincode;
    TextInputLayout CompanyInputLayoutName, CompanyInputLayoutAddress, CompanyInputLayoutPincode;
    SearchableSpinner SpinnerCat, SpinnerCountry, SpinnerState, SpinnerCity;
    Button Next_btn;

    private String url = "";
    private String url1 = "";
    private String url2 = "";
    private String url3 = "";
    public String url4 = "";



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

        getSupportActionBar ().setDisplayHomeAsUpEnabled (true);

        //getSupportActionBar ().setTitle(CompanyInputName.setText ("abc"));





        awesomeValidation = new AwesomeValidation (ValidationStyle.BASIC);
        CompanyInputLayoutName = (TextInputLayout) findViewById (R.id.company_input_layout_name);
        CompanyInputLayoutAddress = (TextInputLayout) findViewById (R.id.company_input_layout_address);
        CompanyInputLayoutPincode = (TextInputLayout) findViewById (R.id.company_input_layout_pincode);

        CompanyInputName = (EditText) findViewById (R.id.company_input_name);
        CompanyInputAddress = (EditText) findViewById (R.id.company_input_address);
        CompanyInputPincode = (EditText) findViewById (R.id.company_input_pincode);

        awesomeValidation.addValidation (this, R.id.company_input_name, "(?:\\s*[a-zA-Z0-9,_\\.\\077\\0100\\*\\+\\&\\#\\'\\~\\;\\-\\!\\@\\;]{2,}\\s*)*", R.string.companynameerror);
        awesomeValidation.addValidation (this, R.id.company_input_address, "(?:\\s*[a-zA-Z0-9,_\\.\\077\\0100\\*\\+\\&\\#\\'\\~\\;\\-\\!\\@\\;]{2,}\\s*)*", R.string.addresserror);
        awesomeValidation.addValidation (this, R.id.company_input_pincode, "^\\d{6}$", R.string.pincodeerror);

        SpinnerCat = findViewById (R.id.spinner_cat);
        SpinnerCountry = findViewById (R.id.spinner_country);
        SpinnerState = findViewById (R.id.spinner_state);
        SpinnerCity = findViewById (R.id.spinner_city);

        Intent g = getIntent ();
        receivedPartyId =  g.getStringExtra ("party_id");
        abc = g.getStringExtra ("party_name");
       CompanyInputName.setText (abc);
        CompanyInputAddress.setText (g.getStringExtra ("party_add"));
        CompanyInputPincode.setText (g.getStringExtra ("party_pin"));

      String abcd = g.getStringExtra ("party_count");
        try {

            for (int x = 0; x < SpinnerCountry.getAdapter().getCount(); x++) {
                if ((SpinnerCountry.getItem(x)).equalsIgnoreCase(abcd)) {
                    SpinnerCountry.setSelection(((ArrayAdapter<String>)SpinnerCountry.getAdapter()).getPosition("party_count"));
                    break;
                }
            }

        } catch (Throwable e) {

        }






        Next_btn = findViewById (R.id.btn_move);

        Next_btn.setOnClickListener (new View.OnClickListener ( ) {

            @Override
            public void onClick(View view) {

                //NextActivity ( );

                if (view == Next_btn) {
                    NextActivity ( );
                }


            }



            private void NextActivity() {

                mrequestQueue = Volley.newRequestQueue (MainInfoActivity.this);
                StringRequest stringRequest = new StringRequest (Request.Method.POST, url4, new Response.Listener <String> ( ) {
                    @Override
                    public void onResponse(String response) {


                        Log.i(TAG,"Response: "+response);

                        if (awesomeValidation.validate ()) {

                            try {
                                JSONObject jsonObject = new JSONObject (response);
                                String p = (String) jsonObject.get ("partyId");
                                Intent intent = new Intent (getApplicationContext (),ContactActivity.class);
                                intent.putExtra ("c",p);
                                startActivity (intent);
                                Toast.makeText (MainInfoActivity.this, response.toString (),Toast.LENGTH_LONG).show ();


                            } catch (JSONException e) {
                                e.printStackTrace ( );
                            }


                        }

                    }
                }, new Response.ErrorListener ( ) {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                        Toast.makeText (getApplicationContext (),"Failure",Toast.LENGTH_LONG).show ();

                    }
                }) {
                    @Override
                    protected Map <String, String> getParams() throws AuthFailureError {
                        CountryObject countryObject = (CountryObject) SpinnerCountry.getSelectedItem ();
                        StateObject stateObject = (StateObject) SpinnerState.getSelectedItem ();
                        Category_Model categoryModel = (Category_Model) SpinnerCat.getSelectedItem ();
                        CityObject cityObject = (CityObject) SpinnerCity.getSelectedItem ();
                        Map<String, String> params = new HashMap <> ();
                        params.put ("partyId", "");
                        params.put ("createdBy", "");
                        params.put ("partyName",CompanyInputName.getText().toString ());
                        params.put ("partyType","Supplier");
                        params.put ("partyCategory",categoryModel.getCategoryName ());
                        params.put ("addressLine1",CompanyInputAddress.getText ().toString ());
                        params.put ("addressLine2","");
                        params.put ("city", String.valueOf (cityObject.getCityid ()));
                        params.put ("state", String.valueOf (stateObject.id));
                        params.put ("country", String.valueOf (countryObject.id));
                        params.put ("postalCode",CompanyInputPincode.getText ().toString ());
                        params.put ("aboutcompany","");

                        return params;
                    }
                };

                stringRequest.setRetryPolicy(new DefaultRetryPolicy(  10*1000, 0,
                        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

                //int socketTimeout = 500;
                //RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
                //stringRequest.setRetryPolicy(policy);
                mrequestQueue.add (stringRequest);

            }
        });

        getCountry ( );
        loadcat();

        SpinnerState.setOnItemSelectedListener (new AdapterView.OnItemSelectedListener ( ) {
            @Override
            public void onItemSelected(AdapterView <?> parent, View view, int pos, long l) {


                StateObject selected_state = (StateObject) parent.getSelectedItem ( );
                int cid = selected_state.id;
                city_List.clear ( );
                loadCity (cid);
            }



            private void loadCity(final int cid) {

                mrequestQueue = Volley.newRequestQueue (MainInfoActivity.this);
                StringRequest stringRequest = new StringRequest (Request.Method.POST, url3, new Response.Listener <String> ( ) {
                    @Override
                    public void onResponse(String response) {



                        try {

                            JSONObject jsonObject = new JSONObject (response);

                            JSONArray jsonArray = jsonObject.getJSONArray ("cityList");
                            Log.i (TAG, "Response : "+ jsonArray.toString ());
                            for (int p = 0; p<jsonArray.length (); p++) {
                                JSONObject feedobj3 = (JSONObject) jsonArray.get (p);
                                //int cid = feedobj3.getInt ("id");
                                CityObject cityObject = new CityObject ();
                                cityObject.setCityid (feedobj3.getInt ("cityid"));
                                cityObject.setCityname (feedobj3.getString ("cityname"));
                                city_List.add (cityObject);


                            }




                           cityObjectArrayAdapter  = new ArrayAdapter <> (MainInfoActivity.this, android.R.layout.simple_spinner_dropdown_item, city_List);
                            cityObjectArrayAdapter.setDropDownViewResource (android.R.layout.simple_spinner_dropdown_item);
                            SpinnerCity.setAdapter (cityObjectArrayAdapter);

                        } catch (JSONException e){

                            e.printStackTrace ();
                        }


                    }
                }, new Response.ErrorListener ( ) {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.i (TAG, "Response: "+ error.toString ());

                    }
                }

                ) {

                    @Override
                    protected Map <String, String> getParams() {
                        Map <String, String> map = new HashMap <> ();
                        map.put ("stateid",String.valueOf (cid));
                        return map;
                    }
                };
                int socketTimeout = 2000;
                RetryPolicy policy = new DefaultRetryPolicy (socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
                stringRequest.setRetryPolicy(policy);
                mrequestQueue.add (stringRequest);
            }




            @Override
            public void onNothingSelected(AdapterView <?> adapterView) {

            }
        });

        SpinnerCountry.setOnItemSelectedListener (new AdapterView.OnItemSelectedListener ( ) {
            @Override
            public void onItemSelected(AdapterView <?> adapterView, View view, int pos, long l) {


                    CountryObject selected_country = (CountryObject) adapterView.getSelectedItem ( );

                    int pid = selected_country.id;
                    loadState (pid);
                }


            private void loadState(final int pid) {

                mrequestQueue = Volley.newRequestQueue (MainInfoActivity.this);
                StringRequest stringRequest = new StringRequest (Request.Method.POST, url2, new Response.Listener <String> () {
                    @Override
                    public void onResponse(String response) {

                        try {

                            JSONObject jsonObject = new JSONObject (response);
                            JSONArray jsonArray = jsonObject.getJSONArray ("stateList");
                            state_List.clear ();
                            Log.i (TAG, "Response : "+ jsonArray.toString ());
                            for (int k = 0; k<jsonArray.length (); k++) {
                                JSONObject stateobj = (JSONObject) jsonArray.get (k);
                                StateObject stateObject = new StateObject ();
                                stateObject.setStateName (stateobj.getString ("stateName"));
                                stateObject.setId (stateobj.getInt ("id"));
                                state_List.add (stateObject);

                            }

                            StateAdapter = new ArrayAdapter <> (MainInfoActivity.this, android.R.layout.simple_spinner_dropdown_item, state_List);
                            StateAdapter.setDropDownViewResource (android.R.layout.simple_spinner_dropdown_item);
                            SpinnerState.setAdapter (StateAdapter);

                        } catch (JSONException e){

                            e.printStackTrace ();
                        }


                    }
                }, new Response.ErrorListener ( ) {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                        Log.i (TAG, "Response: "+ error.toString ());


                    }
                }

                ) {

                    @Override
                    protected Map <String, String> getParams() {
                        Map <String, String> params = new HashMap <> ();
                        params.put ("countryid",String.valueOf (pid));
                        return params;
                    }
                };
                int socketTimeout = 2000;
                RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
                stringRequest.setRetryPolicy(policy);

                mrequestQueue.add (stringRequest);


            }

            @Override
            public void onNothingSelected(AdapterView <?> adapterView) {

            }
        });

        }

    private void loadcat() {



            mrequestQueue = Volley.newRequestQueue (this);
          StringRequest  stringRequest = new StringRequest (Request.Method.GET, url1, new Response.Listener <String> ( ) {
                @Override
                public void onResponse(String response) {

                    try {

                        JSONObject jsonObject = new JSONObject (response);
                        JSONArray jsonArray = jsonObject.getJSONArray ("CustomerCategoryList");
                        Log.i (TAG, "Response : "+ jsonArray.toString ());
                        for (int j = 0; j<jsonArray.length (); j++) {
                            JSONObject feedobj1 = (JSONObject) jsonArray.get (j);
                            //categoryList.add (feedobj1.getString ("categoryName"));

                            Category_Model category_model = new Category_Model ();
                            category_model.setId (feedobj1.getInt ("id"));
                            category_model.setCategoryName (feedobj1.getString ("categoryName"));

                            categoryList.add (category_model);

                        }

                        category_modelArrayAdapter = new ArrayAdapter <> (MainInfoActivity.this, android.R.layout.simple_spinner_dropdown_item, categoryList);
                        category_modelArrayAdapter.setDropDownViewResource (android.R.layout.simple_spinner_dropdown_item);
                        SpinnerCat.setAdapter (category_modelArrayAdapter);
                    } catch (JSONException e){
                        e.printStackTrace ();
                    }

                }
            }, new Response.ErrorListener ( ) {
                @Override
                public void onErrorResponse(VolleyError error) {

                    Log.i (TAG, "Response: "+ error.toString ());

                }
            });
           int socketTimeout = 2000;
           RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
           stringRequest.setRetryPolicy(policy);
           mrequestQueue.add (stringRequest);
        }

    private void getCountry() {

        mrequestQueue = Volley.newRequestQueue (this);
        StringRequest stringRequest = new StringRequest (Request.Method.GET,url, new Response.Listener <String> ( ) {
            @Override
            public void onResponse(String response) {


                try {
                   JSONObject jsonObject = new JSONObject (response);
                    JSONArray jsonArray = jsonObject.getJSONArray ("countryList");
                    Log.i (TAG, "Response : "+ jsonArray.toString ());
                    for (int i = 0; i<jsonArray.length (); i++) {
                        JSONObject feedobj = (JSONObject) jsonArray.get (i);
                        CountryObject item = new CountryObject ();
                        item.setId (feedobj.getInt ("id"));
                        item.setCountryName (feedobj.getString ("countryName"));
                        country_list.add (item);

                    }
                    CountryAdapter = new ArrayAdapter <> (MainInfoActivity.this, android.R.layout.simple_spinner_dropdown_item, country_list);
                    CountryAdapter.setDropDownViewResource (android.R.layout.simple_spinner_dropdown_item);
                    SpinnerCountry.setAdapter (CountryAdapter);


                } catch (JSONException e) {
                    e.printStackTrace ( );
                }

            }
        }, new Response.ErrorListener ( ) {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText (getApplicationContext (),"Response Code", Toast.LENGTH_LONG).show ();

            }
        });
        int socketTimeout = 2000;
        RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        stringRequest.setRetryPolicy(policy);
        mrequestQueue.add (stringRequest);
    }

    @Override
    public void onBackPressed() {


        super.onBackPressed ( );
    }
}

2 个答案:

答案 0 :(得分:0)

I see no error else in the application code yet! maybe the solution can be something like this:

providing a separate runnable process to the spinner will solve the issue for reference check this

SpinnerCountry.post(new Runnable() {
        @Override
        public void run() {
            SpinnerCountry.setSelection(((ArrayAdapter<String>)SpinnerCountry.getAdapter()).getPosition(abcd));
        }
    });

if that does not work then I will recommend that you check first that either the adapter you are asking value from do possess the value in it or not and then got for setting it like this

String abcd = g.getStringExtra ("party_count");
for (int x = 0; x < SpinnerCountry.getAdapter().getCount(); x++) {
            if ((SpinnerCountry.getItemAtPosition(x)).equalsIgnoreCase(abcd)) {
              SpinnerCountry.setSelection(((ArrayAdapter<String>)SpinnerCountry.getAdapter()).getPosition("party_count"));
                break;
            }
        }

NOTE! set selection is a method to put the item on the top of spinner View from the items already in the array provided to the spinner.

as per your case I don't think so that you have any Array already filled in the spinner.

see this to fill spinner with xml array

or

attaching an arrayAdapter to Spinner using java

now that you are saying you have a list to fill out the spinner of yours then here is what you should do step by step.

  • 1: make sure you have the list of strings set up in java after getting the spinner registered
  • 2: find that if that list has the element incoming from your getIntent's StringExtra
  • 3: and if thats the case then update the list and make that item the top item in the list and after that attach that list into an array adapter and set that adapter on the spinner

答案 1 :(得分:0)

SpinnerCountry.setSelection(((ArrayAdapter)SpinnerCountry.getAdapter())为getPosition( “party_count”));

我认为一切正常,只需在SpinnerCountry.setSelection(x)中传递x;