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.
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());
}
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]);
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());
}
Related
I have this kind of a table to deal with:
The path for the headers is:
List<WebElement> headers;
headers = driver.findElements(By.xpath("//*[#id=\"table1\"]/thead/tr/th"));
The path for the table body is:
List<WebElement> dataTable;
dataTable = driver.findElements(By.xpath("//*[#id=\"table1\"]/tbody/tr/td"));
List of headers has size of 6, list of dataTable has size of 24.
I am trying to put this to a list of maps
List<Map<String, String>> listOfMaps = new ArrayList<Map<String,String>>();
So far I've managed to add just the first entry:
for (int i = 0; i < headers.size(); i++) {
mapa.put(headers.get(i).getText(), dataTable.get(i).getText());
}
and the output is:
{Last Name=Smith, First Name=John, Email=jsmith#gmail.com, Due=$50.00, Web Site=http://www.jsmith.com, Action=edit delete}
But if I put it to the loop where row size = 4, it will give me a list of 4 same maps.
What do I have to do to make it work? I would like to have that kind of format (list of maps) so I can send it as a JSON in API POST testing.
Thank you for your help!
Example input
class WebElement {
private final String text;
public WebElement(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
List<WebElement> header = List.of(
new WebElement("Last Name"),
new WebElement("Name"),
new WebElement("Email"),
new WebElement("Due"),
new WebElement("Web Site"),
new WebElement("Action")
);
List<WebElement> dataTable = List.of(
new WebElement("Smith"),
new WebElement("John"),
new WebElement("jsmith#gmail.com"),
new WebElement("$50.00"),
new WebElement("http://www.jsmith.com"),
new WebElement("edit delete"),
new WebElement("Pippo"),
new WebElement("Pluto"),
new WebElement("pippo.pluto#gmail.com"),
new WebElement("$40"),
new WebElement("http:pippo.com"),
new WebElement("edit"),
new WebElement("Ciao"),
new WebElement("Adam"),
new WebElement("adam.ciao#gmail.com"),
new WebElement("$60"),
new WebElement("http://ciao.com"),
new WebElement("delete")
);
List<Map<String, String>> listOfMaps = new ArrayList<>();
for(int i = 0; i < dataTable.size(); i = i + header.size()) {
Map<String, String> mapa = new HashMap<>();
for(int j = 0; j < header.size(); j++) {
mapa.put(header.get(j).getText(), dataTable.get(i + j).getText());
}
listOfMaps.add(mapa);
}
Example output:
listOfMaps.forEach(map -> System.out.println(map));
{Action=edit delete, Email=jsmith#gmail.com, Web Site=http://www.jsmith.com, Due=$50.00, Last Name=Smith, Name=John}
{Action=edit, Email=pippo.pluto#gmail.com, Web Site=http:pippo.com, Due=$40, Last Name=Pippo, Name=Pluto}
{Action=delete, Email=adam.ciao#gmail.com, Web Site=http://ciao.com, Due=$60, Last Name=Ciao, Name=Adam}
I m trying to store all these elements and i m getting error like java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 and I'm not sure what my mistakes are.
public List<AddUserInformation> insertData(AddUserDetail user) {
List<AddUserInformation> inserted = null;
try{
List<AddUserInformation> addUserInformation = new ArrayList<AddUserInformation>() ;
ArrayList accName = new ArrayList();
for (int i = 0; i < user.getListofaccounts().toArray().length ; i++) {
accName.add(user.getListofaccounts().get(i).getAccountName());
}
List<AddUserInformation> addUserInformation1 = new ArrayList<AddUserInformation>();
for (int i = 0; i< accName.toArray().length; i++) {
addUserInformation1.get(i).setUserID(user.getUserId());
addUserInformation1.get(i).setUsername(user.getUsername());
addUserInformation1.get(i).setPassword(user.getPassword());
addUserInformation1.get(i).setEmailid(user.getEmailid());
List<AddUserAccountDetails> adduseraccountdetails = new ArrayList<>();
addUserInformation1.get(i).setAccountName(user.getListofaccounts().get(i).getAccountName());
addUserInformation1.get(i).setPermission_id(user.getListofaccounts().get(i).getPermission_id());
}
inserted = adduserInformationDao.saveAddUserInfo(addUserInformation1);
} catch (Exception e) {
LOGGER.error("Exception in adding of account to a user " + user.getUsername(), e);
}
return inserted;
}
The thing is accName contains number of accounts lets say 'n' as list and in the second "for" loop finally to replaces new values and showing last list values.
The statement:
List<AddUserInformation> addUserInformation1 = new ArrayList<AddUserInformation>();
creates a new empty ArrayList, so when you write addUserInformation1.get(i) in the for loop, you are trying to access the element at index 0 but the list is still empty (no element at 0), so you get the exception.
You must add something to your list (e.g., invoking add(...) method) before trying to get(...) elements.
As Robert mentioned, you are trying to access an element that is not exist.
Note: The List<AddUserAccountDetails> adduseraccountdetails = new ArrayList<>(); is never in use ..
You can create an object of class AddUserInformation then add it to your list like this:
public List<AddUserInformation> insertData(AddUserDetail user) {
List<AddUserInformation> inserted = null;
try{
List<AddUserInformation> addUserInformation = new ArrayList<AddUserInformation>() ;
ArrayList accName = new ArrayList();
for( int i = 0; i < user.getListofaccounts().toArray().length ; i++ ) {
accName.add(user.getListofaccounts().get(i).getAccountName());
}
List<AddUserInformation> addUserInformation1 = new ArrayList<AddUserInformation>();
for(int i = 0; i< accName.toArray().length; i++) {
AddUserInformation obj = new AddUserInformation ();
obj.setUserID(user.getUserId());
obj.setUsername(user.getUsername());
obj.setPassword(user.getPassword());
obj.setEmailid(user.getEmailid());
obj.setAccountName(user.getListofaccounts().get(i).getAccountName());
obj.setPermission_id(user.getListofaccounts().get(i).getPermission_id());
addUserInformation1.add(obj);
}
inserted = adduserInformationDao.saveAddUserInfo(addUserInformation1);
}catch (Exception e) {
LOGGER.error("Exception in adding of account to a user " + user.getUsername(), e);
}
return inserted;
}
I have a problem with my code, because it throws NullPointerException when I try to assign string from arraylist to array.
String[][] data = new String[idList.size()][];
for(int i = 1; i<=idList.size(); i++) {
data[i][0] = idList.get(i);
data[i][1] = nameList.get(i);
data[i][2] = hList.get(i);
data[i][3] = sList.get(i);
data[i][4] = fList.get(i);
data[i][5] = mList.get(i);
data[i][6] = osList.get(i);
data[i][7] = tsList.get(i);
data[i][8] = podList.get(i);
data[i][9] = pacList.get(i);
}
Can someone please tell me how do I fix that?
data[i] is null, since you initialized data to contain idList.size() null references of type String[].
Change
String[][] data = new String[idList.size()][];
to
String[][] data = new String[idList.size()][10];
which will initialize data to contain idList.size() references to a String array of length 10 (String[10]).
I suggest to define the array properly (in both dimensions )
replace this
new String[idList.size()][];
for something like
new String[idList.size()][10]; // you have 10 different lists there...
and iterate in the for loop with zero base...
Example:
String[][] data = new String[idList.size()][10];
for (int i = 0; i < idList.size(); i++) {
data[i][0] = idList.get(i);
data[i][1] = idList.get(i);
data[i][2] = idList.get(i);
data[i][3] = idList.get(i);
}
I don't really understand why this is happening. This is, by far, the weirdest error I've never come across.
The thing is I'm retrieving some info from a Server using Retrofit, and for that, I needed to create a POJO called POJO_PATIENTINFO. Inside this pojo, I have a BigDataset_PatientInfo variable called data. Inside this variable, I am storing a List<Dataset_RegVar> called registro_variable, inside of which I have these strings:
registro_var_id
registro_var_fecha
registro_var_descripcion
registro_var_variable
registro_var_medida
registro_var_comentario
No problems with that. The idea is that I want to recover these Strings from another Fragment.class, easy task I thought.
This is my piece of code for doing such an easy task:
int size = POJOS.getPojo_patientInfo().data.registro_variable.size();
int i = 0;
strVariable = strId = strFecha = strMedida = strDescripcion = strComentarios = new String[size];
for (POJO_PATIENTINFO.Dataset_RegVar dataset : POJOS.getPojo_patientInfo().data.registro_variable) {
strVariable[i] = dataset.registro_var_variable;
strId[i] = dataset.registro_var_id;
strFecha[i] = dataset.registro_var_fecha;
strMedida[i] = dataset.registro_var_medida;
strDescripcion[i] = dataset.registro_var_descripcion;
strComentarios[i] = dataset.registro_var_comentario;
i++;
}
After the first iteration, just before the "i++;" line executes, the String arrays are all storing exactly the same value, that is, the same value as dataset.registro_var_comentario. In a nutshell, the aforementioned piece of code is execute as if I was writing:
int size = POJOS.getPojo_patientInfo().data.registro_variable.size();
int i = 0;
strVariable = strId = strFecha = strMedida = strDescripcion = strComentarios = new String[size];
for (POJO_PATIENTINFO.Dataset_RegVar dataset : POJOS.getPojo_patientInfo().data.registro_variable) {
strVariable[i] = dataset.registro_var_comentario;
strId[i] = dataset.registro_var_comentario;
strFecha[i] = dataset.registro_var_comentario;
strMedida[i] = dataset.registro_var_comentario;
strDescripcion[i] = dataset.registro_var_comentario;
strComentarios[i] = dataset.registro_var_comentario;
i++;
}
Obviously, the first thing that came to my mind is that maybe all of these strings were holding the same value. No, they are not. I know this because I did some debugging work on my own. Let me paste some results (note that these images are for i=3): http://postimg.org/gallery/2gf1lj7qa/
I will provide more details if you think they are necessary. Thanks.
You are assigning one and the same String array to all those variables. So the last write to any of these variables overwrites the corresponding index in all the other variables aswell. And this happens to be this assignment:
strComentarios[i] = dataset.registro_var_comentario;
So instead of
strVariable = strId = strFecha = strMedida = strDescripcion = strComentarios = new String[size];
you need to write
strVariable = new String[size];
strId = new String[size];
strFecha = new String[size];
strMedida = new String[size];
strDescripcion = new String[size];
strComentarios = new String[size];
Funny reason: You are using same memory location for all the string array.
Why you are getting values of strComentarios in every array: Because a new memory location is assigned to it and you are using same memory location for other array. So whatever is updated in strComentarios, all other array get that value.
strVariable = strId = strFecha = strMedida = strDescripcion = strComentarios = new String[size];
Split it like this
strVariable = new String[size];
strId = new String[size];
strFecha = new String[size];
strMedida = new String[size];
strDescripcion = new String[size];
strComentarios = new String[size];
I am trying to populate a list view from an ArrayList but for some reason it only grabs the last record. The array holds the data correctly and if I change the I to a number it will print the selected value.
My code is below any help would be appreciated.
ArrayList<String> tests = new ArrayList();
for(HashMap<String, String> test : outageData){
String outagenumber = test.get("outagenum");
Log.v("Outage",outagenumber);
tests.add(outagenumber);
}
SectionListItem[] exampleArray = null;
for(int i = 0; i < tests.size(); i++) {
exampleArray = new SectionListItem[]{
new SectionListItem("test", tests.get(i)),
};
}
CustomOutageDetailListAdapter adapter = new CustomOutageDetailListAdapter(this, exampleArray);
sectionAdapter = new SectionListAdapter(getLayoutInflater(),
adapter);
This is the adapter for fill List.
public class SectionOutageListItem {
public Object item;
public String section;
public SectionOutageListItem(final Object item, final String section) {
super();
this.item = item;
this.section = section;
}
#Override
public String toString() {
return item.toString();
}
}
Updated Code:
SectionOutageListItem[] exampleArray = new SectionOutageListItem[outnums.size()];
for(int i = 0; i < outnums.size(); i++) {
exampleArray[i] =
new SectionOutageListItem("Impact", impacted.get(i), "Outage No. " + outnums.get(i)),
new SectionOutageListItem("status", status.get(i), "Outage No. " + outnums.get(i));
}
CustomOutageDetailListAdapter adapter = new CustomOutageDetailListAdapter(this, exampleArray);
sectionAdapter = new SectionOutageListAdapter(getLayoutInflater(),
adapter);
The issue is here:
for(int i = 0; i < tests.size(); i++) {
exampleArray = new SectionListItem[]{
new SectionListItem("test", tests.get(i)),
};
}
For each element in tests, you are creating a new exampleArray with a single item.
You should use:
SectionListItem[] exampleArray = new SectionListItem[tests.size()];
for(int i = 0; i < tests.size(); i++) {
exampleArray[i] = new SectionListItem("test", tests.get(i)),
}
Update this code:
SectionListItem[] exampleArray = null;
for(int i = 0; i < tests.size(); i++) {
exampleArray = new SectionListItem[]{
new SectionListItem("test", tests.get(i)),
};
}
with:
SectionListItem[] exampleArray = new SectionListItem[tests.size()];
for(int i = 0; i < tests.size(); i++) {
exampleArray[i]= new SectionListItem("test", tests.get(i));
}