2017-02-14 3 views
0

Я знаю, что есть много вопросов, связанных с моими вопросами, я смотрел на эти решения, но не мог получить помощь от них. Поэтому я задаю этот вопрос.Как добавить подсказку в spinner?

My app получает json данные от web-service. Ниже мой json результат

{"users":[{"Id":"1","Name":"Faisal"},{"Id":"2","Name":"Salman"},{"Id":"3","Name":"Asim"},{"Id":"4","Name":"Asad"},{"Id":"5","Name":"Mateen"},{"Id":"6","Name":"Omar"},{"Id":"7","Name":"Usama"}]} 

Из приведенных выше данных, отображающих я только Names в андроида блесны. Ниже мой Config.java код

public class Config { 

//JSON URL 
public static final String DATA_URL = "http://10.0.2.2:8000/MobileApp/index.php"; 

//Tags used in the JSON String 

public static final String TAG_NAME = "Name"; 

public static final String TAG_ID = "Id"; 

//JSON array name 
public static final String JSON_ARRAY = "users"; 

} 

Для MainActivity.java см ниже

public class MainActivity extends AppCompatActivity implements OnItemSelectedListener { 

//Declaring an Spinner 
private Spinner spinner; 

//An ArrayList for Spinner Items 
private ArrayList<String> users; 

//JSON Array 
private JSONArray result; 

//TextViews to display details 
private TextView textViewResult; 



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


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

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


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

    //Initializing TextView 

    textViewResult = (TextView)findViewById(R.id.textView); 

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

private 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 
         getUsers(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); 
} 

private void getUsers(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 

      users.add(json.getString(Config.TAG_NAME)); 
     } 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, users)); 

} 


//Method to get student name of a particular position 
private String getName(int position) 
{ 
    String name = ""; 
    try 
    { 
     //Getting object of given index 
     JSONObject json = result.getJSONObject(position); 
     //Fetching name from that object 
     name = json.getString(Config.TAG_NAME); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    return name; 
} 

//Method to get student Id of a particular position 
private String getId (int postion) 
{ 
    String Id=""; 
    try{ 
     JSONObject json = result.getJSONObject(postion); 

     Id = json.getString(Config.TAG_ID); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    return Id; 
} 

//this method will execute when we pic an item from the spinner 
@Override 
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 

    //Appending the values to textview for a selected item 
    // textViewResult.setText(""); 
    textViewResult.setText("Hi " + getName(position) + " your ID is " + getId(position)); 
} 

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

    textViewResult.setText(""); 

} 
} 

Когда я запустить приложение ниже результат показан

enter image description here

Я хочу каждый раз, когда я бегу app в сначала text в spinner будет как Select a name

В моем файле макета я сделал пытался android:hint="Select a name", но он не работает, так как не показывает мне ничего в блесны

enter image description here

Update 1 Как было предложено Selin Marvan K я сделал следующее

//Getting json object 
      JSONObject json = j.getJSONObject(i); 

      //Adding the name of the student to array list 
      users.add("Select a name"); 
      users.add(json.getString(Config.TAG_NAME)); 

Когда я запустил app, следующий результат показан

enter image description here

По предложению Selin Marvan K я следующее

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

    //Appending the values to textview for a selected item 
    // textViewResult.setText(""); 

    if(!getName(position).equals("select a name")) { 
     textViewResult.setText("Hi " + getName(position-1) + " your ID is " + getId(position-1)); 
    } 
    //textViewResult.setText("Hi " + getName(position) + " your ID is " + getId(position)); 
} 

Беллоу являются результатом которых я вижу

enter image description here

Он не должен показывать текст на первом запуске также в dropdown.

Он показывает мне мой намек, но в результате он все еще отображает мне первое имя и идентификатор. Когда я выбираю второе имя, отображается 3-е имя и идентификатор

Я не знаю, что делать.Любая помощь будет высоко оценен

+0

может быть, это может помочь HTTP : //stackoverflow.com/questions/20451499/android-spinne r-set-default-text –

+0

http://stackoverflow.com/questions/37810610/how-to-set-hint-text-for-spinner –

+0

Сообщите мне, работал ли он или нет. –

ответ

0

Я думаю, что вертушка нет никакого намека на

Но у меня есть небольшое решение

ваш код

users.add(json.getString(Config.TAG_NAME));//this will add name to user array list 

, прежде чем добавить имена пользователей в ArrayList, введите ниже код

ie.add ваш совет в массив

users.add("your hint"); 
eg:users.add("select name"); 

я думаю, что это поможет вам

+0

Хорошо, я попробую и дам вам знать – faisal1208

+0

Это не помогло мне, все это показывает мне пустой прядильщик – faisal1208

+0

Извините, мой плохой, мой сервер 'xampp' не работал, любезно посмотрите обновление – faisal1208

0

использовать, если условие

if(!getName(posission).equals("select a name")) 
{ 
    textViewResult.setText("Hi " + getName(position-1) + " your ID is " + getId(position-1)); 
}   
+0

В какой момент я бы использовал его? – faisal1208

+0

положить код В функции onItemSelected() –

0

В onItemSelected функции()

public void onItemSelected(AdapterView<?> parent, View view, int position,long id) { 
//Appending the values to textview for a selected item 
// textViewResult.setText(""); 
    if(!getName(posission).equals("select a name")) 
    { 
    textViewResult.setText("Hi " + getName(position-1) + " your ID is " + getId(position-1)); 
    } }                             
+0

ok позвольте мне попробовать, я скажу вам – faisal1208

+0

проверить мой обновленный вопрос – faisal1208