2017-01-25 4 views
0

У меня есть 3 spinner в моей Home Activity.If, я выбираю 1 другой должен измениться в соответствии с 1-м spinner.I есть страна, город и местоположение, как spinner, если я выбираю страну, тогда город и местоположение должны измениться в соответствии с этим. удастся получить элемент страны в spinner (элемент из базы данных). Теперь, как получить только выбранный элемент в spinner..im confused. ?? здесь мой дом активность (где я получаю вращателя (страна) пункт):Как получить элемент spinner на выбор предыдущего счетчика в android?

public class Home extends AppCompatActivity implements AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener { 

    private Spinner countrySpinner, locationSpinner, citySpinner; 
    private TextView cityCodeTextView; 
    private Button submitButton; 
    private ArrayList<String> country_list, location_list, city_list; 
    private JSONArray result; 
    ProgressDialog progressDialog; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_home); 

     countrySpinner = (Spinner) findViewById(Country); 



     //citySpinner = (Spinner) findViewById(City); 
     //locationSpinner = (Spinner) findViewById(R.id.Location); 
     countrySpinner .setOnItemSelectedListener(this); 

     country_list = new ArrayList<String>(); 

     //location_list = new ArrayList<String>(); 
     // city_list = new ArrayList<String>(); 

     getData(); 
    } 
    private void getData(){ 
     StringRequest 
       stringRequest = new StringRequest(Config.DATA_URL, 
       new Response.Listener<String>() { 
        @Override 
        public void onResponse(String response) { 
         JSONObject j = null; 
         try { 
          Log.d("Test",response); 
          JSONArray result = new JSONArray(response); 
          //Calling method getCountry to get the Country from the JSON Array 
          getCountry(result); 
         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 
        } 
       },new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
      }}); 
     RequestQueue requestQueue = Volley.newRequestQueue(this); 
     //Adding request to the queue 
     requestQueue.add(stringRequest); 
    } 
    private void getCountry(JSONArray jsonArrayCountry){ 
     //Traversing through all the items in the json array 
     List<Country> countries = new ArrayList<>(); 
     try { 
      String country_name, country_code; 
      JSONObject countries_object; 
      for (int i = 0; i < jsonArrayCountry.length(); i++) { 
       countries_object = jsonArrayCountry.getJSONObject(i); 
       country_code = countries_object.getString("id"); 
       country_name = countries_object.getString("country"); 
       countries.add(new Country(country_code, country_name)); 
      } 
      ArrayAdapter countryAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, countries); 
      countrySpinner.setPrompt("--Select Country--"); 
      countrySpinner.setAdapter(countryAdapter); 
      countrySpinner.setAdapter(new NothingSelectedSpinnerAdapter(countryAdapter, 
          R.layout.contact_spinner_row_nothing_selected,this)); 
      countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
       @Override 
       public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 

       } 
       @Override 
       public void onNothingSelected(AdapterView<?> arg0) { 
       } 
      }); 

     } catch (JSONException e) { 
      Log.e("Home", e.getLocalizedMessage(), e); 
     } 
    } 
    @Override 
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 
     //Setting the values to textviews for a selected item 
     //textViewName.setText(getName(position)); 
     //textViewCourse.setText(getCourse(position)); 
     //textViewSession.setText(getSession(position)); 
    } 

    //When no item is selected this method would execute 
    @Override 
    public void onNothingSelected(AdapterView<?> parent) { 
     // textViewName.setText(""); 
     // textViewCourse.setText(""); 
     //textViewSession.setText(""); 
    } 

    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 

    } 
} 

это Country.java

public class Country { 

     private String name; 
     private String id; 

     public Country(String id, String name) { 
      this.name = name; 
      this.id = id; 
     } 

     public String getName() { 
      return name; 
     } 

     public String getId() { 
      return id; 
     } 
    @Override 
     public String toString() { 
      return name; 
     } 
    } 

это City.java

public class City { 

    private String name; 



    public String getName() { 
     return name; 
    } 



    @Override 
    public String toString() { 
     return name; 
    } 
} 

это is Location.java

public class Location { 

    private String name; 



    public String getName() { 
     return name; 
    } 



    @Override 
    public String toString() { 
     return name; 
    } 
} 

это Config.java

public class Config { 
    //JSON URL 
    public static final String DATA_URL = "http://demo5...../get_country.php"; 

    public static final String DATA_URL1 = "http://demo5...../get_jsoncity.php?id="; 

    //Tags used in the JSON String 

public static final String DATA_URL2 = "http://demo5...../get_jsonlocation.php?id="; 

    //Tags used in the JSON String 
    //JSON array name 
    public static final String JSON_ARRAY = "result"; 

} 

это мой 1-й для JSON блесны:

