Reputation:
Below is my model:
public class Products {
String date = "", item = "";
public Products () {
}
public Products (String date String item ) {
this.date = date
this.item = item ;
}
public String getdate() {
return date
}
public void setdate (String date) {
this.date = date
}
public String getitem () {
return item
}
public void setitem (String item) {
this.item = item
}
}
And below code for defined the Arralist:
private ArrayList<TasksCharts> mArrayList;
and i have data in ArrayList:
position 0 -> date - "2016-10-02" , item = "pens"
position 1 -> date - "2016-10-03" , item = "xyz"
position 2 -> date - "2016-10-03" , item = "fts"
Now i want the position of ArraList whose contain "pens" . So for that i have eritten below code:
if (containsSubString(mArrayList, "pens")) {
int listIndex = getItemPos("pens");
}
private int getItemPos(String item) {
return mArrayList.indexOf(item);
}
When i runt this it will give me -1
index for item pens
.
How can i get the index of particular item ?
Upvotes: 0
Views: 5461
Reputation: 466
you should do sth like this :
private int getItemPos(String key , String item) {
int i = 0;
for (i=0; i<mArrayList.size(); i++)
{
if(mArrayList.get(i).get(key).equalsIgnoreCase(item))
{
return i;
}
}
return -1;
}
and call
int x = getItemPos("item" , "pen");
Upvotes: 2
Reputation: 2143
I have simply added products in the same ArrayList and then used for-loop to find that product position.
ArrayList<Products> mArrayList = new ArrayList<>();
Products products1 = new Products("2016-10-05", "Pens");
Products products2 = new Products("2016-10-04", "Pencil");
Products products3 = new Products("2016-10-03", "Book");
Products products4 = new Products("2016-10-02", "Dairy");
mArrayList.add(products1);
mArrayList.add(products2);
mArrayList.add(products3);
mArrayList.add(products4);
for (Products products : mArrayList) {
if (products.getitem().equals("Pens")) {
Log.d("Position", mArrayList.indexOf(products) + "");
}
}
This will give Output as
D/Position: 0
Upvotes: 1
Reputation: 2011
You can run a for loop to get job done .
private int getItempos(ArrayList<TasksCharts> mArrayList, String str)
{
for(int i=0;i<mArrayList.size();i++)
{
if(mArrayList.get(i).item.indexOf(str)!=-1)
{
return i;
}
}
return -1;
}
Hope this helps!
Upvotes: 2
Reputation: 44814
Does a TasksCharts
Object containing pens
equal a String Object containing pens
?
Unless you have overriden the equals method I would say "no".
I would recommend that you use a Map instead or you will have to loop through looking for a TasksCharts
Object containing pens
Upvotes: 2