karthiventure karthiventure - 5 months ago 31
Java Question

How to set "hint text" for spinner?

The value of the Spinner from Database. I am confusing to add hint for Spinner, I followed some posts in SO but i am struck with this place and I Tried this

Spinner sp = (Spinner)findViewById(R.id.spinner);
sp.setSelection(pos);


the position have Integer value so i give it as a Integer value for position,also i try with getCount() inside of setSeletction() method

main.java

//spinner for customer
sp=(Spinner)findViewById(R.id.spinner);
adapter=new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.txt,listItems);
sp.setAdapter(adapter);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sales_order);
cus_name = (Spinner) findViewById(R.id.spinner);//customer spinner

// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

//spinner for customer
sp=(Spinner)findViewById(R.id.spinner);
adapter=new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.txt,listItems);
sp.setAdapter(adapter);


}

private class BackTask extends AsyncTask<Void,Void,Void> {
ArrayList<String> list;
protected void onPreExecute(){
super.onPreExecute();
list=new ArrayList<>();
}
protected Void doInBackground(Void...params){
InputStream is=null;
String result="";
try{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost= new HttpPost("http://IP/web_services/customer_spinner.php");
HttpResponse response=httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
}catch(IOException e){
e.printStackTrace();
}

//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result+=line;
}
is.close();
//result=sb.toString();
}catch(Exception e){
e.printStackTrace();
}
// parse json data
try{
JSONObject object = new JSONObject(result);
JSONArray jArray = object.getJSONArray("cus_Name");
//JSONArray jArray =new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject jsonObject=jArray.getJSONObject(i);
// add interviewee name to arraylist
list.add(jsonObject.getString("cus_Name"));
}
}
catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result){
listItems.addAll(list);
adapter.notifyDataSetChanged();
}
}

Answer

There are lot of way :

1.) Android Hint Spinner

Use this dependency in build.gradle file.

dependencies {
    compile 'me.srodrigo:androidhintspinner:1.0.0'
}

Output :

enter image description here

for more detail visit this : https://github.com/srodrigo/Android-Hint-Spinner

2.) second Way

visit here : https://github.com/ravivyas84/AndroidSpinnerHint