How to get string from arraylist - java

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

Related

How to get details when clicking on an item in a RecyclerView?

I am trying to get the details of the Recipe from which Recipe I have clicked in recycler view. I am using this to go to an edit/delete feature. Here is the code for my main activity.
The details that I am trying to get is getting the Name, Ingredients and method.
public class MainActivity extends AppCompatActivity implements RecipeListAdapter.OnItemClickListener {
private RecipeViewModel mRecipeViewModel;
public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
public String Name;
public String Ingredients;
public String Method;
private RecipeListAdapter mAdapter;
private RecipeDao recDao;
private LiveData<List<Recipe>> RecipeList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
final RecipeListAdapter adapter = new RecipeListAdapter(this);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(MainActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecipeViewModel = new ViewModelProvider(this).get(RecipeViewModel.class);
mRecipeViewModel.getAllRecipes().observe(this, new Observer<List<Recipe>>() {
#Override
public void onChanged(#Nullable final List<Recipe> recipes) {
// Update the cached copy of the words in the adapter.
adapter.setWords(recipes);
}
});
void onItemClick(int position) {
//Delete Below test to pass data through
Recipe recipe = new Recipe("Test", "Yeet", "Jim");
// showAlertDialogBox();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Edit or Delete...");
alertDialog.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent update = new Intent(MainActivity.this, UpdateRecipeActivity.class);
update.putExtra("Name", recipe.getName());
update.putExtra("Ingredients", recipe.getIngredients());
update.putExtra("Method", recipe.getMethod());
startActivity(update);
}
});
alertDialog.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Delete
}
});
alertDialog.show();
}
Here is the Recipe.class if you needed it!
#Entity(tableName = "recipe_table")
public class Recipe {
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name= "recipeId")
private int RecipeId;
private String name;
private String Ingredients;
private String Method;
#Ignore
public Recipe(String name, String Ingredients, String Method) {
this.RecipeId = RecipeId;
this.name = name;
this.Ingredients = Ingredients;
this.Method = Method;
}
public Recipe(String name) {
this.name = name;
}
public void changeText1(String text){
name = text;
}
//Add Image somehow!
public int getRecipeId() {
return RecipeId;
}
public void setRecipeId(int recipeId) {
RecipeId = recipeId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMethod() {
return Method;
}
public void setMethod(String method) {
Method = method;
}
public String getIngredients() {
return Ingredients;
}
public void setIngredients(String ingredients) {
Ingredients = ingredients;
}
}
If you need anymore files, these are the files I have:
- RecipeListAdapter
- RecipeDao
- RecipeRepository
- RecipeRoomDatabase
- RecipeViewModel
Recipe Adapter code
public class RecipeListAdapter extends RecyclerView.Adapter {
private OnItemClickListener mListener;
private List recipeList;
public interface OnItemClickListener{
void onItemClick(int position, Recipe recipe);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
class RecipeViewHolder extends RecyclerView.ViewHolder {
private final TextView recipeItemView;
private RecipeViewHolder(View itemView) {
super(itemView);
recipeItemView = itemView.findViewById(R.id.textView);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (mListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
mListener.onItemClick(position,
recipeList.get(getAdapterPosition()));
}
}
}
});
}
}
private final LayoutInflater mInflater;
private List<Recipe> mRecipes; // Cached copy of words
RecipeListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.recipeList = recipeList;
}
#Override
public RecipeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.recyclerview_item, parent,
false);
return new RecipeViewHolder(itemView);
}
#Override
public void onBindViewHolder(RecipeViewHolder holder, int position) {
if (mRecipes != null) {
Recipe current = mRecipes.get(position);
holder.recipeItemView.setText(current.getName());
} else {
// Covers the case of data not being ready yet.
holder.recipeItemView.setText("No Recipes");
}
}
void setWords(List<Recipe> recipes){
mRecipes = recipes;
notifyDataSetChanged();
}
// getItemCount() is called many times, and when it is first called,
// mWords has not been updated (means initially, it's null, and we can't
return null).
#Override
public int getItemCount() {
if (mRecipes != null)
return mRecipes.size();
else return 0;
}
public interface OnNoteListener{}
}
Inside the onItemClick there is one more parameter need to add.
void onItemClick(int position, Recipe recipe) {
//Delete selected recipe from recipe list
arrayList.remove(recipe)
}
The onItemClick method will get called from adapter, from there you have to pass the selected receipe. In the adapter you have to use recipeList.get(getAdapterPosition()) to get the clicked receipe and pass this to the interface method, onItemClick along with the position.
So your code will look like this way inside the adapter,
itemClickListener.onItemClick(position,
recipeList.get(getAdapterPosition()))
Just as a note, please ensure instead of List, you need to take ArrayList to perform remove operation.

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

