I have created a spinner with a custom Adapter. I am trying to the preselected items on the following spinner. I am not able to get the position of the text.
This is my class:
public class Spinner {
private String id;
private String name;
public Spinner(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
#Override
public boolean equals(Object obj) {
if(obj instanceof Spinner){
Spinner c = (Spinner )obj;
return c.getName().equals(name) && c.getId().equals(id);
}
return false;
}
}
And I am setting the data in the spinner through :
ArrayAdapter<Spinner> vehicle_type_adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, vehicle_type_list);
spinner.setAdapter(vehicle_type_adapter)
How can I get the position of the name from it. Thanks
You can set AdapterView.OnItemSelectedListener:
spinner.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Spinner currentItem= vehicle_type_list[position]
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
);
Related
In my app I have a recycler view that holds a name and address of a restaurant and I just tried to add a rating bar to it and I get all the data from SQL database and I use volley for connecting to it, every thing works fine and I can even send a rating for a restaurant but when I try to get the data I get 0
and I checked the REST API and Json, when I set the rating with a final value without database in my Recycler adapter class It works but when I try to set the data in my MainActivity and geting it in my on bindview holder it gets 0 please help
MainActivty
public void sendRequest(){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, request_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
restaurants.clear();
for (int i = 0; i < response.length(); i++) {
Restaurant restaurant = new Restaurant();
try {
JSONObject jsonObject = response.getJSONObject(i);
restaurant.setId(jsonObject.getInt("restaurant_id"));
restaurant.setName(jsonObject.getString("restaurant_name"));
restaurant.setAddress(jsonObject.getString("restaurant_address"));
restaurant.setImage(jsonObject.getInt("restaurant_image_type"));
restaurant.setHasNote(jsonObject.getBoolean("restaurant_has_note"));
restaurant.setRating((float) jsonObject.getInt("restaurant_rating"));
swipeRefreshLayout.setRefreshing(false);
} catch (JSONException e) {
swipeRefreshLayout.setRefreshing(false);
Log.i("VolleyGetError",e.toString());
e.printStackTrace();
}
restaurants.add(restaurant);
adapter.notifyDataSetChanged();
shimmerContainer.stopShimmerAnimation();
shimmerContainer.setVisibility(View.GONE);
}
fastfoodRecyclerView.setAdapter(adapter);
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley Error:", String.valueOf(error));
}
});
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(jsonArrayRequest);
}
My POJO class
public Restaurant() {
}
public Restaurant(String name, String address,int type){
this.name = name;
this.address = address;
this.type = type;
}
public Restaurant(int id, String name, String address,int type){
this.id = id;
this.name = name;
this.address = address;
this.type = type;
}
public Restaurant(int id, String name, String address, int type,int image,int count) {
this.id = id;
this.name = name;
this.address = address;
this.type = type;
this.image = image;
this.count = count;
}
public Restaurant(int id, String name, String address, int type,int image,int count,float rating) {
this.id = id;
this.name = name;
this.address = address;
this.type = type;
this.image = image;
this.count = count;
this.rating = rating;
}
public float getRating() {
return rating;
}
public int getCount() {
return count;
}
public void setRating(float rating) {
this.rating = rating;
}
public void setCount (int count) {this.count = count;}
public int getId() { return id;}
public void setId (int id) { this.id = id;}
public String getName() {
return name;
}
public void setName(String name) { this.name = name;}
public boolean isHasNote(){
return hasNote;
}
public void setHasNote(boolean hasNote){
this.hasNote = hasNote;
}
public String getAddress() { return address;}
public void setAddress(String address) { this.address = address;}
public void setType(int type) {this.type = type;}
public int getType() {return type;}
public int getImage() {return image;}
public void setImage(int image) {this.image = image;}
}
my Recycler Adapter class
TextView listviewName,listviewAddress;
ImageView icon,noteIcon,deleteicon;
RelativeLayout viewBackground, viewForeground;
RatingBar ratingBar;
MyViewHolder(View view){
super(view);
ratingBar = view.findViewById(R.id.rating_bar);
listviewName = view.findViewById(R.id.listview_name);
listviewAddress = view.findViewById(R.id.listview_address);
icon = view.findViewById(R.id.type_ic);
noteIcon = view.findViewById(R.id.note_icon);
deleteicon = view.findViewById(R.id.delete_icon);
deleteicon.setVisibility(View.GONE);
viewBackground = view.findViewById(R.id.view_background);
viewForeground = view.findViewById(R.id.view_foreground);
view.setOnCreateContextMenuListener(this);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onRestaurantSelected(restaurantListFiltered.get(getAdapterPosition()));
}
});
}
#Override
public void onCreateContextMenu(ContextMenu menu,View v,ContextMenu.ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
menu.add(0, 1, 0, "Edit");
menu.add(0, 2, 1, "Remove");
menu.add(0, 3, 2, "Add Note");
menu.add(0, 4, 3, "All Notes");
}
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
Animation animation = AnimationUtils.loadAnimation(context, R.anim.fadein);
itemView.startAnimation(animation);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
setPosition(holder.getAdapterPosition());
return false;
}
});
Restaurant restaurant = restaurantList.get(position);
holder.listviewName.setText(restaurant.getName());
holder.listviewAddress.setText(restaurant.getAddress());
holder.ratingBar.setRating(restaurant.getRating());
switch (restaurant.getImage()) {
case RestaurantContract.EntryRestaurants.RESTAURANT_TYPE_DELIVERY:
holder.icon.setImageResource(R.drawable.phoneorderr);
break;
case RestaurantContract.EntryRestaurants.RESTAURANT_TYPE_SITDOWN:
holder.icon.setImageResource(R.drawable.sitdownn);
break;
case RestaurantContract.EntryRestaurants.RESTAURANT_TYPE_TAKEAWAY:
holder.icon.setImageResource(R.drawable.takeaway);
break;
}
holder.noteIcon.setImageResource(R.drawable.notepadicon);
if(restaurant.isHasNote()) {
holder.noteIcon.setVisibility(View.VISIBLE);
}else {
holder.noteIcon.setVisibility(View.INVISIBLE);
}
}
My json
{
"restaurant_id": "97",
"restaurant_name": "tt",
"restaurant_address": "rr",
"restaurant_type": "0",
"restaurant_has_note": "0",
"restaurant_image_type": "2",
"restaurant_rating": "3"
}
]
Firstly, you've your POJO class as Restaurant. Add below value to your rating field
public Restaurant(){
public float rating = 0.0f;
}
Secondly, you'll need to listen your rating bar changes on your MyViewHolder like below:
ratingBar = (RatingBar) view.findViewById(R.id.rating_bar);
ratingBar .setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
restaurants.get(getPosition()).rating = ratingBar.getRating();
}
});
I see you've already implemented an arraylist with the name of restaurantList, i've still mentioned the implementation below for reference:
Then in your Adapter you'll have to implement an arraylist to fetch the data for your ratingBar
static List<Restaurant> restaurants= new ArrayList<>(); //restaurantList in your
Initiate it in your constructor.
this.restaurants = restaurants;//restaurantList in your case
Then in your onBindViewHolder
List<String> restro= new ArrayList<String>();
for(int i=0;i<restaurants.size();i++){
restro.add(String.valueOf(restaurants.rating));//restaurantList in your case
}
Hope that helps.
Is there any way to update certain List data from RecyclerView.Adapter class
here is my List class:
public class Idea {
private String id, name, voted;
public Idea(String id, String name, String voted) {
this.id = id;
this.name = name;
this.voted = voted;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getVoted() {
return voted;
}
}
my RecyclerView Adapter class:
public class IdeaListAdapter extends RecyclerView.Adapter<IdeaListAdapter.IdeaViewHolder> {
private Context mCtx;
private List<Idea> ideaList, idlst;
public IdeaListAdapter(Context mCtx, List<Idea> ideaList) {
this.mCtx = mCtx;
this.ideaList = ideaList;
}
#NonNull
#Override
public IdeaListAdapter.IdeaViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.idea_list_object_layout, null);
return new IdeaListAdapter.IdeaViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull IdeaListAdapter.IdeaViewHolder ideaViewHolder, int i) {
final Idea idea = ideaList.get(i);
if (idea.getVoted().equals("0")) {
ideaViewHolder.checkBoxLikeIdeaListFragment.setChecked(false);
} else if (idea.getVoted().equals("1")) {
ideaViewHolder.checkBoxLikeIdeaListFragment.setChecked(true);
}
ideaViewHolder.checkBoxLikeIdeaListFragment.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
*** Update my idea.getVoted() here ***
} else {
*** Update my idea.getVoted() here ***
}
}
});
ideaViewHolder.textViewNameIdeaListFragment.setText(idea.getName());
}
#Override
public int getItemCount() {
return ideaList.size();
}
class IdeaViewHolder extends RecyclerView.ViewHolder {
TextView textViewNameIdeaListFragment;
CheckBox checkBoxLikeIdeaListFragment;
public IdeaViewHolder(#NonNull View itemView) {
super(itemView);
textViewNameIdeaListFragment = (TextView) itemView.findViewById(R.id.textViewNameIdeaListFragment);
checkBoxLikeIdeaListFragment = (CheckBox) itemView.findViewById(R.id.checkBoxLikeIdeaListFragment);
}
}
}
i would like to update my idea.getVoted() when the user click the checkBoxLikeIdeaListFragment
im not quite sure how i will use the ideaList.set() at this part.
should i do it on my MainActivity ? if yes, please teach me.
Create Setter method on your Model class **Idea** and access setter method to update the data.
Like this.
public class Idea {
private String id, name, voted;
public Idea(String id, String name, String voted) {
this.id = id;
this.name = name;
this.voted = voted;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVoted() {
return voted;
}
public void setVoted(String voted) {
this.voted = voted;
}
}
Use setter method of setVoted in your adapter class.
ideaViewHolder.checkBoxLikeIdeaListFragment.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
i
ideaList.get(i).setVoted("set your data"); //here you have to upadte the vote value.
notifiyDatasetChanged();
}
});
Quickest way to do this is to pass a OnCheckedListener on your IdeaViewHolder constructor and assign it to your checkBoxLikeIdeaListFragment.
Or on your existing code you can:
ideaViewHolder.checkBoxLikeIdeaListFragment.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
ideaList.get(i).setVoted(b); // i is the int index passed to onBindViewHolder(..)
IdeaListAdapter.this.notifyDatasetChanged(); //update list
}
});
I have this class
public class MasterData {
public long id;
public String name;
#Expose(deserialize = true, serialize = false)
public String type;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
return name;
}
In my Activity I have an spinner loaded with String values, when the user select one item on the spinner I would like to cast the item to my model, getSelectedItem() return an object, so what I do is:
MasterData md = (MasterData) spinner.getSelectedItem();
The adapter for the spinner is :
ArrayAdapter spinnerListAdapter = new ArrayAdapter(spinner.getContext(),
android.R.layout.simple_spinner_item, list.toArray(new MasterData[list.size()]));
It works well on Huawei but on Samsung I am getting this error:
Fatal Exception: java.lang.ClassCastException: java.lang.String cannot
be cast to es.miapp.comapny.data.master.model.MasterData
Any idea about what I can do in order to cast a String spinner item to MasterData class?
You can use spinner.getSelectedItemPosition()
Suppose you have a list, So
MasterData md = list.get(spinner.getSelectedItemPosition());
This is my JSON:
I need to access to extra_services and get the service_name.
I know I can do it directly using Gson but the problem is that I need to use getters and setters because I'm using an adapter inside of a recycler, how can I do that?
here is my adapter class where I need to get the service name
public class ExtraServicesAdapter extends RecyclerView.Adapter<ExtraServicesAdapter.ViewHolder> implements View.OnClickListener
{
private ArrayList<Business> businessList;
private Activity activity;
private int layoutMolde,idb;
public ExtraServicesAdapter(Activity activity, ArrayList<Business> list, int layout)
{
this.activity = activity;
this.businessList = list;
layoutMolde = layout;
}
#Override
public ExtraServicesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_services_basic, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position)
{
if(businessList.get(position).getExtra_services()==null)
{
holder.txtNameServiceBasic.setText("There's nothing to show");
}
holder.txtNameServiceBasic.setText(businessList.get(position).getExtra_services());
}
#Override
public int getItemCount()
{
return businessList.size();
}
#Override
public void onClick(View v)
{
}
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView txtNameServiceBasic;
public ViewHolder( View itemView)
{
super(itemView);
txtNameServiceBasic = (TextView) itemView.findViewById(R.id.txtNameServiceBasic);
}
}
}
and this is my class where are the getters and setters that I'm using
public class Business {
private Integer id,rating;
private String name, description, cover_url_string, logo_url_string, icon_default,business_name,cover_default,extra_services;
private Boolean status;
public Business(){}
public Business(Integer id,Integer rating,String business_name, String name, String description, String logo_url_string, String cover_default, String icon_default,String cover_url_string,String extra_services) {
this.id = id;
this.name = name;
this.business_name=business_name;
this.description = description;
this.logo_url_string = logo_url_string;
this.cover_url_string = cover_url_string;
this.rating=rating;
this.icon_default=icon_default;
this.cover_default=cover_default;
this.extra_services=extra_services;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getRating() {
return rating;
}
public String getBusiness_name() {
return business_name;
}
public void setBusiness_name(String business_name) {
this.business_name = business_name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLogo_url_string() {
return logo_url_string;
}
public void setLogo_url_string(String logo_url_string) {
this.logo_url_string = logo_url_string;
}
public String getIcon_default() {
return icon_default;
}
public String getCover_default() {
return cover_default;
}
public String getCover_url_string() {
return cover_url_string;
}
public String getExtra_services() {
return extra_services;
}
public void setExtra_services() {
this.extra_services=extra_services;
}
}
You can add an ExtraServices class that contains a list of ExtraService
ExtraService
public class ExtraService {
private String Id;
private String ServiceName;
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
public String getServiceName() {
return ServiceName;
}
public void setServiceName(String ServiceName) {
this.ServiceName = ServiceName;
}
ExtraServices
public class ExtraServices {
private List<ExtraService> extraServicesList;
public List<ExtraService> getExtraServicesList() {
return extraServicesList;
}
public void setExtraServicesList(List<ExtraService> extraServicesList) {
this.extraServicesList = extraServicesList;
}
public void add(ExtraService extraService){
if(extraServicesList == null){
extraServicesList = new ArrayList<>();
}
extraServicesList.add(extraService);
}
And in your Business class add getters and setters of ExtraServices
private ExtraServices extraServices;
public ExtraServices getExtraServices () {
return extraServices;
}
public void setExtraServices (ExtraServices extraServices) {
this.extraServices = extraServices;
}
After you have to do the setter process and in your Adapter you should do something like this:
holder.txtNameServiceBasic.setText(businessList.get(position).getExtraServices().getExtraServicesList().get(posistion).getServiceName());
i have 2 classes to show some data in list view
but i want make option for users to sort this list view
this is adapter class
public class CustomListViewAdapter extends BaseAdapter {
private Activity activity;
private Book[] data;
private static LayoutInflater inflater=null;
public CustomListViewAdapter(Activity a, Book list[]) {
activity = a;
data=list;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getBookId(int position){
return data[position].getId();
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row, null);
TextView row_id =(TextView)vi.findViewById(R.id.row_id);
TextView name=(TextView)vi.findViewById(R.id.title);
TextView descp = (TextView) vi.findViewById(R.id.artist);
TextView note_type = (TextView) vi.findViewById(R.id.row_note_type);
ImageView image=(ImageView)vi.findViewById(R.id.image);
row_id.setText(String.valueOf(data[position].getId()));
name.setText(data[position].getTitle());
descp.setText(data[position].getContent());
//row_id.setText(data[position].getId());
note_type.setText(data[position].getType());
//image.setImageResource(R.drawable.subway);
if(data[position].getImage().toString().equals("Facebook")){
image.setImageResource(R.drawable.facebook);
}else if(data[position].getImage().toString().equals("skype")){
image.setImageResource(R.drawable.skype);
}else if(data[position].getImage().toString().equals("Subway")){
image.setImageResource(R.drawable.subway);
}else if(data[position].getImage().toString().equals("Book")){
image.setImageResource(R.drawable.book);
}
return vi;
}
}
and this is book class
public class Book {
private int id;
private String title;
private String content; // this is content of table
private String image; // choosing images
private String type; // type of table ( note or task)
private int archived; // Archive table (true or false)
private int check; // make overline when finish (true or false)
private int protect; // protect the table with password (true or false)
private String password; // password of table if it was protected
private String date_added;
public Book() {}
public Book(String title, String content, String image, String type, int archived,
int check, int protect, String password) {
this.title = title;
this.content = content;
this.image = image;
this.type = type;
this.archived = archived;
this.check = check;
this.protect = protect;
this.password = password;
}
// ---- setter
public void setId(int id){
this.id = id;
}
public void setTitle(String title){
this.title = title;
}
public void setContent(String content){
this.content = content;
}
public void setImage(String image){
this.image = image;
}
public void setType(String type){
this.type = type;
}
public void setArchived(int archived){
this.archived = archived;
}
public void setCheck(int check){
this.check = check;
}
public void setProtect(int protect){
this.protect = protect;
}
public void setPassword(String password){
this.password = password;
}
public void setDate_added(String date_added){
this.date_added = date_added;
}
// --- getter ---
public int getId(){
return id;
}
public String getTitle(){
return title;
}
public String getContent(){
return content;
}
public String getImage(){
return image;
}
public String getType(){
return type;
}
public int getArchived(){
return archived;
}
public int getCheck(){
return check;
}
public int getProtect(){
return protect;
}
public String getPassword(){
return password;
}
public String getDate_added() {
return date_added;
}
public String toString(){
return "Book >> id:"+id+" | title:"+title+" | author:";
}
}
and this is method for showing the data in list view but BookTable is class of connect and get data from sqlite
public void list_Books() {
BookTable bt = new BookTable(getActivity());
adapter = new CustomListViewAdapter(getActivity(), bt.getAllBooks());
list.setAdapter(adapter);
list.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View arg1,int pos, long id) {
selected = adapter.getBookId(pos);
row_type = (TextView) arg1.findViewById(R.id.row_note_type);
return false;
}
});
registerForContextMenu(list);
}
i want to know how can i sorting this data by objects of my Book class
please i want speed answer
One approach of sorting is for your object Book to implement Comparable interface:
public class Book implements Comparable<Book>{
private int id;
#Override
public int compareTo(Book another) {
if(this.id >= another.id)
return 1;
return -1;
}
}
If you want to sort after you query the data from database you can just call the Collections sort() method:
Collections.sort(list);
If you dont want to implement Comparable interface, you can just create a Comparator and call the following method of Collections:
Collections.sort(list, new Comparator<Book>() {
#Override
public int compare(Book lhs, Book rhs) {
if(lhs.id >= rhs.id)
return 1;
return -1;
}
});
To reverse the order (as frequently it is requiredfor sorting):
Collections.sort(list, Collections.reverseOrder());
After you sort the list dont forget to notify the adapter to refresh the view:
adapter.notifyDataSetChanged();