2016-03-29 2 views
-1

Я новичок в приложениях для Android. мне нужна помощь я делаю это за последние 4 дняЗаполнение базы данных spinner на территории страны с помощью Mysql в студии android

если выбрать Мумбай, то второй кок должен отображать уважаемое pickup_point_cd (показать 4 значения не аэропорта значение: D)

enter image description here

общественный класс MainActivity расширяет AppCompatActivity реализует Spinner.OnItemSelectedListener {

//Declaring an Spinner 
public Spinner spinner; 
public Spinner spinner1; 

//An ArrayList for Spinner Items 
public ArrayList<String> students; 
public ArrayList<String> students1; 


//JSON Array 
public JSONArray result; 
public JSONArray result1; 

//TextViews to display details 
private TextView textViewName; 
private TextView textViewCourse; 
private TextView textViewSession; 

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

    //Initializing the ArrayList 
    students = new ArrayList<String>(); 
    students1 = new ArrayList<String>(); 

    //Initializing Spinner 
    spinner = (Spinner) findViewById(R.id.spinner); 
    spinner1 = (Spinner) findViewById(R.id.spinner2); 


    //Adding an Item Selected Listener to our Spinner 
    //As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener 
    spinner.setOnItemSelectedListener(this); 
    spinner1.setOnItemSelectedListener(this); 

    //Initializing TextViews 
    textViewName = (TextView) findViewById(R.id.textViewName); 
    textViewCourse = (TextView) findViewById(R.id.textViewCourse); 
    textViewSession = (TextView) findViewById(R.id.textViewSession); 

    //This method will fetch the data from the URL 
    getData(); 
    getData1(); 



} 

public void getData(){ 
    //Creating a string request 
    StringRequest stringRequest = new StringRequest(Config.DATA_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(Config.JSON_ARRAY); 

         //Calling method getStudents to get the students from the JSON Array 
         getStudents(result); 
        } 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); 
} 

public void getStudents(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 
      students.add(json.getString(Config.TAG_USERNAME)); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

public void getData1() { 
    //Creating a string request 
    StringRequest stringRequest = new StringRequest(Config.DATA2_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 
         result1 = j.getJSONArray(Config.JSON_ARRAY2); 

         //Calling method getStudents to get the students from the JSON Array 
         getStudents1(result1); 
        } 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); 
} 

public void getStudents1(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 
      students1.add(json.getString(Config.TAG_CD)); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 

    //Setting adapter to show the items in the spinner 
    spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, students)); 
    spinner1.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, students1)); 

} 
+0

проверки этого : http://www.androidhive.info/2012/06/android-populating-spinner-data-from-sqlite-database/ – David

+0

httpclient устарел .. :( – ATKT

+1

https://www.simplifiedcoding.net/android-spinner -example-to-load-json-using-volley/i следую этому руководству ... @David bro, пожалуйста, помогите мне :) – ATKT

ответ

0

Во-первых, вы должны сделать веб-службы или веб-интерфейс для извлечения требуемого йа ta для прядильщиков в приложении android из вашего MySQL. После этого вы можете получать данные через веб-сервис. Сделайте 2 веб-службы differnet для данных с двумя разбросами. Для справки вы можете использовать этот учебник .... enter link description here

Если вы сделаете это, я предоставлю вам код, как установить данные второго счетчика на значение выбора первого счетчика. Вот код .....

Remove this lines first.. 
//Setting adapter to show the items in the spinner 
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, students)); 
spinner1.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, students1)); 

и добавьте следующие строки кода после метода GetData()

ArrayList<String> cityList_final = new ArrayList<String>(); 
     cityList_final .add("Select Item"); 
     cityList_final .addAll(students); 
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, cityList_final)); 

     spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 

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

       spinnerSelectedItem= spinner.getItemAtPosition(pos).toString(); 
if(spinnerSelectedItem.equalsIgnoreCase("Select Item")==false) {     
// call here your getData1 method and pass spinnerSelectedItem in url to fetch data according to spinnerSelectedItem.//donot call getData1 method in onCreate 
        getData1(spinnerSelectedItem); 

      } 

       setSecondSpinner(); 
      } 

      public void onNothingSelected(AdapterView<?> arg0) { 

      } 
     }); 
public void setSecondSpinner() 
{ 
ArrayList<String> pickPointList_final = new ArrayList<String>(); 
    pickPointList_final .add("Select Item"); 
     pickPointList_final .addAll(students1); 

spinner1.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, pickPointList_final)); 
    spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 

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


      spinnerSelectedItem1= spinner1.getItemAtPosition(arg2).toString(); 


     } 

     public void onNothingSelected(AdapterView<?> arg0) { 

     } 
    }); 

} 

Надежда это поможет вам .....

+0

Работающий, но неполный проверить это http://i.stack.imgur.com/pYTDn.png – ATKT

+0

У меня есть обновленный ответ ... проверьте это ... –

+0

Позвольте мне проверить bro :) – ATKT

Смежные вопросы