How can I pass object to the spinner in android? - java

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

Related

ListView or false method to get the result

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.

AutoCompleteTextView - Get Id when select Name

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

I can not set Set Text in Card View name and surname

I have problem with set text in card view. I have 3 activist. First activity is list , second activity which show edit text which I complete data Person next acttivty 3 summary click buton go to MainActivty. When click to MainActitvty display error.
04-05 09:21:06.879 1035-1035/magdalena.pl.callmistake E/AndroidRuntime: FATAL EXCEPTION: main
Process: magdalena.pl.callmistake, PID: 1035
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String magdalena.pl.callmistake.Person.getName()' on a null object reference
at magdalena.pl.callmistake.PersonAdapter.onBindViewHolder(PersonAdapter.java:41)
at magdalena.pl.callmistake.PersonAdapter.onBindViewHolder(PersonAdapter.java:18)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6356)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6389)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5335)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5598)
my PersonAdapter
public class PersonAdapter extends RecyclerView.Adapter<PersonAdapter.PersonViewHolder> {
public List<Person> personList = new ArrayList<>();
Person person;
private LayoutInflater layoutInflater;
public PersonAdapter(LayoutInflater layoutInflater) {
this.layoutInflater = layoutInflater;
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.
from(parent.getContext()).inflate(R.layout.item_card, parent, false);
return new PersonViewHolder(view);
}
#Override
public void onBindViewHolder(PersonViewHolder holder, int position) {
person = personList.get(position);
holder.name.setText(person.getName());
holder.surname.setText(person.getSurname());
}
#Override
public int getItemCount() {
return personList.size();
}
public void addPerson(Person person) {
int position = getItemCount();
personList.add(position, person);
notifyDataSetChanged();
}
public class PersonViewHolder extends RecyclerView.ViewHolder {
public TextView name, surname;
public PersonViewHolder(View itemView) {
super(itemView);
name = (TextView)itemView.findViewById(R.id.person_name);
surname = (TextView)itemView.findViewById(R.id.person_surname);
}
}
}
class Person
public class Person implements Parcelable
{
private String name;
private String surname;
private String email;
private String phone;
private String description;
protected Person(Parcel in) {
name = in.readString();
surname = in.readString();
email = in.readString();
phone = in.readString();
description = in.readString();
}
public Person(String name, String surname, String email, String phone, String description) {
this.name = name;
this.surname = surname;
this.email = email;
this.phone = phone;
this.description = description;
}
public String setName(String name) {
this.name = name;
return null;
}
public String getSurname() {
return surname;
}
public String setSurname(String surname) {
this.surname = surname;
return null;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public static Creator<Person> getCREATOR() {
return CREATOR;
}
public static final Creator<Person> CREATOR = new Creator<Person>() {
#Override
public Person createFromParcel(Parcel in) {
return new Person(in);
}
#Override
public Person[] newArray(int size) {
return new Person[size];
}
};
public String getName() {
return name;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeString(surname);
parcel.writeString(email);
parcel.writeString(phone);
parcel.writeString(description);
}
}
What is wrong ?
all code
https://github.com/Madzia123/CallInert
Apparently, In the onBindViewHolder method the person object is null. And you are trying to invoke getName() method on null reference. So it is causing the error. Make sure to have valid reference to Person object.
You are adding null person to personList at
public void addPerson(Person person) {
int position = getItemCount();
personList.add(position, person);
notifyDataSetChanged();
}
That's why when you call
person = personList.get(position);
it returns null
try this
public void addPerson(Person person) {
if(person==null){
Log.e("error","person is null");
return;
}
int position = getItemCount();
personList.add(position, person);
notifyDataSetChanged();
}
final Person person = personList.get(position);
holder.name.setText(person.getName());
From your attached logs, seems that you are getting NullPointerException when calling Person.getName() from your adapter's onBindViewHolder().
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String magdalena.pl.callmistake.Person.getName()' on a null
object reference
Solution:
Update your PersonAdapter as below:
public class PersonAdapter extends RecyclerView.Adapter<PersonAdapter.PersonViewHolder> {
Context context;
private LayoutInflater layoutInflater;
// Person List
public List<Person> personList;
public PersonAdapter(Context context, List<Person> persons) {
this.context = context;
this.personList = persons;
layoutInflater= LayoutInflater.from(context);
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.item_card, parent, false);
// View holder
PersonViewHolder holder = new PersonViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(PersonViewHolder holder, int position) {
// Person
Person person = personList.get(position);
holder.name.setText(person.getName());
holder.surname.setText(person.getSurname());
}
#Override
public int getItemCount() {
return personList.size();
}
public void addPerson(Person person) {
int position = getItemCount();
personList.add(position, person);
notifyDataSetChanged();
}
public class PersonViewHolder extends RecyclerView.ViewHolder {
public TextView name, surname;
public PersonViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.person_name);
surname = (TextView) itemView.findViewById(R.id.person_surname);
}
}
}
In your Activity do this:
..........
.................
Context mContext;
// RecyclerView
RecyclerView recyclerView;
PersonAdapter personAdapter;
RecyclerView.LayoutManager layoutManager;
// Values
List<Person> listPerson;
#Override
protected void onCreate(Bundle savedInstanceState) {
.......
............
// Context
mContext = this;
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
// Set your recyclerView layout manager
// Person List
listPerson = new ArrayList<Person>();
// Add some person data to list from API call or from Database
// Here I added some for test purpose
listPerson.add(new Person("Hello Android", "Android", "google#gmail.com", "21132342423", "Lorem ipsum"));
listPerson.add(new Person("Hello Android", "Android", "google#gmail.com", "21132342423", "Lorem ipsum"));
// specify an adapter
personAdapter = new PersonAdapter(mContext, listPerson);
recyclerView.setAdapter(personAdapter);
}
...............
...........................
Hope this will help you~
first pass the data from where you call this adapter.
adapter = new PersonAdapter(getContext(),(ArrayList<Person>) list);
use arraylist.method to access class method.
holder.name.setText(person.personList(position).getName());

