Parsing JSON and deleting objects from it is giving error - java

I have a phonegap application and I want to prune the pictures before downloading.
I am passing a JSON object to my function which is
[{"name":"aaa.jpg","link":"https:\/\/www.abc.com\/aaa.jpg"},"name":"bbb.jpg","link":"https:\/\/www.abc.com\/\/bbb.jpg"}]
And using the following function to parse and delete
function prunePictures(pictures) {
for ( var i = 0; i < entries.length; ++i) {
var name = entries[i].name;
$.each(pictures, function(i, obj) {
if (obj.name == name) {
delete pictures[i];
}
});
}
}
But its not going through the loop and I am getting an error "Cannot read property 'name' of undefined"

...you don't want to delete the picture object.
You want to splice it out of the array.
Deleting it leaves a hole in the array, whereas splicing it removes the hole.
var l = entries.length, i = 0, pictureName;
for (; i < l; i += 1) {
pictureName = entries[i].name;
pictures.forEach(function (picture, i, arr) {
if (pictureName === picture.name) { arr.splice(i, 1); }
});
}
Removes the object in pictures if an object in entities has the same name property.

your json string is missing a brace:
[{"name":"aaa.jpg","link":"https:\/\/www.abc.com\/aaa.jpg"},{"name":"bbb.jpg","link":"https:\/\/www.abc.com\/\/bbb.jpg"}]
Edit
I think your json just had a typo, since that's not the error you would get.
You shouldn't delete out of a $.each instead you should use $.grep
see info here
pictures = $.grep(pictures, function(obj,i) {
if (obj.name == name) {
return false;
}
return true;
});

Related

Problems when instantiating and initializing objects

I've been coding one of my final school projects related to a text file based on weddings.
I am trying to code a method that will return a wedding object,
(NOTE: weeding object consists of a brideName, groomName, weddingDate, Venue, number of Guests).
In a normal method using Strings. For example, I would merely type
String temp = "";
run a loop to loop through my array. if statement
temp = temp + arr[loop].toString();
return temp;
But now dealing with a wedding object when I declare it:
Wedding temp; - (As i cant initialize it as there is no brideName etc.)
run loop
if statement
temp = temp + array[loop];
return temp;
Here is where i get the error of temp may not have been initialized.
Could anyone help with a suggestion of how to fix this? Thank you so much
Here is what the actual method looks like
public Wedding getWeddingsOnDay(String date, String venue)
{
Wedding temp;
for (int loop = 0; loop < counter; loop++)
{
if (wedArr[loop].getWeddingDate().equals(date) && wedArr[loop].getVenue().equals(venue))
temp = wedArr[loop];
else
temp = null;
}
return temp;
}
Rewrite the method this way.
public Wedding getWeddingAt(String date, String venue) {
for (Wedding w : wedArr)
{
if (w.getWeddingDate().equals(date) &&
w.getVenue().equals(venue)) {
return w;
}
}
return null;
}
Your code will say this obviously beacise it is possible that you code will not go into the if block and temp varialble remain unintilized . So , anyone using it need to check null value before using this temp variable .
There are several ways you can remove this error :
Ignore this error. As this error will not stop running your code .
you can use optional intead of returing null , after this your method will lokks like below method :
public Optional<Wedding> getWeddingsOnDay(String date, String venue){
Optional<Wedding> temp;
for (int loop = 0; loop < counter; loop++) {
if (wedArr[loop].getWeddingDate().equals(date) && wedArr[loop].getVenue().equals(venue)) {
temp = Optional.of(wedArr[loop]);}
else{
temp = Optional.empty();
}
}
return temp;
}
You need not to use temp at all just return wedArr[loop] or null

updating an object in object array angularjs

