1

In my simple java application i have this function to return ArrayList:

Items.java class:

package com.example.Hadis;

/**
 * Created by tux-world on 8/1/14.
 */
public class Items {

    public int id;
    public String content;
}

ArrayList function for fill and return result:

DataBaseHelper.java class's getFavorite function :

public ArrayList<Items> getFavorite(){
    ArrayList<Items> arrayList = new ArrayList<Items>();

    do {

        Items dbItems = new Items();

        dbItems.id = cursor.getInt(0);
        dbItems.content = cursor.getString(1);
        arrayList.add(dbItems);
    } while (cursor.moveToNext());

    return arrayList;
}

i want to fetch this return ArrayList and fill HashMap but i can not program this part of project

Defined map as Method in class:

    static Map<Integer,String> map = new HashMap<Integer,String>();

retrive ArrayList and my problem is this:

    DatabaseHandler db = new DatabaseHandler(ApplicationHadith.this);
    ArrayList<Items> list = db.getFavorite();

    Iterator<Items> it = list.iterator();
    while(it.hasNext())
    {

      // map.put( it.id , it.content )

    }

how to retrive getFavorite() and fill HashMap? please help me.Thanks

3
  • What specifically is your problem ? Commented Aug 1, 2014 at 16:27
  • 1
    @BrianAgnew retrive getFavorite() and fill HashMap map Commented Aug 1, 2014 at 16:28
  • Please don't post duplicate questions just because you don't get the answer you want in 30 minutes. Commented Aug 1, 2014 at 16:53

3 Answers 3

4

Just use a simple for loop e.g.

for (Item item : list) {
   map.put( item.id, item.content);
}

I wouldn't normally use an Iterator in this scenario. The enhanced for-loop syntax above dates from Java 5.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow you just barely beat me to it! I'll remove mine since it's a duplicate.
1

You need to use the iterator's next() method to get the instance of Items :

Iterator<Items> it = list.iterator();
while(it.hasNext())
{
  Items item = it.next();
  map.put( item.getID() , item );

}

Comments

1
while(it.hasNext())
    {
Item item = (Item) it.next();

       map.put( item.getId() , item.getContent() )

    }

Have getters generated for id and content

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.