How to get id From JSON in spinner ?
i want get city id, if i choose item in spinner
example : https://imgur.com/shvfvnO,
if i choose "ACEH BARAT", i'll get id "512"
public void displayCities(List<CityResponse.City> cities) {
for (CityResponse.City city : cities) {
Log.d(TAG, city.getNama());
spinnerItem.add(city.getNama());
adapter.notifyDataSetChanged();
}
}
private void setSpinner(Context context){
adapter = new ArrayAdapter<>(context, R.layout.spinner_item, spinnerItem);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mainBinding.spinnerCity.setAdapter(adapter);
mainBinding.spinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String citySelected = parent.getItemAtPosition(position).toString();
Toast.makeText(context, "City : " + citySelected, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(context, "Not Selected", Toast.LENGTH_LONG).show();
}
});
}
You need to create another arraylist to store id
locationId.add(i, response.getData());
now you need to get Id in spinner
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
try {
selectedId = (String) locationId.get(position);
} catch (Exception e) {
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
You need to update mainBinding.spinnerCity.setOnItemSelectedListener() inside setSpinnner() method as I have added below:
private void setSpinner(Context context){
adapter = new ArrayAdapter<>(context, R.layout.spinner_item, spinnerItem);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mainBinding.spinnerCity.setAdapter(adapter);
mainBinding.spinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Comment by Hari: You have already position available here so why you are doing this..
//String citySelected = parent.getItemAtPosition(position).toString();
/*Comment by Hari: If CityModel is the model of your cities ArrayList then it can be received inside spinner from the same index position as of the item as you are creating spinnerItemList in loop and both the list item position will be synced. */
CityModel cityModel = cities.get(position);
String citySelected = cityModel.getCity(); //Where cities is the main array in your activity class.
String cityId = cityModel.getCityId();
Toast.makeText(context, "City Name: " + citySelected + " // City Id: cityId" + , Toast.LENGTH_LONG).show();
//Do what you want to do next with the cityId here....
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(context, "Not Selected", Toast.LENGTH_LONG).show();
}
});
}
Change your onItemSelected like this
mainBinding.spinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String citySelected = parent.getItemAtPosition(position).toString();
for (CityResponse.City city : cities) {
if(city.getNama().equalsIgnoreCase(citySelected){
String city_id = city.getCityId(); //THIS IS YOUR CITY ID
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(context, "Not Selected", Toast.LENGTH_LONG).show();
}
});
Related
i have a spinner in add new data, I want the selected data to be an image in the item of recyclerview anyone knows how to make like that
like this but spinner that is from activity not item recycler view and thats the problem, how to get id spinner in adapter
holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
if (item == important){
holder.img_category.setImageResource(R.drawable.important);
}else if (item == notImportant){
holder.img_category.setImageResource(R.drawable.notimportant);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
use Glide for image set in imageView check below code.
add -> 'implementation 'com.github.bumptech.glide:glide:4.9.0' into your app.gradle
yes check that item getting your desired values using log and use
if(item.equalsIgnoreCase(important)) to check your if condition.
holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
log.e("TAG","Selected ITEM :"+item);
if(item.equalsIgnoreCase(important)){
Glide.with(context).load(R.drawable.important).into(holder.img_category); //here
}else if(item.equalsIgnoreCase(notImportant)){
Glide.with(context).load(R.drawable.notimportant).into(holder.img_category); // here
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Hi look updated answer
selectImageType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
{
if(i!=0)
{
selectedItem=binding.selectImageType.getSelectedItem().toString();
Log.e(TAG, "onItemSelected: "+selectedItem);
if(!selectedItem.equalsIgnoreCase(""))
{
spinnerDemoAdapter=new SpinnerDemoAdapter(dataImageList,selectedItem,SpinnerDemoActivity.this);
binding.recycleSpinnerDemo.setHasFixedSize(true);
binding.recycleSpinnerDemo.setLayoutManager(new LinearLayoutManager(SpinnerDemoActivity.this, RecyclerView.VERTICAL,false));
binding.recycleSpinnerDemo.setAdapter(spinnerDemoAdapter);
spinnerDemoAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
And this below is your adapter code
I take arraylist here and add random values for testing purpose
public SpinnerDemoAdapter(ArrayList<String> arrayList, String selectedItem, Context mContext) {
this.arrayList = arrayList;
this.selectedItem = selectedItem;
this.mContext = mContext;
}
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
if (!selectedItem.equalsIgnoreCase(""))
{
Log.e(TAG, "onBindViewHolder: "+selectedItem);
if (selectedItem.equalsIgnoreCase("important")) {
Glide.with(mContext).load(R.drawable.woman).into(holder.imageview);
} else if (selectedItem.equalsIgnoreCase("notimportant")) {
Glide.with(mContext).load(R.drawable.man).into(holder.imageview);
}
}
}
i use Retrofit,
item shown but i can't selected.
after clicking item, toast and spinner not show anything (i can't select item on spinner).......
private List<String> spinnerItem;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
spinnerItem = new ArrayList<>();
setSpinner();
}
public void displayCities(List<CityResponse.City> cities) {
mainBinding.helloText.setText(cities.get(508).getNama());
for (CityResponse.City city : cities) {
Log.d(TAG, city.getNama());
spinnerItem.add(city.getNama());
}
}
private void setSpinner(){
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, spinnerItem);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mainBinding.spinnerCity.setAdapter(adapter);
mainBinding.spinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String citySelected = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "City : " + citySelected, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(CityActivity.this, "Not Selected", Toast.LENGTH_LONG).show();
}
});
}
Current solution:
You set the adapter in the setSpinner() with a list called spinnerItem which is empty for this moment. Then in displayCities() you fill list with values but forget to notify the adapter about new values added.
public void displayCities(List<CityResponse.City> cities) {
for (CityResponse.City city : cities) {
spinnerItem.add(city.getNama());
}
// 2. notify adapter that you have inserted new cities to the list
}
private void setSpinner(){
// 1. set the adapter with spinnerItem which is empty here
ArrayAdapter<String> adapter = new ArrayAdapter<>(..., ..., spinnerItem);
mainBinding.spinnerCity.setAdapter(adapter);
...
}
If adapter is local variable for setSpinner() then displayCities() does not have access to the adapter. Create adapter as global and then you can call adapter.notiftDataSetChanged() in point 2 comment
Your setSpinner() method:
private void setSpinner(final Context context, Spinner spinnerCity, List<Object> spinnerItem) {
final ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_spinner_item, spinnerItem);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCity.setAdapter(adapter);
spinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String citySelected = parent.getItemAtPosition(position).toString();
//adapter.notifyDataSetChanged();
Toast.makeText(context, "City : " + citySelected, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(context, "Not Selected", Toast.LENGTH_LONG).show();
}
});
}
CityActivity.java:
Spinner spinnerCity = findViewById(R.id.spinner);
String[] spinnerItem = {"A", "B", "C", "D", "E"};
setSpinner(CityActivity.this, spinnerCity, Arrays.<Object>asList(spinnerItem));
I want to get the value of the selected item when I select the item in the list view.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String data = getText(position).toString();
Toast.makeText(Main2Activity.this,data,Toast.LENGTH_SHORT).show();
}
});
In this code, String data = getText(position).toString(), I get this error:
a String resource ID #0x0
This code is add listview
void DBadd() {
String name = addTxt1.getText().toString();
String info = addTxt2.getText().toString();
if (name.equals("") || info.equals("")) {
Toast.makeText(getApplicationContext(), "정보를 입력해 주세요", Toast.LENGTH_SHORT).show();
return;
} else {
db.execSQL("INSERT INTO tableName VALUES (null, '" + name + "', '" + info + "');");
Toast.makeText(getApplicationContext(), "추가 성공", Toast.LENGTH_SHORT).show();
addTxt1.setText(""); //입력시 EditText에 입력된값 지움
addTxt2.setText("");
cursor = db.rawQuery("SELECT * FROM tableName", null);
startManagingCursor(cursor); //엑티비티의 생명주기와 커서의 생명주기를 같게 한다.
adapter = new ArrayAdapter<String>(Main2Activity.this, android.R.layout.simple_list_item_1);
adapter2 = new ArrayAdapter<String>(Main2Activity.this, android.R.layout.simple_list_item_1);
while (cursor.moveToNext()) {
adapter.add(cursor.getString(1));
adapter2.add(cursor.getString(2));
}
listView.setAdapter(adapter);
listView2.setAdapter(adapter2);
}
}
How do I get the value of a selected item?
Try this, it works for me:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String data = listView.getItemAtPosition(position).toString();
Toast.makeText(Main2Activity.this,data,Toast.LENGTH_SHORT).show();
}
});
Or, just fetch the string value directly from adapter using .get(postion) like that :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String data = adapter.get(position);
Toast.makeText(Main2Activity.this,data,Toast.LENGTH_SHORT).show();
}
});
Good Luck
I'm not sure did i understood your question correctly, but let me guess the desired behavior:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView textViewOfTheClickedRaw = view.findViewById(android.R.id.text1);
String data = textViewOfTheClickedRaw.getText().toString();
Toast.makeText(Main2Activity.this, data, Toast.LENGTH_SHORT).show();
}
});
This is how you can get the value of TextView from android.R.layout.simple_list_item_1
But I really doesn't think this is how things should work in your app
Please i have a spinner in a CustomAdapterClass which extends ArrayAdapter. I want to save the state of the spinner even when the activity is destroyed. It is only one spinner that appears in a listview. I have searched but all i see is when there are more than one spinner, each having it's own id. How do i achieve this please. Here is my code
public class CustomListAdapterForCgpa extends ArrayAdapter<String> implements AdapterView.OnItemSelectedListener {
LinearLayout colorLayout;
TextView userGpScoreUneditable;
Spinner spinnerForGradePoints;
public String mathSubject= "Mathematics";
public String chemSubject = "Chemistry";
public String physicsSubject = "Physics";
public String biologySubject = "Biology";
public String gsSubject = "General Studies";
public String cscSubject = "CSC";
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
public CustomListAdapterForCgpa(Context context, ArrayList<String> subjects) {
super(context, R.layout.custom_list_view_cgpa, subjects);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
View customView = layoutInflater.inflate( R.layout.custom_list_view_cgpa,parent,false);
String singleSubject = getItem(position);
TextView singleText = (TextView) customView.findViewById(R.id.listSubjectsMyCoursesCgpa);
colorLayout = (LinearLayout)customView.findViewById(R.id.colorForSubjectsCgpa);
userGpScoreUneditable = (TextView)customView.findViewById(R.id.userGpScoreUneditable);
spinnerForGradePoints = (Spinner)customView.findViewById(R.id.spinnerForGradePointCgpa);
ArrayAdapter<String> gradePointAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, TabFirstSemesterMyCGPA.userSubjectGrade);
spinnerForGradePoints.setAdapter(gradePointAdapter);
spinnerForGradePoints.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String selectedItem = adapterView.getItemAtPosition(i).toString();
if (selectedItem.equals("A"))
{
Toast.makeText(getContext(), "You Clicked A", Toast.LENGTH_SHORT).show();
}else if ( selectedItem.equals("B"))
{
Toast.makeText(getContext(), "You Clicked B", Toast.LENGTH_SHORT).show();
}else if ( selectedItem.equals("C"))
{
Toast.makeText(getContext(), "You Clicked C", Toast.LENGTH_SHORT).show();
}else if ( selectedItem.equals("D"))
{
Toast.makeText(getContext(), "You Clicked D", Toast.LENGTH_SHORT).show();
}else if ( selectedItem.equals("E"))
{
Toast.makeText(getContext(), "You Clicked E", Toast.LENGTH_SHORT).show();
}else if ( selectedItem.equals("F"))
{
Toast.makeText(getContext(), "You Clicked F", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
singleText.setText(singleSubject);
colorLayout.setBackgroundColor(UserCourseSelection2.userSubjectsListColor.get(position));
return customView;
}
}
In pure Java you could save the state as a static field. The value will persist after the activity is destroyed because it belongs to the Class, not an instance. It should work the same in Android.
This is a very basic issue.
It is that, I have a basic Spinner implemented with a listener as below:
Spinner sensModeSpinner = (Spinner) findViewById(R.id.SensorModeSpinner);
ArrayAdapter<CharSequence> sensModeAdapter = ArrayAdapter.createFromResource(this, R.array.sensorMode_array, android.R.layout.simple_spinner_item);
sensModeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sensModeSpinner.setAdapter(sensModeAdapter);
sensModeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
sMode = parent.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(getBaseContext(), "You need to select atleast one mode!", Toast.LENGTH_SHORT).show();
}
});
Toast.makeText(getBaseContext(), "sensorMode = " + sMode, Toast.LENGTH_SHORT).show();
The issue is the sMode variable result is NOT appearing in the Toast message(value is NULL) where as it works fine within the OnItemSelected method.
Where am I going wrong?
you are executing the Toast.show(); method before the sMode value could be set, instead place this in onItemSelected() after setting sMode value, change your code to following:
Spinner sensModeSpinner = (Spinner) findViewById(R.id.SensorModeSpinner);
ArrayAdapter<CharSequence> sensModeAdapter = ArrayAdapter.createFromResource(this, R.array.sensorMode_array,
android.R.layout.simple_spinner_item);
sensModeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sensModeSpinner.setAdapter(sensModeAdapter);
sensModeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
sMode = parent.getItemAtPosition(pos).toString();
Toast.makeText(getBaseContext(), "sensorMode = " + sMode, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(getBaseContext(),
"You need to select atleast one mode!",
Toast.LENGTH_SHORT).show();
}
});
You can do this
Spinner sensModeSpinner = (Spinner) findViewById(R.id.SensorModeSpinner);
ArrayAdapter<CharSequence> sensModeAdapter = ArrayAdapter.createFromResource(this, R.array.sensorMode_array, android.R.layout.simple_spinner_item);
sensModeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sensModeSpinner.setAdapter(sensModeAdapter);
sensModeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
sMode = parent.getItemAtPosition(pos).toString();
//CALL_YOUR_FUNCTION_HERE
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(getBaseContext(), "You need to select atleast one mode!", Toast.LENGTH_SHORT).show();
}
});
some time may be it is silly mistake so try this..
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// sMode = parent.getItemAtPosition(pos).toString();
sMode = parent.getAdapter().getItemAtPosition(pos).toString();
}