I am trying to update one particular entry in the entire array based on id value. If I try using the for loop it shows some undesired output. please let me know what can be done on this. Sample code which I tried as follows,
angular.module('app').controller('MyController', function($scope) {
$scope.object = {
name: 'test',
objects: [
{id: 1, name: 'test1'},
{id: 2, name: 'test2'}
]
};
$scope.update = function(id, data) {
var objects = $scope.object.objects;
for (var i = 0; i < objects.length; i++) {
if (objects[i].id == id) {
objects[i].name = data;
break;
}
}
}
});
Is this code supposed to update the name property of an object?
If yes
You should change this line of your for loop:
objects[i] = data;
To:
objects[i].name = data;
If no
You are trying to replace an object you are iterating over. It may create issues in the looping. If so, you would better to update each property instead of trying to overwrite the whole object.

find and return an element of an array in java

So I've been trying to figure this out on my own for the past couple of hours but I'm stuck.
I have an array that has a list of a person's name, age, height (in cm). I want to create a method where I use only the person's name as a parameter and searches for the name in the array; if there is no matching name, return null.
Looks like this:
data = new data[50];
data[0] = new data("Dan", 23, 179);
data[1] = new data("David", 20, 180);
data[2] = new data("Sharon", 19, 162);
data[3] = new data("Jessica", 22, 160);
data[4] = new data("Nancy", 25, 164);
...
numberData = 30; // this is the number of people that are in this array so far
This is what I've been trying so far..
public data findData(String name) {
for (int i = 0; i < numberData; i++) {
if (name == data[i]) {
return data[i];
} else {
return null;
}
}
}
I know it isn't right, but I can't seem to find a solution. Any ideas?
array is referencing the Data class with name parameter so we should compare with name parameter not directly with reference of data and for string comparisons always go for equals() method.
public Data findData(String name) {
for (int i = 0; i < numberData; i++) {
if (name.equals(data[i].getName())) {
return data[i];
}
}
return null;
}
Since you want to compare strings you must use the equals method.
Here's an example of how can you use java 8:
public Data findData(Data[] datas, String name) {
return Arrays.stream(datas).filter(data -> data.getName().equals(name)).findAny().orElse(null);
}
In case the loop doesn't execute at least once, you're missing return value.
== compares references, equals compares Strings.
Return null just in case, there is no such element in the array.
Class names should start with a capital letter. Please write Data instead of data.
Code:
public Data findData(String name) {
for (Data d : data) {
if (name.equals(d.getName())) {
return d;
}
}
return null;
}
is what you're looking for. In the original code, null was returned if the 0th element wasn't name.
OK, the above was a quick fix and now some theory:
The pseudo code for linear search in an array:
Loop through all elements in an array. If any matches with the one you're looking for, return it.
If nothing was returned, return the indicating value (null in our case).
Look, in the original code, on the 0th element, you decided whether to return that element or a null. Also, if the loop wasn't run at least once, there was no return statement to hit.
Use equals() to compare strings,
e.g.
if(name.equals(data[i].getName())) {
statements...
}
You should use equals() to compare strings. equals() checks the actual contents of the string, == checks if the object references are equal.
And also, as mentioned above, move return null outside the loop;
You can use following code. Assuming that your data class will have getName() method which returns the name value.
public data findData(String name) {
for (int i = 0; i < numberData; i++) {
if (name.equals(data[i].getName())) {
return data[i];
}
}
return null;
}
move the return null statement out of the loop.
Oh! and yes, use the equals() method instead of ==

Error handling for a while loop

