updating an object in object array angularjs - java

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.

Related

Getting values from object in java

How I can get those values from this object? I was trying to getFields, getDeclaredFields etc. but everything is empty.
The problem is that Field[] myField = o.getClass().getDeclaredFields(); always return an empty array.
I am getting those values from database this way:
Query reqDisplayResponse = em.createNativeQuery("Select * FROM pxds_displayResponse");
List<Object> displayResponseList = reqDisplayResponse.getResultList();
And I want to print those values:
for(Object o: displayResponseList) {
for(Field field: o.getClass().getDeclaredFields()) {
log.info(field.getName());
}
}
Unfortunately log.info is unreachable.
Ok, here is solution. In fact object is an array, getDeclaredFields() return empty table, in documentation we can read:
If this Class object represents an array type, a primitive type, or void, then this method returns an array of length 0.
So in this situation it is useless. All we have to do is iterate over this object this way:
for(Object o: displayResponseList) {
for(int i = 0; i < 7; i++) {
System.out.println(((Object[])o)[i].toString());
}
System.out.println("...............");
}
Hope this will help someone in future.
You should use getDeclaredField, and then use get on it, passing the object as parameter.
Like this:
Field myField = object.getClass().getDeclaredField("_myField");
myField.setAccessible(true);
return (Integer) myField.get(object);
Try to display the object 'o' like an array:
for(int index = 0 ; index < 10 ; index++){
Log.info(String.valueOf(o[index]));
}
I think those fields you are trying to access are private
So in order to access private fields you have to:-
for (Field f : object.getClass().getDeclaredFields()) {
f.setAccessible(true);
Object o;
try {
o = f.get(object);
} catch (Exception e) {
o = e;
}
System.out.println(f.getGenericType() + " " + f.getName() + " = " + o);
}
This is an ID given by the Eclipse debugger, not by Java. You cannot access it.
There is System.identityHashCode(Object) to get the Object identity. (not the same ID)
If you want an ID like the one shown in the Eclipse debugger, you'd have to allocate them yourself.
Here is some general direction how you could do something like that:
Elegant way to assign object id in Java
Gwozdz, I think I understand your question. If I understood correctly, you are having problemas to access the value from a list of objects, in your image code example I'm seeing that you are using List. Try to use List<Object[]> and then use a foreach to access every value of your matrix.
List<Object[]> displayResponseList = reqDisplayReponse.getResultList();
foreach(.....){
foreach(.....){
[manipulate you object value here]
}
}
Just for your information: Matrix is a list of lists. In that case a list of array.

ArrayList in Session object seems to lose contents

