how to set spinner list value first position showing empty - android

How to set spinner List first position value showing empty, i attached the adapter and activity: kindly resolve my problem.
SpinnerAdapterIdtypeMaster
public class SpinnerAdapterIdtypeMaster extends ArrayAdapter {
private Context mContext;
private List<CMSSubMasterDB> spinnerList = new ArrayList<>();
private MasterType type;
public SpinnerAdapterIdtypeMaster(#NonNull Context context, List<CMSSubMasterDB> list) {
super(context, 0, list);
mContext = context;
spinnerList = list;
}
#Override
public View getDropDownView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
#Override
public int getCount() {
return spinnerList.size();
}
#Nullable
#Override
public CMSSubMasterDB getItem(int position) {
return spinnerList.get(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItem = convertView;
if (listItem == null)
listItem = LayoutInflater.from(mContext).inflate(R.layout.spinner_list, parent, false);
CMSSubMasterDB currentMovie = spinnerList.get(position);
TextView name = (TextView) listItem.findViewById(R.id.spinner);
name.setText(currentMovie.name);
return listItem;
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
//return super.getView(position, convertView, parent);
View listItem = convertView;
if (listItem == null)
listItem = LayoutInflater.from(mContext).inflate(R.layout.spinner_list, parent, false);
TextView label = (TextView) listItem.findViewById(R.id.spinner);
label.setText(spinnerList.get(position).name);
return listItem;
}
}
CreateRyotManagerFragment
public class CreateRyotManagerFragment extends Fragment {
Spinner mIDType
List<CMSSubMasterDB> mIdtypeMasterList;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.layout_new_ryot, container, false);
mIDType = view.findViewById(R.id.idtype);
mIdtypeMasterList = AppUtils.getIDTypeMasterDb();
SpinnerAdapterIdtypeMaster idTypeMaster = new SpinnerAdapterIdtypeMaster(getActivity().getApplicationContext(), mIdtypeMasterList);
mIDType.setAdapter(idTypeMaster);
return view;
}
}

Try this code,
List<CMSSubMasterDB> mIdtypeMasterList = new List<CMSSubMasterDB>;
CMSSubMasterDB cmsdb = new CMSSubMasterDB();
cmsdb.setName("Select value");
mIdtypeMasterList.add(cmsdb);
List<CMSSubMasterDB> mIdList =AppUtils.getIDTypeMasterDb();
for (int i=0;i<mIdList.size();i++){
mIdtypeMasterList.add(mIdList.get(i));
}
SpinnerAdapterIdtypeMaster idTypeMaster = new
SpinnerAdapterIdtypeMaster(getActivity().getApplicationContext(),
mIdtypeMasterList);
mIDType.setAdapter(idTypeMaster);
mIDType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
mgetdatacall(position);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
private void mgetdatacall(int position) {
if(position != 0) {
mIdList.get(position - 1).getname();
}
}

Related

How do I retrieve the string value of my spinner's selected item?

