I want to copy specific data from one list to another. It shows
ERROR:
java.lang.NullPointerException
at controllers.WebForms.getMenu(WebForms.java:134)
at Routes$$anonfun$routes$1$$anonfun$applyOrElse$2$$anonfun$apply$2.apply(routes_routing.scala:222)
List<menu> allMenus = menu.find.all();
List<menu> selectedMenu=null;
System.out.println("selected menu:"+selectedMenu);//prints: null
int count = 0;
for (models.menu m : allMenus) {
System.out.println("m:"+m);
if (m.r_id == r_id) {
count=1;
System.out.println("r_id:"+m.r_id+" "+m.item);
//prints: r_id:1 Noodles
selectedMenu.add(m);
//throws NULLPointer Exception
System.out.println("selected menu inside loop:"+selectedMenu);
}
}
List<menu> selectedMenu = new ArrayList<>();. You have to initialise the list before you perform operations on it.
List selectedMenu = new ArrayList<>();
Related
I am new to test automation and i am currently working on a personal project
I have this method in which it finds all the links for a section on the page, clicks on each link, irritates through each tab and then gets the title of each page
However, i want a way to verify the titles of these links against a list of expected titles
What would be the best approach to modify this in order to do this? would it be better to store in an array and then assert/verify each title separately?
I have tried a few ways to assert by changes return type to String and also to List but with no luck
public void linksAreWorkingDashBoardLeftPanal() throws Exception {
List<WebElement> li_All = links_myAccountNav.findElements(By.tagName("a"));
for(int i = 0; i < li_All.size(); i++){
String clickOnLinkTab = Keys.chord(Keys.CONTROL, Keys.ENTER);
links_myAccountNav.findElements(By.tagName("a")).get(i).sendKeys(clickOnLinkTab);
Thread.sleep(5000);
}
//Opens all the tabs
Set<String> getTitleinWindow = driver.getWindowHandles();
Iterator<String> it = getTitleinWindow.iterator();
while(it.hasNext())
{
driver.switchTo().window(it.next());
System.out.println(driver.getTitle());
}
Modify the while loop as follows;
List<String> expectedTitleList = new ArrayList<>();
// Get the expected titles in a list.
// You have to initiate and add expected titles to this list, before running the while loop.
List<String> actualTitleList = new ArrayList<>();
while(it.hasNext())
{
driver.switchTo().window(it.next());
actualTitleList.add(driver.getTitle());
}
// Create copies of each list;
Set<String> expectedSet = new HashSet<>(expectedTitleList);
Set<String> actualSet = new HashSet<>(actualTitleList);
Set<String> expectedOnlySet = new HashSet<>(expectedSet);
Set<String> actualOnlySet = new HashSet<>(actualSet);
expectedOnlySet.removeAll(actualSet);
actualOnlySet.removeAll(expectedSet);
// Check if expectedOnlySet and actualOnlySet are empty
// If both of them are empty then all titles are received as expected.
boolean isEmpty = (expectedOnlySet.size() == 0 && actualOnlySet.size() == 0);
if (expectedOnlySet.size() > 0 || actualOnlySet.size() > 0) {
// If expectedOnlySet contain any title; it means those titles are not opened in the browser.
// If actualOnlySet contain any title; it means those titles are not expected titles.
StringBuilder message = new StringBuilder();
for (String x: expectedOnlySet) {
message.append("Did not receive: ");
message.append(x).append(", ");
}
for (String y: actualOnlySet) {
message.append("Not expected but received: ");
message.append(y).append(", ");
}
Assert.assertTrue(false, message,toString());
}else {
Assert.assertTrue(true);
}
Here you can use removeAll() method in Collections. Check the documentation
We have to check both scenarios;
Whether all expected titles are received
All received titles are expected
Thanks! I took what i needed from your code and it worked perfectly.
this work and i added my own assertion
List<WebElement> li_All = links_myAccountNav.findElements(By.tagName("a"));
for(int i = 0; i < li_All.size(); i++){
String clickOnLinkTab = Keys.chord(Keys.CONTROL, Keys.ENTER);
links_myAccountNav.findElements(By.tagName("a")).get(i).sendKeys(clickOnLinkTab);
}//Opens all the tabs
Set<String> getTitleinWindow = driver.getWindowHandles();
Iterator<String> it = getTitleinWindow.iterator();
// Get the expected titles in a list.
// You have to initiate and add expected titles to this list, before running the while loop.
List<String> expectedTitleList = new ArrayList<>();
expectedTitleList.add("Page 1 title");
expectedTitleList.add("Page 2 title");
expectedTitleList.add("Page 3 title");
expectedTitleList.add("Page 4 title");
expectedTitleList.add("Page 5 title");
expectedTitleList.add("Page 6 title");
expectedTitleList.add("Page 7 title");
List<String> actualTitleList = new ArrayList<>();
while(it.hasNext())
{
driver.switchTo().window(it.next());
actualTitleList.add(driver.getTitle());
}
//System.out.println(expectedTitleList);
// System.out.println(actualTitleList);
if(actualTitleList.equals(expectedTitleList)).....
I'm in the process of building a basic database using csv files, and i'm currently testing the select function out when i ran into something strange.
private ArrayList<Record> selectField(String selectTerm)
{
Log.log("Selection " + selectTerm,2,"DB_io");
ArrayList<Record> ret = new ArrayList<Record>();
if (titleRow.values.contains(selectTerm))
{
Log.log("Adding values to " + selectTerm);
int ordinal = titleRow.values.indexOf(selectTerm);
Log.log("Ordinal " + ordinal);
List<String> tempList = new ArrayList<String>();
for (Record r : data)
{
List<String> tempList = new ArrayList<String>();
tempList.add(r.values.get(ordinal));
Record s = new Record(tempList);
ret.add(s);
tempList.clear();
}
Log.log("Number of records in ret " + ret.size());
for (Record t : ret)
{
Log.log(t.toString());
}
}
else
{
Log.log("keyField does not contain that field");
return null;
}
Log.log("Values " + ret.toString());
return ret;
}
When i do this, the part where it logs t.ToString() shows the record to be empty, whereas if i log it before tempList.clear(), it shows the record to be containing data like it should.
If i move the tempList declaration into the Record r : data loop, then it works fine and the Record t : ret loop works outputs the contents of the record like it should
Why is this?
Edit : Record class
public class Record
{
List<String> values = new ArrayList<String>();
public Record(List<String> terms)
{
this.values = terms;
}
public Record(String[] s)
{
this.values = Arrays.asList(s);
}
public String toString()
{
return values.toString();
}
}
Your Record instance holds a reference to the ArrayList instance you passed to its constructor. Therefore, when you call tempList.clear(), you clear the same List that your Record instance is holding a reference to.
You shouldn't call tempList.clear(), since you are creating a new ArrayList in each iteration of your loop anyway.
you are referencing object from more than one place and clear method is cleaning object by setting its reference to null:
instead of ret.add(s); you can use ret.add(s.clone());
I have seen this 2d Arraylist Question multiple times on SO, but don't understand why this doesn't work for my Language App.
I have an arraylist (called stage1) containing multiple arraylists (each is called entry) The System.out.println("In switch: this is entry" + entry); displays the database values correctly so I am sure that the query string elsewhere is correct (e.g. [In switch: this is entry[water, aqua, C:\Users\Username\Documents\NetBeansProjects\LanguageApp\src\Images\Categories\Food images\water.png])
But when I add entry to stage 1 and try to access it via stage1.get(0).get(0) I get the error "Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0" which is why I tested if stage1 is empty. The other trace statement confirms that stage1 is null even after entries are added.
ArrayList<List<String>> stage1 = new ArrayList<>();
ArrayList<String> entry = new ArrayList<>();
int count = 0;
//words is an Observable List of all words relating to a specific category and langage
for (Words k : words) {
String eng = k.getEnglishWord();
String trans = "";
switch (lang) {
case "spanish":
trans = k.getSpanishWord();
break;
case "french":
trans = k.getFrenchWord();
break;
case "german":
trans = k.getGermanWord();
break;
}
String pic = k.getPicture();
entry.add(eng);
entry.add(trans);
entry.add(pic);
System.out.println("This is entry" + entry);
stage1.add(entry);
entry.clear();
if(stage1.size()!=0){ System.out.println("Stage1 " + stage1.get(0).get(0));
}
else {System.out.println("IT IS NULL");}
}
You are using single object at each time that's why it gives index out of bounds exception
Just place your arraylist into the for loop
ArrayList<String> entry = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
//put you code here
ArrayList<String> entry = new ArrayList<String>();
entry.add("sd");
entry.add("sd");
entry.add("sd");
System.out.println("This is entry" + entry);
stage1.add(entry);
//entry.clear();
if(stage1.size()==0){ System.out.println("Stage1 " + stage1.get(0).get(0));
}
else {System.out.println("IT IS NULL");}
}
This will give's you desired output.
Every object in Java are reference Object. When you pass an object trought parameters of function, you pass the reference. If you modify the object inside or outside the method you will modify the object in and or out of the function.
I suggest you to take a look to it to clear your mind about all this.
Is Java "pass-by-reference" or "pass-by-value"?
Now, to solve your problem, you can reinstanciate you entre with entry = new ArrayList(); and the begiining of each loop and remove the entry.clear();.
ArrayList<List<String>> stage1 = new ArrayList<>();
ArrayList<String> entry = null;
int count = 0;
//words is an Observable List of all words relating to a specific category and langage
for (Words k : words) {
entry = new ArrayList<>();
String eng = k.getEnglishWord();
String trans = "";
switch (lang) {
case "spanish":
trans = k.getSpanishWord();
break;
case "french":
trans = k.getFrenchWord();
break;
case "german":
trans = k.getGermanWord();
break;
}
String pic = k.getPicture();
entry.add(eng);
entry.add(trans);
entry.add(pic);
System.out.println("This is entry" + entry);
stage1.add(entry);
//entry.clear();
if(stage1.size()!=0){ System.out.println("Stage1 " + stage1.get(0).get(0));
}
else {System.out.println("IT IS NULL");}
}
I am using temboo to get all the events for a calendar. However, i am trying to create a hashtable of the events and the days. but the for loop says its a null pointer exception even though the program is actually able to access that ith element. I have even printed it and the i is less than the size of the array. Here is the snippet code: Error is in the second line of the for loop.Errr occurs when i = 23, but items.size is 41.
GetAllEvents getAllEventsChoreo = new GetAllEvents(session);
// Get an InputSet object for the choreo
GetAllEventsInputSet getAllEventsInputs = getAllEventsChoreo.newInputSet();
// Set inputs
getAllEventsInputs.set_AccessToken(accessToken);
getAllEventsInputs.set_ClientID(clientID);
getAllEventsInputs.set_ClientSecret(clientSecret);
getAllEventsInputs.set_CalendarID(callIDs[0]);
// Execute Choreo
GetAllEventsResultSet getAllEventsResults = getAllEventsChoreo.execute(getAllEventsInputs);
results = getAllEventsResults.get_Response();
System.out.println(results);
root = jp.parse(results);
rootobj = root.getAsJsonObject();
JsonArray items = rootobj.get("items").getAsJsonArray();
System.out.println("Abour to enter the for loop\nItems:\n"+items.toString());
System.out.println("****************************\nEnter the for loop");
System.out.println("iems Size: "+items.size());
System.out.println(items.get(23).toString());
for(int i = 0;i < items.size();i++)
{
System.out.println("i: "+i);
String startTime = items.get(i).getAsJsonObject().get("start").getAsJsonObject().get("dateTime").getAsString();
System.out.println("startTime: "+startTime);
String dayKey = startTime.split("T")[0];
if(dayKey.equals(beginDate)==false | dayKey.equals(endDate)==false)
{
System.out.println(startTime + " not the one interested so skipping");
continue;
}
System.out.println("passed the first if in for loop");
String endTime = items.get(i).getAsJsonObject().get("end").getAsJsonObject().get("dateTime").getAsString();
String name = items.get(i).getAsJsonObject().get("summary").getAsJsonPrimitive().getAsString();
calendarEvent eventTemp = new calendarEvent(name,startTime,endTime);
if(table.containsKey(dayKey))
table.get(dayKey).add(eventTemp);
else
{
ArrayList<calendarEvent> schedule = new ArrayList<calendarEvent>();
schedule.add(eventTemp);
table.put(dayKey,schedule);
}
}
Set<String> key = table.keySet();
Iterator<String> it = key.iterator();
while(it.hasNext())
{
String keyValue = it.next();
System.out.println("Events on "+keyValue);
ArrayList<calendarEvent> temp = table.get(keyValue);
for(int j =0;j<temp.size();j++)
{
System.out.println(temp.get(j));
}
}
After breaking down the exception line, the exception occurs when I try to get the dateTime as string, the last part creates an exception.
Just because the ith element of an array exists, it does not mean that the element is not null.
Referencing a property or method of such an element will yield a NullPointerException.
If i went beyond the bounds of the array, you would get an ArrayIndexOutOfBoundsException instead.
Check indexed array elements for null before using them.
Sorry to be brief and not reference your code or other sources. I am on my phone. The likely source of your problem is pretty clear, though.
If i want to add an ArrayList to a JList, it is not shown in the list, but the array contains the items. How could i fix this?
public void updateLeftList(){
// Enter the search text
interFace.Search.setText(this.search);
// Get the left list
JList leftList = interFace.LeftList;
leftList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
// Define the arraylists
allPdf = new ArrayList();
curPdf = new ArrayList();
addPdf = new ArrayList();
// Get Files from manuals folder
File files = new File(configFile.getProperty("dir") + "/" + this.taal);
File[] listFiles = files.listFiles();
for(int i = 0; i < listFiles.length; i++){
if(listFiles[i].getName().endsWith(".pdf") && listFiles[i].isFile()){
allPdf.add(listFiles[i].getName().toString());
}
}
leftList.setListData(allPdf.toArray());
}
use ListModel to add the data:
1. create new instance of DefaultListModel
2. add your file names to the list model
3. set it as your JList list model
for(Object item : arrayList.toArray()){
((DefaultListModel) list1.getModel()).addElement(item);
}