I'm having a problem with retrieving and casting ArrayList from session. I get the following error:
javax.servlet.ServletException: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
I stored the arrayList in the session:
List<UserApplication> userList = uaDAO.searchUser(eds);
if (!userList.isEmpty()) {
request.getSession().setAttribute("userList", userList);
action_forward = EDITSUCCESS;
and for casting the session object to ArrayList, did the following:
EditStudentForm edt = (EditStudentForm)form;
if ((session.getAttribute("userList")) instanceof List){
List <UserApplication> studtList = (ArrayList<UserApplication>)session.getAttribute("userList");
}
try {
uaDAO.editUser(edt,studtList);
action_forward = EDITSUCCESS;
}
I'm getting the error over here in the DAO class:
public void editUser(EditStudentForm edt,List studtList) throws Exception {
PreparedStatement pst = null;
StringBuilder sb = new StringBuilder();
int stCode =Integer.parseInt(studtList.get(1).toString()); GETTING ERROR HERE
if (edt.getTitle() != null && !edt.getTitle().equals(studtList.get(2).toString())) {
sb.append("title = '").append(edt.getTitle()).append("'");
}
.
.
You are explicitly asking for 2nd (studtList.get(1)) and 3rd (studtList.get(2)) item in the list but never really make sure this list is big enough. Moreover your code apparently doesn't even compile:
if ((session.getAttribute("userList")) instanceof List){
List <UserApplication> studtList = ///...
}
try {
uaDAO.editUser(edt,studtList);
studtList is unaccessible in try block, also parenthesis in if statement are unmatched.
Check your studtList value.
From the error it seems your studtList only contain one item and you're try to get the second item with this code :
int stCode =Integer.parseInt(studtList.get(1).toString());
Change your code like this :
public void editUser(EditStudentForm edt,List studtList) throws Exception {
PreparedStatement pst = null;
StringBuilder sb = new StringBuilder();
if(studtList.size() > 1)
int stCode =Integer.parseInt(studtList.get(1).toString()); GETTING ERROR HERE
if (studtList.size() > 2 && edt.getTitle() != null && !edt.getTitle().equals(studtList.get(2).toString())) {
sb.append("title = '").append(edt.getTitle()).append("'");
}
}
In studtList there are no two elements and size of list maybe 1 or 0 elements, you should check it before try to call studtList.get(1). In ArrayList indexing start from 0 and if you want get first element you should call studtList.get(0).
In this code:
EditStudentForm edt = (EditStudentForm)form;
if ((session.getAttribute("userList")) instanceof List){
List <UserApplication> studtList = (ArrayList<UserApplication>)session.getAttribute("userList");
}
try {
uaDAO.editUser(edt,studtList);
action_forward = EDITSUCCESS;
}
You create a new variable 'studtList' that is never used. It's scope is only the { } pair around that one line.
There has to be another variable by that same name, studtList, in the outer scope so the 'editUser()' call can work.
Additional Note
As the other folks have answered, it looks like you may be doing a .get(1) and expecting the first element of the array list. Maybe. Maybe not.

Parsing JSON and deleting objects from it is giving error

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;
});

Passing Of Objects in scala

Hey guys i am trying to pass an Object(type Object) that is a combination of a (string+object).
In the function i need to compare the the string with a hash map and accordingly do operations with the attached object.
The code goes like this
Function (srt : Object)
{
//s is an array of Strings
var s = srt.toString.split("+")
if(s[0]== insert)
{
var ne = s[1].asInstanceOf(USERDEFINEDCLASS) //ERROR here
//do operations
}
}
main()
{
var og : className = new className(parameters)
Function(og ->("insert"))
}
In this code i am getting the error saying it cannot be converted from string to the class object.
I am not able to figure out a way of doing it. Can someone help me with this
I am not sure it will help you. Here follows a program with some features you described:
class Main{
class SomeClass(val x:String) { override def toString:String = x }
def funct(obj:Object) {
val s=obj.toString.split("+")
if(s(0) == "a" ) { // assumingn it's a non empty string
println(obj.asInstanceOf[SomeClass].x)
}
}
def main(args:Array[String]):Unit = {
funct(new SomeClass("a+b"))
}
}

How can I initialize an array with an enhanced for-loop?

I was optimizing an application and wanted to change my for loops to enhanced loops:
From:
for (int m = 1;m < MAX_BEREN;m++)
{
Wasberen[m] = new Wasbeer();
Wasberen[m].YYY = r.nextInt(SchermY - 28);
}
to:
for (Wasbeer a : Wasberen)
{
if (a!=null)
{
a = new Wasbeer();
a.YYY = r.nextInt(SchermY - 28);
}
}
I get a NullPointerException, because it probably doesnt know how much 'beren' can be in
the array, but I'm not sure how to manage the same as the loop above (MAX_BEREN = 11).
If the array reference ('Wasberen' in this case) in an enhanced for statement is null, then a NullPointerException will result when the statement is executed.
For initializing arrays, you should stick to the syntax you had before.
You can't use the enhanced for-loop in Java to fill an array. (I'm assuming your Wasberen array was already created before - if not, this will get you a NullPointerException in both variants.)
Your code (simplified)
for (Wasbeer a : Wasberen)
{
a = ...;
}
is equivalent to
for (int i = 0; i < Wasberen.length; i++)
{
Wasbeer a = Wasberen[i];
a = ...;
}
This assignment will change the local variable a, but will have no effect on the contents of the array.

Categories

Resources