I need help with this scenario where I need to find a string from a pagination table wherein each page contains 50 items. My code below works fine, only problem is that when it cannot find the data my while loop sometimes keep running indefinitely and does not fail but sometimes it does! What can I do so that it will always return an error after reaching a number of loops?
public int inboxLocateLoan(String expName, String name) throws Throwable {
//Locate Loan element in SharePoint table
report.setFailedResult("Loan element is not found");
int loanRow;
try {
boolean loansearch = true;
while (loansearch) {
List < WebElement > rowElem = getWebElements(getAEDriver(), "xpath", sRow);
for (int i = 1; i <= rowElem.size(); i++) {
String actualLoanName = driver.findElement(By.xpath("//*[#id='onetidDoclibViewTbl0']/tbody[2]/tr[" + i + "]/td[3]")).getText();
// String actualLoanNumber = driver.findElement(By.xpath("//*[#id='onetidDoclibViewTbl0']/tbody[2]/tr["+i+"]/td[5]")).getText();
loanRow = i;
if (actualLoanName.equals(expName)) {
loansearch = false;
return loanRow;
}
if (actualLoanName.equals(name)) {
click(getAEDriver(), "xpath", "//*[#class='ms-pivotControl-surfacedOpt-selected']", "Refresh");
loansearch = true;
} else {
if (i == 50) {
click(getAEDriver(), "xpath", "//*[#id='pagingWPQ2next']/a", "Next Page");
} else {
loansearch = true;
}
}
}
}
}
Initialize the romElem outside the for, and then use it to toggle your flag. If you reached your max rowElemen and you didn't find what you were looking for, it is safe then to assume that the value will be false.
Also, what is the purpose of the while? you could remove it completely, it is usually a bad idea to mix a while and a for. I don´t see the point in doing so in this case.

Insert Method in a BinarySearchTree

Hey i have written some kind of Binary Search Tree, which has a insert method.
So it gets a Object to insert, a Char Array and a Integer which gives it the Index to look at.
So this is the insert method :
public void insert(Buchstabe pBuchstabe,char[] pChar,int pStelle)
{
if(pBuchstabe==null)
return;
if(baum.isEmpty())
{
baum=new BinaryTree(pBuchstabe);
}
else
if(pStelle <= pChar.length)
{
if(pChar[pStelle] == '.')
{
Mybaum lTree=this.getLeftTree();
lTree.insert(pBuchstabe,pChar,pStelle+1);
this.baum.setLeftTree(lTree.baum);
}
else
if(pChar[pStelle]=='-')
{
Mybaum lTree=this.getRightTree();
lTree.insert(pBuchstabe,pChar,pStelle+1);
this.baum.setLeftTree(lTree.baum);
}
}
}
I have a Method which passes the required Parameters (in this case) : A Object Buchstabe,then the Char Array['.','.'] and the integer 0 to the insert method.
And i get a out of bounds error :
java.lang.ArrayIndexOutOfBoundsException: 2
at Mybaum.insert(Mybaum.java:22)
at Mybaum.insert(Mybaum.java:25)
at Mybaum.insert(Mybaum.java:25)
at Mörserbaum.einlesen(Mörserbaum.java:42)
Does anyone know what ive made wrong ?
Looks like you have an issue
if(baum.isEmpty())
{
baum=new BinaryTree(pBuchstabe);
}
else
**if(pStelle <= pChar.length)**
{
**if(pChar[pStelle] == '.')**
{
Mybaum lTree=this.getLeftTree();
lTree.insert(pBuchstabe,pChar,pStelle+1);
this.baum.setLeftTree(lTree.baum);
}
if(pChar[pStelle] == '.') -- you get indexOutOfBound bc/ you need to say
if(pChar[pStelle-1] == '.') .. since Java array index starts from 0, if the length is 5, last index would be pChar[4]...
there could be more issues with this code, since we don't have full code/context i can't speculate more.. but this is one of the reason you could get indexoutofbound
public void einlesen()
{
Buchstabeenschlange sch = new Buchstabeenschlange();
for(int i = 0;i<codeTabelle.length;i++)
{
Buchstabe a = new Buchstabe(alphabet[i],codeTabelle[i]);
if(a == null)
{
System.out.println("Buchstabe mit Error == "+a);
}
System.out.println("Buchstabe == "+a);
sch.hinzufuegen(a);
System.out.println("------------");
}
List l = sch.gibListe();
sch.druckeListe();
l.toFirst();
while(l.hasAccess())
{
Buchstabe buch = (Buchstabe) l.getObject();
char[] code = buch.getCode().toCharArray();
baum.insert(buch,code,0);
l.next();
}
TreeViewGUI view = new TreeViewGUI(baum);
}
This creates the object Buchstabe and sorts it in a List so that you have the shortest Strings at the beginning.
Then it inserts them into a Binaray Tree and displays it.

Categories

Resources