Search code examples
androidarraylistandroid-spinnerbaseadapterpojo

How to set default Text in Android Spinner


I am displaying values in spinner. I want to display default text like "Select Table". Here's my code

    JSONArray tablearray = tablenamejson.getJSONArray("data");
    for (int i = 0; i < tablearray.length(); i++) {
    JSONObject jsonObject = tablearray.getJSONObject(i);
    String table_id = jsonObject.getString(TAG_TABLE_ID);
    String table_name = jsonObject.getString(TAG_TABLE_NAME);
    ArrayList<TableData> tableDatas = new ArrayList<TableData>();
    TableData tables = new TableData();
    tables.setTblId(table_id);
    tables.setTblName(table_name);
    tableDatas.add(tables);
    }

    adapter = new TableAdapter(tableDatas, getActivity());
    spinner.setAdapter(adapter);

Solution

  • first of all you should declare

    ArrayList<TableData> tableDatas = new ArrayList<TableData>();
    

    outside forloop as you are adding all the entries in that list

    add your default value first inside list then write forloop for adding all the values in json array and then use spinner.setSelection(0); method to show defult value in spinner as you have added it in 1st position in an array

    following is code

    ArrayList<TableData> tableDatas = new ArrayList<TableData>();
    
    //for default value
    TableData tables = new TableData();
    tables.setTblId(0);
    tables.setTblName("Select");
    tableDatas.add(tables);
    
    JSONArray tablearray = tablenamejson.getJSONArray("data");
    for (int i = 0; i < tablearray.length(); i++) {
      JSONObject jsonObject = tablearray.getJSONObject(i);
      String table_id = jsonObject.getString(TAG_TABLE_ID);
      String table_name = jsonObject.getString(TAG_TABLE_NAME);
      TableData tables = new TableData();
      tables.setTblId(table_id);
      tables.setTblName(table_name);
      tableDatas.add(tables);
    }
    
    adapter = new TableAdapter(tableDatas, getActivity());
    spinner.setAdapter(adapter);
    spinner.setSelection(0);