0

I know there are lot of questions related to my questions, i looked at those solutions but couldn't able to get help from them. So that's why i am posting this question.

My app is getting a json data from a web-service. Below is my json result

{"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"}]}

From the above data i am displaying only Names in an android spinner. Below is my Config.java code

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";

}

For MainActivity.java see below

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("");

 }
}

When i run the app the below result is shown

enter image description here

I want is whenever i run app the first text in the spinner would be like Select a name

In my layout file i did tried android:hint="Select a name" but it didn't work as it shows me nothing in the spinner

enter image description here

Update 1 As suggested by Selin Marvan K i have done the following

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

When i run the app following result is shown

enter image description here

On the suggestion of Selin Marvan K i have the following

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

Bellow are the result which i am seeing

enter image description here

It should not show an text on first run also in dropdown.

It does show me my hint but in result it still displaying me the first name and id. When i select the second name the 3rd name and id is displaying

I don't know what to do. Any help would be highly appreciated

Moeez
  • 494
  • 9
  • 55
  • 147

3 Answers3

0

I think spinner have no hint

But i have small solution

your code is

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

before add user names to arraylist, put below code

ie.add your hint to your array

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

i think it will help you

0

use if condition

if(!getName(posission).equals("select a name"))
{
    textViewResult.setText("Hi " + getName(position-1) + " your ID is " + getId(position-1));
}        
Komal12
  • 3,340
  • 4
  • 16
  • 25
0

In onItemSelected() function

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