[ 
    { 
    "id": "1", 
    "country": "UAE" 
    }, 
    { 
    "id": "2", 
    "country": "UK" 
    }, 
    { 
    "id": "3", 
    "country": "SAUDI ARABIA" 
    }, 
    { 
    "id": "4", 
    "country": "OMAN" 
    }, 
    { 
    "id": "5", 
    "country": "BAHRAIN" 
    }, 
    { 
    "id": "6", 
    "country": "INDIA" 
    } 
] 

это для города, если я выбран ID = 1

[ 
    { 
    "id": "1", 
    "city_name": "Abu Dhabi" 
    }, 
    { 
    "id": "2", 
    "city_name": "Dubai" 
    }, 
    { 
    "id": "3", 
    "city_name": "Sharjah" 
    }, 
    { 
    "id": "4", 
    "city_name": "Ajman" 
    }, 
    { 
    "id": "5", 
    "city_name": "Ummal Qwain" 
    } 
] 

Я уже получаю 1-й счетчик, т. Е. Страна, мне нужно получить предмет для города (2-й счетчик) и место (3-й счетчик) по выбору 1-го счетчика.

+0

посмотреть учебник; http://www.androidhive.info/2013/12/android-populating-spinner-data-from-mysql-database/ – rafsanahmad007

+0

да, я видел это, но мне нужно 3 spinner ..thts для 1 –

+0

, если я выберу 1 другое 2 shud получить выбранный элемент с сервера n не все item –

ответ

0

Ваш country.class должен иметь геттер-сеттер города и его местоположения.

public class Country { 
     private String name; 
      private String id; 
private Location loc; 
     ArrayList<City> Cityarr = new ArrayList<City>(); 

     public ArrayList<City> getCityarr() { 
      return Cityarr; 
     } 

     public void setCityarr(ArrayList<City> Citya) { 
      this.Cityarr = Citya; 
     } 

     public Country(String id, String name) { 
       this.name = name; 
       this.id = id; 
      } 

      public String getName() { 
       return name; 
      } 

      public String getId() { 
       return id; 
      } 
public Location getLocation() { 
     return loc; 
    } 
     @Override 
      public String toString() { 
       return name; 
      } 
     } 

и spinner.OnItemSelectedLisenter должны вложенными

country.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
        @Override 
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { 
         vbopr.get(i).getCityarr().size(); 

         cityname.clear(); 
         cityname.add("All"); 
         for (int j = 0; j < vbopr.get(i).getCityarr().size(); j++) { 
          cityname.add(vbopr.get(i).getCityarr().get(j).getCityname()); 
         } 
         try { 
          adpcity.notifyDataSetChanged(); 
         } catch (NullPointerException ne) { 

         } 
         adpcity = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_items, cityname); 
         city.setAdapter(adpcity); 

        } 

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

        } 
       }); 

мой URL содержит данные в XML-форме например

<world> 
<country> 
<countryid>2</countryid> 
<countryname>India</countryname> 
<city> 
<city_id>1462</city_id> 
<city_name>abc</city_name> 
</city> 

<city> 
<city_id>1460</city_id> 
<city_name>def</city_name> 
</city> 

<city> 
<city_id>1461</city_id> 
<city_name>jkl PLANT</city_name> 
</city> 

</country> 

<country> 
<countryid>3</countryid> 
<countryname>Australia</countryname> 
<city> 
<city_id>1462</city_id> 
<city_name>gdfg PLANT</city_name> 
</city> 

<city> 
<city_id>1460</city_id> 
<city_name>xdfPLANT</city_name> 
</city> 

<city> 
<city_id>1461</city_id> 
<city_name>dfgPLANT</city_name> 
</city> 

<city> 
<city_id>617</city_id> 
<city_name>dgvdfgg</city_name> 
</city> 
</country> 
</world> 
+0

вы хотите сказать один элемент выбран, мы можем получить все предметы из 3-х прядильщиков. –

+0

может объяснить, как мы можем отображать данные с url –

+0

, так как у меня есть 3 url в config.java ..do мне нужно сделать только файл php ... как im little confused can u tell me .. –

0

попробовать это:

spinner_1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 

       @Override 
       public void onItemSelected(AdapterView<?> arg0, View arg1, 
              int position, long arg3) { 

        if (spinner_1.getSelectedItem().equals("UAE")) { 

         //cal api url here to get data 
         // set adapter to spinner_2 here for "UAE" selected 

        } else if (spinner_1.getSelectedItem().equals("UK")) { 
         //same.. 
        } 
       } 


       @Override 
       public void onNothingSelected(AdapterView<?> arg0) { 
       } 
      } 
    ); 
+0

no i can not do it tht way..имя страны может быть изменено ..i can not take hardcoded name –

+0

У вас есть какой-нибудь пример, например, если вы щелкните страну в spinner u получите элемент в других 2 spinner динамически –

+0

@ z.al да ... но в вашем случае это другое. Я думаю, что если вы хотите, чтобы ваш выбор был динамическим ... вы можете просто передать первое выбранное значение spinner на сервер .. и на стороне сервера вы можете вернуть соответствующий JSON respnse для другой spinner ... – rafsanahmad007