dcp3450
dcp3450

Reputation: 11187

How do I store multiple values in an array in Android?

For this example I have an array:

String[] books = new String[x];

I would like to store the id and title in each location:

books[0]=>id:0, title:"book title1"
books[0]=>id:1, title:"book title2"
books[0]=>id:2, title:"book title3"
books[0]=>id:3, title:"book title4"

I want to store the id since it may change. I'm getting the id and title from a database. Getting the info isn't the issue. I want to store it this way so in my other functions this returns to I can use something like:

btn.setText(regions[i].title)

Any suggestion on how to handle this would be great.

Upvotes: 1

Views: 6913

Answers (3)

Mohan Raj
Mohan Raj

Reputation: 590

Do one thing, first create a bean class like BookBean. Under this declare two variables ID and Title. and declare getters and setters (If u are using eclipse u can easily do this by (Source -> generate getters and setters.. option) and then declare a ArrayList to store BookBean vale as of follow.

 ArrayList<BookBean> bookArrayList=new ArrayList<BookBean>();

   for(int i=0;i<=urSize;i++)
   {
    // create a object for BookBean 
    BookBean book =new BookBean();
    book.setID("what ever");
    book.setTitle("what ever");
    bookArrayList.ass(book)
    }

Upvotes: 3

Ram kiran Pachigolla
Ram kiran Pachigolla

Reputation: 21191

It is better to use Arraylist with custom class.

see this

class Book
{
   String id,title;

   /* Cunstructor to store data */
   public Book(String id,String title) 
   {
       this.id = id;
       this.title = title;
   }
}

//declare arraylist
ArrayList<Book> bookList = new ArrayList<Book>();
bookList.add("1","book1");
bookList.add("2","book2");
bookList.add("3","book3");
bookList.add("4","book4");

btn.setText(bookList.get(i).title)

Upvotes: 2

Viswanath Lekshmanan
Viswanath Lekshmanan

Reputation: 10083

I think you have several options

  • Use a HashMap where you can use your id as key and value title

  • Define a class and keep id and title as attributes , define get and set methods.

Keep the objects of the class in a ArrayList

Upvotes: 1

Related Questions