In my spinner, I have the values 'Male', 'Female' and 'Male and female'. If someone clicks 'Male' in the spinner, I'd like to retrieve that value. My existing code which uses spinner.getSelectedItem().toString() provides the following result:
com.example.kitchen.SpinnerItem#64dd10e
I've even tried to implement .setOnItemSelectedListener() but that didn't work either. Main activity code:
public class ManageEventsActivity extends AppCompatActivity {
String stringCreateEventGender;
ArrayList<String> arrayUpcomingEventGender = new ArrayList<>();
ArrayList<SpinnerItem> mGenderList = new ArrayList<>();
SpinnerAdapter genderAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_events);
spinnerCreateEventGender = findViewById(R.id.spinnerCreateEventGender);
initGenderList();
genderAdapter = new SpinnerAdapter(this, mGenderList);
spinnerCreateEventGender.setAdapter(genderAdapter);
}
private void initGenderList() {
mGenderList.add(new SpinnerItem("Male"));
mGenderList.add(new SpinnerItem("Female"));
mGenderList.add(new SpinnerItem("Male and female"));
}
}
Spinner adapter code:
public class SpinnerAdapter extends ArrayAdapter<SpinnerItem> {
public SpinnerAdapter(Context context, ArrayList<SpinnerItem> genderList) {
super(context, 0, genderList);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
return initView(position, convertView, parent);
}
#Override
public View getDropDownView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
return initView(position, convertView, parent);
}
private View initView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.spinner_layout, parent, false
);
}
TextView textViewItem = convertView.findViewById(R.id.textViewItem);
SpinnerItem currentItem = getItem(position);
if (currentItem != null) {
textViewItem.setText(currentItem.getItem());
}
return convertView;
}
}
Spinner item code:
public class SpinnerItem {
String mItem;
public SpinnerItem(String item) {
mItem = item;
}
public String getItem() {
return mItem;
}
}
You need to cast object to its original type (also check if it is not null):
#Nullable Object selectedItem = spinner.getSelectedItem();
if (selectedItem != null) { // selectedItem is null if there is nothing selected
String item = ((SpinnerItem) selectedItem).getItem();
}
Or you should override the toString method in order to return value of the object:
public class SpinnerItem {
String mItem;
public SpinnerItem(String item) {
mItem = item;
}
public String getItem() {
return mItem;
}
#NonNull
#Override
public String toString() {
return mItem;
}
}
and then spinner.getSelectedItem().toString() will provides correct result.
Managed to find a solution:
spinnerCreateEventGender.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
spinnerItem = (SpinnerItem) parent.getItemAtPosition(position);
clickedItem = spinnerItem.getItem();
Toast.makeText(ManageEventsActivity.this, clickedItem, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

not getting the exact name to the spinner

hi I created two spinners and I given two different default values to the two spinners,but its taking only one value as the default, if I set only fromtext or totext its getting correctly, when I setting both its not taking. I'm not understanding where the fault occurs.
public class UniqueConverter extends Fragment {
private Spinner fromDetails, toDetails;
private EditText fromInput, toInput;
public static UniqueConverter setArguments(int position) {
UniqueConverter uniqueConverter = new UniqueConverter();
Bundle args = new Bundle();
args.putInt("position", position);
uniqueConverter.setArguments(args);
return uniqueConverter;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_uniquelayout, container, false);
int position = getArguments().getInt("position");
onInitVies(view);
switch (position) {
case 0:
setAdapter(getResources().getStringArray(R.array.temperatureform), "Celsius", "Fahrenheit");
break;
case 1:
setAdapter(getResources().getStringArray(R.array.weightform), "Kilograms", "Grams");
break;
return view;
}
private void setAdapter(String[] spinnerItems, String fromDefaultText, String toDefaultText) {
fromDetails.setAdapter(new CustomSpinnerAdapter(getContext(), R.layout.spinner_item, spinnerItems, fromDefaultText));
toDetails.setAdapter(new CustomSpinnerAdapter(getContext(),R.layout.spinner_item,spinnerItems,toDefaultText));
}
private void onInitVies(View view) {
fromDetails = (Spinner) view.findViewById(R.id.fromSpinner);
toDetails = (Spinner) view.findViewById(R.id.toSpinner);
fromInput = (EditText) view.findViewById(R.id.fromInput);
toInput = (EditText) view.findViewById(R.id.toInput);
}
}
my string-array:
<string-array name="temperatureform">
<item name="c">Celsius</item>
<item name="f">Fahrenheit</item>
<item name="k">Kelvin</item>
</string-array>
spinnerAdapter:
public class CustomSpinnerAdapter extends ArrayAdapter<String> {
Context context;
String[] objects;
String firstElement;
boolean isFirstTime;
public CustomSpinnerAdapter(Context context, int textViewResourceId, String[] objects, String defaultText) {
super(context, textViewResourceId, objects);
this.context = context;
this.objects = objects;
this.isFirstTime = true;
setDefaultText(defaultText);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
if (isFirstTime) {
objects[0] = firstElement;
isFirstTime = false;
}
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
notifyDataSetChanged();
return getCustomView(position, convertView, parent);
}
public void setDefaultText(String defaultText) {
this.firstElement = objects[0];
objects[0] = defaultText;
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.spinner_item, parent, false);
TextView label = (TextView) row.findViewById(R.id.text1);
label.setText(objects[position]);
return row;
}
}