How can I pass object to the spinner in android?

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

How to update data in one arraylist with two arrayadapter in different activity

I am trying to use two different ArrayAdapter(separately in to two Activity) with one Arraylist. The first ArrayAdapter does the Increment for the Quantity and the second does the Decrement. Then all of the Data from the first ArrayAdapter will be transfer to the second ArrayAdapter, but only the Data with Quantity greater than 1 will be displayed. All of the previous task seems to be working fine, until I tried to Decrement a Quantity(It shows that the data decements) and try to check if changes were saved by going back to the first Activity and back again to the second Activity. What happens is that changes made by the Decrement is being ignored and resets the data from when the item was Incremented. I know it's kinda messed up, but I hope you can help me what am I doing wrong.
EDIT: I am using two ArrayAdapter because I want to display the quantity in the second adapter, along with other elements.
Here is my codes:
myProductAdapter.java(Increment Adapter)
public class myProductAdapter extends ArrayAdapter<myProduct> {
public class ViewHolder{
Button addItem;
}
public myProductAdapter(Context context, ArrayList<myProduct> myProducts) {
super(context, 0, myProducts);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final myProduct product = getItem(position);
final ViewHolder viewHolder;
//Some Codes Here..
viewHolder.addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
product.productQuantity ++;
Toast.makeText(getContext(), "" + product.productQuantity(), Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}
myOrderAdapter.java(Decerement Adapter)
public class myOrderAdapter extends ArrayAdapter<myProduct> {
public class ViewHolder{
Button minusItem;
}
public myOrderAdapter(Context context, ArrayList<myProduct> orders){
super(context, 0, orders);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final myProduct order = getItem(position);
viewHolder.minusItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
order.productQuantity --;
if(order.productQuantity() <= 0){
order.productQuantity = 0;
notifyDataSetChanged();
}
Toast.makeText(getContext(),"" + order.productQuantity(),Toast.LENGTH_SHORT).show();
return convertView;
}
}
myProduct.java
public class myProduct implements Parcelable {
#SerializedName("productID")
public int productID;
#SerializedName("categoryID")
public int categoryID;
#SerializedName("productName")
public String productName;
#SerializedName("productPrice")
public int productPrice;
public int productQuantity = 0;
public myProduct(int productID, int categoryID, String productName, int productPrice){
this.productID = productID;
this.categoryID = categoryID;
this.productName = productName;
this.productPrice = productPrice;
}
public int getProductID(){
return productID;
}
public int getCategoryID(){
return categoryID;
}
public String getProductName(){
return productName;
}
public int getProductPrice(){
return productPrice;
}
public int productQuantity() {
return productQuantity;
}
protected myProduct(Parcel in) {
productID = in.readInt();
categoryID = in.readInt();
productName = in.readString();
productPrice = in.readInt();
productQuantity = in.readInt();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(productID);
dest.writeInt(categoryID);
dest.writeString(productName);
dest.writeInt(productPrice);
dest.writeInt(productQuantity);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<myProduct> CREATOR = new Parcelable.Creator<myProduct>() {
#Override
public myProduct createFromParcel(Parcel in) {
return new myProduct(in);
}
#Override
public myProduct[] newArray(int size) {
return new myProduct[size];
}
};
}
Menu.class
viewOrder = (Button)findViewById(R.id.viewOrder);
viewOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Menu.this, Order.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("productList", productList);
i.putExtras(bundle);
startActivity(i);
}
});
Order.class
Bundle bundle = getIntent().getExtras();
productList = bundle.getParcelableArrayList("productList");
filter = new ArrayList<myProduct>();
orderAdapter = new myOrderAdapter(getApplicationContext(),filter);
for(myProduct item : productList){
if(item.productQuantity > 0){
Log.d(TAG,item.getProductName());
Log.d(TAG,"" + item.productQuantity());
filter.add(item);
}
else if(item.productQuantity <= 0){
filter.remove(item);
}
}
orderListView.setAdapter(orderAdapter);
The issue is that you are passing the array to the second adapter as a Parcelable, so it's basically making a deep copy of the array, and has nothing to do with the original array. Therefore changes in second array, don't show in first array.
A simple (but maybe dirty) solution would be to make the array as a static variable (or part of the application class, or a singleton), and use the actual array in both activities.
If you can design, that both lists are in two fragments, and part of one activity, then just have the activity hold on to the shared array for both fragments.

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