1

I have an Array to hold the value from DB. If I try with some default data it working fine but if I get value from DB, its only showing last value.

Default Data;

MenuList menu_data [] = new MenuList[]{};
menu_data  = new MenuList[]
{
new MenuList("test","test1") ,      
new MenuList("test","test1") ,  
new MenuList("test","test1") ,  
new MenuList("test","test1") ,  
new MenuList("test","test1") ,  
new MenuList("test","test1") ,  
new MenuList("test","test1") ,  
new MenuList("test","test1") ,  
new MenuList("test","test1") ,  
new MenuList("test","test1") ,  
new MenuList("test","test1") 
};

Value from DB,

MenuList menu_data [] = new MenuList[]{};
List<Menu> profiles = db.getAllContacts();
for (Menu cn : profiles) {
menu_data  = new MenuList[]
{
new MenuList(cn.getmenuname(), cn.getmenuprice())  
};
}

How do I get all the value from DB.

2
  • have you tried menu_data = profiles.toArray()? Commented Mar 30, 2012 at 3:28
  • in my profiles I have few values like menu,price,Vege,Time,Date...I just want to show menu and price.... Commented Mar 30, 2012 at 3:30

3 Answers 3

3

Everytime you go through the loop, you are creating a new array. Hence, only the last value is available. Please try the following

menu_data  = new MenuList[profiles.size()];

for (int i = 0; i < menu_data.length; i++) {
    Menu cn = profiles.get(i);
    menu_data[i] = new MenuList(cn.getmenuname(), cn.getmenuprice());  
}
Sign up to request clarification or add additional context in comments.

4 Comments

you need to declare and initialize i variable: int i = 0; and in the loop: ` menu_data[i++] = ...`
@LuiggiMendoza Missed that completely! Thanks
it throw java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
@chinna_82 Which line is the exception thrown at?
2

Try this:

List<MenuList> menulists = new ArrayList<MenuList>();
for (Menu cn : db.getAllContacts())
    menulists.add(new MenuList(cn.getmenuname(), cn.getmenuprice()));
MenuList[] menu_data = menulists.toArray(new MenuList[0]);

Comments

2
List<Menu> profiles = db.getAllContacts();
int numProfiles = profiles.size();
MenuList[] menu_data = new MenuList[numProfiles];
for (int i = 0; i < numProfiles; i++) {
    Menu cn = profiles.get(i);
    menu_data[i] = new MenuList(cn.getmenuname(), cn.getmenuprice());
}

2 Comments

it throw 2 error.. 1st. Cannot define dimension expressions when an array initializer is provided..2nd java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
Sorry, I meant to just create it instead of using the initializer. Fixed. If length = 0 then the for loop body will not be executed at all.

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.