How To pre-select value in Listview SingleChoice?

How to Preselect value in ListView Single Choice? Actually I am creating app where user have to select his work type like farmer etc.
And in my database user selected farmer now through this listview I am giving him to choice to change is type so that's why I have to show first what he selected first.
Here is my code.
public class UserTypeSettings extends AppCompatActivity {
private List<UserTypePrivacySettings> userTypePrivacySettingsList;
private ListView userTypeListView;
private int listpos;
public int getListpos() {
return listpos;
}
public void setListpos(int listpos) {
this.listpos = listpos;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_type_settings);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setActionbar();
initViews();
}
private void initViews() {
userTypeListView = (ListView) findViewById(R.id.userTypeListView);
userTypeListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
userTypePrivacySettingsList = new Parse(UserTypeSettings.this).parseUserType();
userTypeListView.setAdapter(new SingleChoiceArrayadapter(this, userTypePrivacySettingsList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
setListpos(position);
return super.getView(position, convertView, parent);
}
});
userTypeListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
userTypeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("check user stype", userTypePrivacySettingsList.get(position).getUser_type());
}
});
}}
Here is my adapter class
public class SingleChoiceArrayadapter extends ArrayAdapter<UserTypePrivacySettings> {
public SingleChoiceArrayadapter(Context context, List<UserTypePrivacySettings> usertypes) {
super(context, 0, usertypes);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_single_choice, parent, false);
}
UserTypePrivacySettings user = getItem(position);
final CheckedTextView textView = (CheckedTextView) super.getView(position, convertView, parent);
textView.setText(user.getUser_type());
textView.setTextColor(getResources().getColor(R.color.kisanColorGreen));
return convertView;
}
#Override
public long getItemId(int position) {
return getItem(position).getUser_type().hashCode();
}
#Override
public boolean hasStableIds() {
return true;
}
}
Here is how I set a pre-selected item on a Simple Adapter. But it should work the same as you have it now. If not let me know.
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_single_choice, android.R.id.text1, arrayList);
int selectedPosition;
userTypeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedPosition = position;
}
});
userTypeListView.performItemClick(userTypeListView.getAdapter().getView(position, null, null), position, position);

Using StickyGridHeaders

