I am getting the values from api(which list of Names with Id which i stored in model)- How to set this Name to AutoComplete and get both Name and Id on dropdown selection.
This will set a Name in autocomplete and getting name at onItemClick but how to get ID?
Model class
public class MeetingContactModel implements Serializable {
private String id;
private String text;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
MyActivity class
OnCreate :
calling autocomplete adapter
setMeetingContactAuto(autoContact, contactList);
autoContact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
strContact =(String) parent.getItemAtPosition(position);
// strContactCode = code.get(position);
}
});
private void setMeetingContactAuto(AutoCompleteTextView autoContact, final ArrayList<MeetingContactModel> xcontactList) {
List<String> names = new AbstractList<String>() {
#Override
public int size() { return xcontactList.size(); }
#Override
public String get(int i) {
code.clear();
code.add(xcontactList.get(i).getText());
return xcontactList.get(i).getText();
}
};
autoContact.setThreshold(1);
autoContact.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names));
}
Not able to get Id - Please let me know to get it
Implement toString() method in your model class
public class MeetingContactModel implements Serializable {
private String id;
private String text;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
#Override
public String toString() {
return text;
}
}
// Fetch your selected model
autoContact.setAdapter(new ArrayAdapter<>(requireContext(), R.layout.spinner_item_ranking, contactList));
autoContact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MeetingContactModel m=(MeetingContactModel) parent.getItem(position);
String name=m.getText();
String id=m.getId();
}
});
Related
I currently get stock on this part. I want to display simple data from GSON and I practice using MVVM structure and with Hilt and "RxJava".
This is my "View Model" and I don't know what to do.(This is my first time using this structure and dependencies.)
At my "getTip()" function under my View Model how can i transfer the data from "tipsModel" to arraylist and if i did something wrong at my codes.
public class TipsViewModel extends ViewModel {
private static final String TAG = "TipsViewModel";
private Repository repository;
private MutableLiveData<ArrayList<TipsModel>> tipsList = new MutableLiveData<>();
#ViewModelInject
public TipsViewModel(Repository repository){
this.repository = repository;
}
public MutableLiveData<ArrayList<TipsModel>> getTipsList(){
return tipsList;
}
public void getTips(){
repository.getTips()
.subscribeOn(Schedulers.io())
.map(new Function<TipsModel, ArrayList<TipsModel>>() {
#Override
public ArrayList<TipsModel> apply(TipsModel tipsModel) throws Throwable {
// What i have to put here to transfer the data from "tipsModel" to my ArrayList.
return null;
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(result -> tipsList.setValue(result),
error -> Log.e(TAG,"getTips: "+error.getMessage()));
}
}
This is my Repository
public class Repository {
private TipsApiService apiService;
#Inject
public Repository(TipsApiService apiService){
this.apiService = apiService;
}
public Observable<TipsModel> getTips(){
return apiService.getTips();
}
}
And this is my Model. it a simple model.
public class TipsModel {
private Integer id;
private String gameName;
private String gameMenu;
private String subtitle;
private String description;
private Object image;
public TipsModel(Integer id, String gameName, String gameMenu, String subtitle, String description, Object image) {
this.id = id;
this.gameName = gameName;
this.gameMenu = gameMenu;
this.subtitle = subtitle;
this.description = description;
this.image = image;
}
public Integer getId() {
return id;
}
public String getGameName() {
return gameName;
}
public String getGameMenu() {
return gameMenu;
}
public String getSubtitle() {
return subtitle;
}
public String getDescription() {
return description;
}
public Object getImage() {
return image;
}
public void setId(Integer id) {
this.id = id;
}
public void setGameName(String gameName) {
this.gameName = gameName;
}
public void setGameMenu(String gameMenu) {
this.gameMenu = gameMenu;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
public void setDescription(String description) {
this.description = description;
}
public void setImage(Object image) {
this.image = image;
}
}
This is my Code on my fragment
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
binding = ActivityTipsViewBinding.inflate(inflater,container,false);
return binding.getRoot();
}
#Override
public void onViewCreated(#Nonnull View view, #Nullable Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
viewModel = new ViewModelProvider(this).get(TipsViewModel.class);
initRecyclerView();
observeData();
viewModel.getTips();
}
private void observeData(){
viewModel.getTipsList().observe(getViewLifecycleOwner(), new Observer<ArrayList<TipsModel>>() {
#Override
public void onChanged(ArrayList<TipsModel> tipsModels) {
Log.e(TAG,"onChanged: "+ tipsModels.size());
tipsAdapter.updateList(tipsModels);
}
});
}
private void initRecyclerView(){
binding.tipsRecyclerview.setLayoutManager(new LinearLayoutManager((getContext())));
tipsAdapter = new TipsAdapter(getContext(),tipsModels);
binding.tipsRecyclerview.setAdapter(tipsAdapter);
}
}
package eu.andykrzemien.dog4u;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
class Size {
private int id;
private String SizeName;
public Size(int id, String sizeName) {
this.id = id;
SizeName = sizeName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSizeName() {
return SizeName;
}
public void setSizeName(String sizeName) {
SizeName = sizeName;
}
public String toString(){
return getId()+" "+getSizeName();
}
}
class Activities {
private int id;
private String ActivityName;
public Activities(int id, String activityName) {
this.id = id;
ActivityName = activityName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getActivityName() {
return ActivityName;
}
public void setActivityName(String activityName) {
ActivityName = activityName;
}
public String toString() {
return getId()+ " "+getActivityName();
}
}
class Children {
private int id;
private String ChildrenName;
public Children(int id, String childrenName) {
this.id = id;
ChildrenName = childrenName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getChildrenName() {
return ChildrenName;
}
public void setChildrenName(String childrenName) {
ChildrenName = childrenName;
}
public String toString() {
return getId()+" "+getChildrenName();
}
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ListView sizeList;
ListView activityList;
ListView childrenList;
Button button;
public static final String TAG = "MyActivity";
public void inItListViews() {
sizeList= findViewById(R.id.sizeList);
activityList= findViewById(R.id.activityList);
childrenList= findViewById(R.id.childrenList);
}
public void dogMatches() {
Size s1 = new Size(1,"Miniature");
Size s2 = new Size(2,"Small");
Size s3 = new Size(3,"Medium");
Size s4 = new Size(4,"Large");
Size s5 = new Size(5,"Giant");
Size [] size = new Size[]{s1,s2,s3,s4,s5};
ArrayAdapter<Size> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,size);
this.sizeList.setAdapter(adapter1);
Activities a1 = new Activities(1,"Lazy");
Activities a2 = new Activities(2,"Light Active");
Activities a3 = new Activities(3,"Very Active");
Activities[] activities = new Activities[]{a1,a2,a3};
ArrayAdapter<Activities> adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,activities);
this.activityList.setAdapter(adapter2);
Children c1 = new Children(1,"Like");
Children c2 = new Children(2,"Doesn't matter");
Children[] children = new Children[]{c1,c2};
ArrayAdapter<Children> adapter3 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_activated_1,children);
this.childrenList.setAdapter(adapter3);
}
public void processResult() {
Log.d(TAG,"Result button clicked");
int pos1= sizeList.getCheckedItemPosition();
int pos2 = activityList.getCheckedItemPosition();
int pos3 = childrenList.getCheckedItemPosition();
Size sSelected= (Size) sizeList.getItemAtPosition(pos1);
Activities aSelected=(Activities) activityList.getItemAtPosition(pos2);
Children cSelected=(Children) childrenList.getItemAtPosition(pos3);
if(sSelected!=null && aSelected!=null && cSelected!=null){
Log.d(TAG,"result "+ sSelected.getSizeName()+" : "+ aSelected.getActivityName()+ " " + cSelected.getChildrenName());
String petSeeker = yourBest(sSelected,aSelected,cSelected);
Toast.makeText(this,petSeeker,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"Please Select Something",Toast.LENGTH_SHORT).show();
}
}
public void buttonPressed() {
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
processResult();
}
});
}
private String yourBest(Size s, Activities a, Children c) {
String doThis;
if(s.getSizeName().equalsIgnoreCase("small")
&& a.getActivityName().equalsIgnoreCase("lazy")
&& c.getChildrenName().equalsIgnoreCase("like")){
Toast.makeText(this,"Chihuahua",Toast.LENGTH_LONG).show();
doThis="Chihuahua";
}
else if(s.getSizeName().equalsIgnoreCase("small")
&& a.getActivityName().equalsIgnoreCase("light active")
&& c.getChildrenName().equalsIgnoreCase("like")){
doThis="Labrador";
} else{
doThis="Find a cat";
}
return doThis;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inItListViews();
dogMatches();
buttonPressed();
}
#Override
public void onClick(View v) {
}
}
The app is running but the problem is that I can't get the result of three listViews. Is it something with the ListView or with the method? After pressing button I get only else message. Maybe there is some method to check the listView because maybe they aren't coded with the press of the mouse. I'm really stuck and need at least some advice not a ready solution.
Instead of using getCheckedItemPosition() to get the position of the selected list item, use listView.setOnItemClickListener()
So you can remove below statements, and make po1-pos3 as global fields
int pos1= sizeList.getCheckedItemPosition();
int pos2 = activityList.getCheckedItemPosition();
int pos3 = childrenList.getCheckedItemPosition();
As below:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
int pos1, pos2, pos3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inItListViews();
dogMatches();
buttonPressed();
sizeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pos1 = position;
}
});
activityList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pos2 = position;
}
});
childrenList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pos3 = position;
}
});
}
And to get a list item for a position:
sizeList.getAdapter().getItem(pos1);
activityList.getAdapter().getItem(pos2);
childrenList.getAdapter().getItem(pos3);
First of all I think it will be better without implementing View.OnClickListener, because you don't use it. Second - you can put a breakpoint at:
int pos1 = sizeList.getCheckedItemPosition();
Debug it and then you will see what is going wrong.
And last, I suggest creating a custom interface that will allow you to find out what position was checked.
I'm trying to pass an object from my RecyclerView adapter to a fragment using parcelable. However when I try to receive the data, the bundle is null. I've looked at other examples, but I can't see where I'm going wrong.
Parcelable class
public class Country extends BaseObservable implements Parcelable {
#SerializedName("name")
#Expose
private String name;
#SerializedName("snippet")
#Expose
private String snippet;
#SerializedName("country_id")
#Expose
private String countryId;
#SerializedName("id")
#Expose
private String id;
#SerializedName("coordinates")
#Expose
private Coordinates coordinates;
#SerializedName("images")
#Expose
private List<CountryImage> images;
protected Country(Parcel in) {
name = in.readString();
snippet = in.readString();
}
public static final Creator<Country> CREATOR = new Creator<Country>() {
#Override
public Country createFromParcel(Parcel in) {
return new Country(in);
}
#Override
public Country[] newArray(int size) {
return new Country[size];
}
};
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(snippet);
}
#Override
public int describeContents() {
return 0;
}
#Bindable
public String getCountryId() {
return countryId;
}
public void setCountryId(String countryId) {
this.countryId = countryId;
notifyPropertyChanged(BR.countryId);
}
#Bindable
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
notifyPropertyChanged(BR.id);
}
#Bindable
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
notifyPropertyChanged(BR.coordinates);
}
#Bindable
public List<CountryImage> getImages() {
return images;
}
public void setImages(List<CountryImage> images) {
this.images = images;
notifyPropertyChanged(BR.images);
}
#Bindable
public String getSnippet() {
return snippet;
}
public void setSnippet(String snippet) {
this.snippet = snippet;
notifyPropertyChanged(BR.snippet);
}
#Bindable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
notifyPropertyChanged(BR.name);
}
}
RetrofitAdapter.java
public class RetrofitAdapter extends RecyclerView.Adapter<RetrofitAdapter.MyViewHolder> implements CustomClickListener {
private List<Country> cities;
private CustomClickListener customClickListener;
private View view;
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
RetroItemBinding retroItemBinding =
DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()),
R.layout.retro_item, viewGroup, false);
view = viewGroup;
return new MyViewHolder(retroItemBinding);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.bindTo(cities.get(i));
myViewHolder.retroItemBinding.setItemClickListener(this);
}
#Override
public int getItemCount() {
if (cities != null) {
return cities.size();
} else {
return 0;
}
}
public void setCityList(ArrayList<Country> cities) {
this.cities = cities;
notifyDataSetChanged();
}
class MyViewHolder extends RecyclerView.ViewHolder {
private RetroItemBinding retroItemBinding;
public MyViewHolder(#NonNull RetroItemBinding retroItemBinding) {
super(retroItemBinding.getRoot());
this.retroItemBinding = retroItemBinding;
}
void bindTo(Country country) {
retroItemBinding.setVariable(BR.city, country);
retroItemBinding.setVariable(BR.itemClickListener, customClickListener);
retroItemBinding.executePendingBindings();
}
}
public void cardClicked(Country country) {
CountryFragment countryFragment = new CountryFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("Country", country);
countryFragment.setArguments(bundle);
((FragmentActivity) view.getContext()).getSupportFragmentManager().beginTransaction()
.replace(R.id.frag_container, new CountryFragment())
.commit();
}
}
Where I receive attempt to receive the data in CountryFragment.java
Country country;
Bundle bundle = this.getArguments();
if (bundle != null) {
country = bundle.getParcelable("Country");
}
.replace(R.id.frag_container, new CountryFragment())
should be
.replace(R.id.frag_container, countryFragment)
You are creating a second instance instead of passing the one you set the arguments on.
The code is:
public class Organization {
private String name;
private Long id;
public Organization(){
}
public Organization(String name, Long id) {
super();
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
The spinner is:
Spinner sp = (Spinner) navigationView.getMenu().findItem(R.id.brand_spinner).getActionView();
sp.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,contactList));
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String value = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(),""+value+"",Toast.LENGTH_SHORT).show();
}
});
How can I pass both name and id to the spinner and the should be listed in the spinner, by selecting the name in the spinner. Store the id of the name in the local variable.
You have to create your own Custom Adapter class which will extend BaseAdapter or ArrayAdapter and in that you just pass the ArrayList<> of your Organization.
Just check this link it will help you in creating adapter
Check Link
For ArrayAdapter you are sending contactList, override toString() in objects of contactList. So ArrayAdapter while rendering it will call toString() method each object of contactList to show the text in textView.
So now onClick of item,
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object obj= parent.getItemAtPosition(position);
Contact c = (Contact) obj;
System.out.println("id = " + c.getId() + " , Name = " + c.getName());
}
This is the code of my project where in I have a listview of objects 'mProductList'. I have set an onclickListener on each item of list view which will open a menu with three options. Now on edit i want to change the variable amount in my selected item and display it on the screen. I am new at this so please dont downvote this. Any help would be appreciated stackoverflow. Please let me k now if u need any more of my code.
ProductListAdapter adapter = new ProductListAdapter(getApplicationContext(), mProductList);
lvProduct.setAdapter(adapter);
lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Do something
Toast.makeText(getApplicationContext(), " Clicked product id = " + view.getTag(), Toast.LENGTH_SHORT).show();
registerForContextMenu(lvProduct);
openContextMenu(lvProduct);
}
});
}
final int CONTEXT_MENU_ADD =1;
final int CONTEXT_MENU_EDIT =2;
final int CONTEXT_MENU_ARCHIVE =3;
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
//Context menu
menu.setHeaderTitle("My Context Menu");
menu.add(0, CONTEXT_MENU_ADD, 0, "Add");
menu.add(0, CONTEXT_MENU_EDIT, 0, "Edit");
menu.add(0, CONTEXT_MENU_ARCHIVE, 0, "Delete");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId())
{
case CONTEXT_MENU_ADD:
{
}
break;
case CONTEXT_MENU_EDIT:
{
// Edit Action
}
break;
case CONTEXT_MENU_ARCHIVE:
{
}
break;
}
return super.onContextItemSelected(item);
}
}
This is my Product class whose objects are made and displayed in the list view:
public class Product {
private int id;
private String name;
private int amount;
//private String description;
//Constructor
public Product(int id, String name, int amount) {
this.id = id;
this.name = name;
this.amount = amount;
}
//Setter, getter
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 int getAmount() {
return amount;
}
public void setPrice(int amount) {
this.amount = amount;
}