How to get string from arraylist

I have problem with getting values from ArrayList. Eveyrhing I can do is get value like: [Ljava.lang.string #....
Can You help me please? I don't know what should be in the mProductList.get(???). I want to have separated values from item clicked.
public class Activity1 extends Activity {
private ListView lvProduct;
private ProductListAdapter adapter;
private List<Product> mProductList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
lvProduct = (ListView)findViewById(R.id.listView1);
mProductList = new ArrayList<>();
mProductList.add(new Product(1, "Product_1", "Price", "Description"));
mProductList.add(new Product(2, "Product_2", "Price", "Description"));
mProductList.add(new Product(3, "Product_3", "Price", "Description"));
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) {
Intent newActivity = new Intent(getApplicationContext(), BrowseProduct.class);
newActivity.putExtra("1st column value", mProductList.get(???));
newActivity.putExtra("2nd column value", mProductList.get(???));
newActivity.putExtra("3rd column value", mProductList.get(???));
newActivity.putExtra("4th column value", mProductList.get(???));
startActivity(newActivity);
}
});
}
}
You should declare Get and Set Method in your Product Class
nowyEkran.putExtra("1st column value", mProductList.get(position).getProduct());
Example
/**
* Created by Intellij Amiyo on 03-04-2017.
*/
public class Product implements Serializable {
public String product,price,description;
int id;
// Empty constructor
public Product()
{
}
// constructor
public Product( int id,String product,String price,String description) {
this.price = price;
this.product = product;
this.description = description;
this.id=id;
}
public String getprice() {
return this.price;
}
public void setprice(String price) {
this.price = price;
}
public String getProduct() {
return this.product;
}
public void setProduct(String product) {
this.product = product;
}
public String getDescription() {
return this.description;
}
public void setDescription(String product) {
this.description = description;
}
public int getID() {
return this.id;
}
public void setID(int id) {
this.id = id;
}
}
You need to get position reference first and then fetch the value of that position from ArrayList
mProductList.get(position).getProductName();
Happy Coding!
Try this
mProductList.get(position).getMethod()
this will get the index 0 1 2 of your array list,it will return the object
mProductList.get(0);
mProductList.get(1);
mProductList.get(2);
Put position in your Braces (). like below...
lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent newActivity = new Intent(getApplicationContext(), BrowseProduct.class);
newActivity.putExtra("1st column value", mProductList.get(position));
newActivity.putExtra("2nd column value", mProductList.get(position));
newActivity.putExtra("3rd column value", mProductList.get(position));
newActivity.putExtra("4th column value", mProductList.get(position));
startActivity(newActivity);
}
});
Hope this will help you...(:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
You can get the clicked item position from the int position parameter of the callback method
You already have a parameter called position. That will be the parameter of the get. However that will return a Product object and you will need to read the given member from there. Since you did not share the code of the Product class with us, we can only guess:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent newActivity = new Intent(getApplicationContext(), BrowseProduct.class);
newActivity.putExtra("1st column value", mProductList.get(position).ID);
newActivity.putExtra("2nd column value", mProductList.get(position).Name);
newActivity.putExtra("3rd column value", mProductList.get(position).Price);
newActivity.putExtra("4th column value", mProductList.get(position).Description);
startActivity(newActivity);
}
mProductList.get(position).price

Editing items in list view after selecting edit from menu of OncontextItemSelected

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

Categories