StickyGridHeaders, but its not working as it should, or at least as I want.
So I got this list with other lists inside, and with that i create a header list(I use the original list) and a full items list (all the subitems), and the call the adapter like so:
List<CalendarDate.CalendarTvShowEpisode> lista=new LinkedList<CalendarDate.CalendarTvShowEpisode>();
for(CalendarDate l:response){
lista.addAll(l.episodes);
}
setListAdapter(new WeekCalendarAdapter(getActivity(), weekCalendar,lista));
Then i have my Adapter:
public class WeekCalendarAdapter extends BaseAdapter implements StickyGridHeadersBaseAdapter {
private final List<CalendarDate> mListHeaders;
private final List<CalendarDate.CalendarTvShowEpisode> lista;
private LayoutInflater inflater;
public WeekCalendarAdapter(Context context, List<CalendarDate> mList, List<CalendarDate.CalendarTvShowEpisode> lista) {
this.mListHeaders = mList;
this.lista=lista;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return lista.size();
}
#Override
public Object getItem(int i) {
return lista.get(i);
}
#Override
public long getItemId(int i) {
return lista.get(i).episode.firstAired.getDay();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.calendarweek_item_episode, parent, false);
}
AQuery aq= new AQuery(convertView);
aq.id(R.id.imageViewCalendarEpisodeBackdrop).image(lista.get(position).episode.images.screen);
aq.id(R.id.textViewCalendartext).text(lista.get(position).episode.firstAired.getDay()+"");
return convertView;
}
#Override
public int getCountForHeader(int header) {
return mListHeaders.get(header).episodes.size();
}
#Override
public int getNumHeaders() {
return mListHeaders.size();
}
#Override
public View getHeaderView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.calendarweek_item, parent, false);
}
AQuery aq = new AQuery(convertView);
SimpleDateFormat format = new SimpleDateFormat("E MM dd, yyyy");
aq.id(R.id.textViewCalendarWeekDay).text(format.format(mListHeaders.get(position).date) + "");
return convertView;
}
The result I get is just a normal listview with all items ordered on below another, no gridview nor header.
What I'm a doing wrong?
Finally found out how to do it.
And the main problem is that it cant be a listfragment because, well listfragment has a listview. It has to be a Fragment and then your view need to have a com.tonicartos.widget.stickygridheaders.StickyGridHeadersGridView
So the code:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.calendarweek_fragment, container, false);
StickyGridHeadersGridView l = (StickyGridHeadersGridView) rootView.findViewById(R.id.listViewCalendar);
mAdapter = new WeekCalendarAdapter(getActivity(), weekCalendar, lista);
l.setAdapter(mAdapter);
return rootView;
}
And the View:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.tonicartos.widget.stickygridheaders.StickyGridHeadersGridView
android:id="#+id/listViewCalendar"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="160dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:gravity="left"
android:background="#color/calendar_background"/>
</LinearLayout>
My adapter
public class WeekCalendarAdapter extends BaseAdapter implements StickyGridHeadersBaseAdapter {
private final List<CalendarDate> mListHeaders;
private final List<CalendarDate.CalendarTvShowEpisode> lista;
private LayoutInflater inflater;
public WeekCalendarAdapter(Context context, List<CalendarDate> mList, List<CalendarDate.CalendarTvShowEpisode> lista) {
this.mListHeaders = mList;
this.lista = lista;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return lista.size();
}
#Override
public CalendarDate.CalendarTvShowEpisode getItem(int i) {
return lista.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.calendarweek_item_episode, parent, false);
}
//EDIT YOUR GRID ITEM HERE
return convertView;
}
#Override
public int getCountForHeader(int i) {
return mListHeaders.get(i).episodes.size();
}
#Override
public int getNumHeaders() {
return mListHeaders.size();
}
#Override
public View getHeaderView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.calendarweek_item, parent, false);
}
//EDIT YOUR VIEW HEADER HERE
return convertView;
}
}

Android Spinner OnItemSelected not firing when using custom child of ArrayAdapter

I have a custom implementation of an Array Adapter that I'm using in a Spinner to get a custom layout for my objects.
With the Custom array adapter in use, I have dialog appear with the spinner options, but none of them can be selected. I can use the back button to dismiss the dialog.
OnItemSelected is not being called. (When I use the back button, OnNothingSelected is not called either).
Here's some code:
Custom Adapter :
public class AboutSettingsServerAdapter extends ArrayAdapter <ServerItem> {
private ArrayList<ServerItem> mServers;
private Context mContext;
public AboutSettingsServerAdapter(Context context, int resource, ArrayList<ServerItem> serverItems) {
super(context, resource, serverItems);
mContext = context;
mServers = serverItems;
}
public int getCount(){
return mServers.size();
}
public ServerItem getItem(int position){
return mServers.get(position);
}
public long getItemId(int position){
return position;
}
public View getView (int position, View convertView, ViewGroup parent) {
return getAdapterView(position, convertView, parent);
}
public View getDropDownView (int position, View convertView, ViewGroup parent) {
return getAdapterView(position, convertView, parent);
}
public View getAdapterView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.spinner_item, null);
}
ServerItem item = mServers.get(position);
if (item!= null) {
TextView titleView = (TextView) view.findViewById(R.id.server_settings_title);
TextView subtitleView = (TextView) view.findViewById(R.id.server_settings_subtitle);
if (titleView != null) {
titleView.setText(item.title);
}
if (subtitleView != null) {
subtitleView.setText(item.url + "/" + item.path_extension);
}
}
return view;
}
}
Spinner initialization :
AboutSettingsServerAdapter adapter = new AboutSettingsServerAdapter(this, R.layout.module_about_server_spinner_item, servers);
adapter.setDropDownViewResource(R.layout.spinner_item);
adapter.notifyDataSetChanged();
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int index, long id) {
mSelectedServer = servers.get(index);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
My fix was to start from scratch and write a new ArrayAdapter and a new layout. For whatever reason this seemed to do it. Though I did not change my methodology at all.

Categories

Resources