Java array[] with unknow size - what's wrong? - java

ImageItem imageItems[] = new ImageItem[data.length()];
for (int i=0; i<data.length(); i++) {
JSONObject object = data.getJSONObject(i);
Log.e("RESPONSE INFO::::", "id:" + object.get("id").toString());
imageItems[i].imageId = object.get("id").toString(); //NullPointerException
imageItems[i].imageURI = object.get("source").toString();
imageItems[i].thumbURI = object.get("picture").toString();
imageItems[i].createdTime = object.get("created_time").toString();
imageItems[i].link = object.get("link").toString();
}
Above is some kind of banal problem that can't resolve. Im still getting the NullPointerException at line with comment. At first I thought somethin's wrong with JSONobjects, but I'm sure that object.get("id").toString(); returns the right String. Something must be wrong with imageItems[] array.
ImageItem is a simple class with few String fields:
public class ImageItem {
public String imageId = null;
public String imageURI = null;
public String thumbURI = null;
public String createdTime = null;
public String link = null;
}
Any ideas what i'm missing here?
EDIT: I should mention that the ImageItem class is inner class of another class AlbumGallery. Now I'm getting error: No enclosing instance of type AlbumGallery is accessible. Must qualify the allocation with an enclosing instance of type AlbumGallery (e.g. x.new A() where x is an instance of AlbumGallery). with imageItems[i] = new ImageItem()

at the top of your for loop add imageItems[i] = gallery.new ImageItem()

Related

I can't add an element to the list. It returns null. How can I add it? [duplicate]

This question already has answers here:
Java List<string> not adding to list after Arrays.asList() has been used
(3 answers)
Closed 4 months ago.
My controller class:
#PostMapping(value = "/uniqueUrl")
#ResponseBody
public ResponseEntity<MyResponse> urlGenerator(#RequestBody MyRequest myRequest){
log.info("Request for url : ", myRequest);
MyResponse myResponse= this.generateUrlService.urlGenerator(myRequest);
log.info("generateUniqueUrl response: ", myResponse.getLongUniqueUrlList());
return ResponseEntity.accepted().body(myResponse);
}
MyRequest class:
#Data
public class MyRequestimplements Serializable {
#NotNull(message = "Url cannot be null or empty")
private String url;
#NotNull(message = "count cannot be null or empty")
private int cound;
}
My service implemantation :
#Override
public myResponse urlGenerator(MyRequest myRequest) {
log.info("urlGenerator started..");
myUrlRequestValidator.validate(myRequest);
String longUrl = myRequest.getUrl();
int count = myRequest.getCount();
List<String> uniqueUrlList = Arrays.asList(new String[count]);
for (String string : uniqueUrlList) {
string = longUrl + "/?";
for (int i = 0; i < rand.nextInt(11)+4; i++) {
string += letters.get(rand.nextInt(35));
}
uniqueUrlList.add(string);
log.info(string);
}
MyResponse response = new MyResponse();
response.setLongUniqueUrlList(uniqueUrlList);
return response;
}
MyResponse class:
#Data
public class MyResponse extends BaseResponse {
private List<String> longUniqueUrlList;
private List<String> shortUrlList;
}
In the method where my Controller and Service class is as follows, the result of uniqueUrlList returns null. I want to add each string formed by the add method to the list, but it does not add it. Can you help me where am I going wrong?
edit1 : When I change the random url generation and adding to the list in this way, it does not enter the for loop, or when I do not change the loop and only define it as an arraylist, it gives a Null error in the add method. How can I solve this? It's such an easy thing, but I don't understand why I can't do it?
List<String> uniqueUrlList = new ArrayList<String>();
String string = null;
for ( int j = 0; j < count; j++) {
string = longUrl + "/?";
for (int i = 0; i < rand.nextInt(11)+4; i++) {
string += letters.get(rand.nextInt(35));
}
uniqueUrlList.add(string);
log.info(string);
}
}
It is null because your List<String> uniqueUrlList is initialized with Arrays.asList which are fixed in size and unmodifiable, as specified in the Javadoc. The Arrays.asList(new String[count]) is also empty as there are no elements inside the new String[count].
Instead you should initialize it with a new ArrayList<String>():
List<String> uniqueUrlList = new ArrayList<String>();
Where you can then modify the list as you please, using a loop to add to your uniqueUrlList as many as myRequest.getCount() times.
You should initialize a list by
List<String> uniqueUrlList = new ArrayList<>();

Getting an Array from my ResultSet and adding it to an Object

I'm trying to use ResultSet.getArray() to grab an int[] array from my database. I'm using postgreSQL, DBeaver, and Java.
ResultSet rs = s.executeQuery(sql);
ArrayList<Theater> theaterList = new ArrayList<>();
while(rs.next()) {
Theater t = new Theater(
rs.getInt("theater_id"),
rs.getArray("theater_numbers"),
rs.getString("theater_loc")
);
theaterList.add(t);
return theaterList;
}
Error message: "The constructor Theater(int, Array, String) is undefined"
I keep getting flagged for not having a constructor of the appropriate type:
import java.sql.Array;
public Theater(int theater_id, Array theater_numbers, String theater_loc) {
super();
this.theater_id = theater_id;
this.theater_numbers = theater_numbers;
this.theater_loc = theater_loc;
Here's the beginning of the class:
public class Theater {
private int theater_id;
private Array theater_numbers;
private String theater_loc;
Not sure how to make the types agree with one another.
How do I make the types agree?

Use a string outside of if and else statement to set string value

I just have a simple enough question on an issue I'm having. I am trying to set a string value to "0" if a webelement isn't present else the string is the the webelement value (using getText). However I can't seem to use these values ouside the if and else statement. How do I do this?
Here is my code
String players_in_game = null;
public void join_game_user_increases_register() throws Exception {
WebDriverWait wait = new WebDriverWait(Drivers.getDriver(), 10);
wait.until(ExpectedConditions.visibilityOf(countdownLabel));
if (!num_of_players_in_game.isDisplayed()) {
String players_in_game = "0";
} else {
String players_in_game = num_of_players_in_game.getText();
}
System.out.println(players_in_game);
int first_num = Integer.parseInt(players_in_game);
Use code below:
WebDriverWait wait = new WebDriverWait(Drivers.getDriver(), 10);
wait.until(ExpectedConditions.visibilityOf(countdownLabel));
String players_in_game = "0";
if(num_of_players_in_game.isDisplayed()){
players_in_game = num_of_players_in_game.getText();
}
System.out.println(players_in_game);
int first_num = Integer.parseInt(players_in_game);
Or:
String players_in_game = num_of_players_in_game.isDisplayed() ? num_of_players_in_game.getText() : "0";
Or:
List<WebElements> num_of_players_in_game = driver.findElements(By....);
String players_in_game = num_of_players_in_game.size()==0 ? "0": num_of_players_in_game.get(0).getText();
Since your already declare that variable as a class member in the first line of your code, simple remove the String to not re-declare that name as a local variable but use the field instead:
if(!num_of_players_in_game.isDisplayed()){
players_in_game = "0";
} else {
players_in_game = num_of_players_in_game.getText();
}
Java allows variable shadowing at class level. So, you can actually declare a variable which has the same name as a class variable inside any method. In your case, the variable name is players_in_game.
You can define that variable once again in a method but scope of that new variable will be different. So, if you want to set that class level String inside a method, do not define a new variable and use the class level variable.
So just use the below code:
if (!num_of_players_in_game.isDisplayed()) {
players_in_game = "0";
} else {
players_in_game = num_of_players_in_game.getText();
}
Already others have answered with code. I just wanted to explain the reason.
You can try this :
String players_in_game = null;
public void join_game_user_increases_register() throws Exception {
WebDriverWait wait = new WebDriverWait(Drivers.getDriver(), 10);
wait.until(ExpectedConditions.visibilityOf(countdownLabel));
try {
if (num_of_players_in_game.isDisplayed()) {
String players_in_game = num_of_players_in_game.getText();
}
} catch (Exception e) {
String players_in_game = "0";
}
System.out.println(players_in_game);
int first_num = Integer.parseInt(players_in_game);

Java 8 shows this error. Local variable itemList defined in an enclosing scope must be final or effectively final

I am writing the code using java 8 but I iterate a List and then find RestaurantOrderBook using category type. and put that List into a Map. it shows this error:
Local variable itemList defined in an enclosing scope must be final or effectively final
Query query = new Query();
String categ = category;
query.addCriteria(Criteria.where("restaurantId").is(restaurantId));
List<RestaurantOrderBook> itemList = new ArrayList<RestaurantOrderBook>();
itemList = mongoTemplate.find(query, RestaurantOrderBook.class);
System.out.println("size : " + itemList.size());
Map<String , List<RestaurantOrderBook>> map = new HashMap<String , List<RestaurantOrderBook>>();
Arrays.asList("TakeAway", "Dining").forEach(e ->{
//Following line throws error:
List<RestaurantOrderBook> list = itemList.stream().filter(a -> !a.getOrderType().isEmpty() && a.getOrderType().equals(e)).collect(Collectors.toList());
map.put(e, list);
});
I have an another situation:
#Override
public EventReportRewardsPoints eventReportRewardsPoints(String organizerId) {
try{
List<Event> listOfEvents = eventRepo.findByOrganizerId(organizerId);
EventReportRewardsPoints eventTransReport = new EventReportRewardsPoints();
Integer soldTics = 0;
Double totalRevenue = 0d;
Integer soldToday = 0;
Integer findTotalAvailableTics = 0;
Integer findTotalQtytics = 0;
for (Event event : listOfEvents) {
List<EventTicket> eventTicket = eventTicketRepo.findByEventId(event.getId());
Integer sumOfAvailabletics = eventTicket.stream()
.mapToInt(EventTicket::getRemainingTickets).sum();
findTotalAvailableTics = findTotalAvailableTics + sumOfAvailabletics;
Integer sumOfQtytics = eventTicket.stream().mapToInt(EventTicket::getQty).sum();
findTotalQtytics = findTotalQtytics + sumOfQtytics;
List<EventTicketBook> listOfEventsTic = eventTicketBookRepository.findByEventId(event.getId());
for (EventTicketBook eventTicketBook : listOfEventsTic) {
Double sumOfSales = eventTicketBook.getTickets().stream().mapToDouble(EventTicket::getPrice).sum();
totalRevenue = totalRevenue + sumOfSales;
Date now = new Date();
System.out.println("create date : " + eventTicketBook.getCreateOn());
/*if(now.compareTo(eventTicketBook.getCreateOn()) == 0){
Integer sumOfSoldToday = eventTicketBook.getTickets().stream().mapToInt(EventTicket::getQty).sum();
soldToday = soldToday + sumOfSoldToday;
}*/
}
}
System.out.println("findTotalQtytics : " + findTotalQtytics);
System.out.println("findTotalAvailableTics : " + findTotalAvailableTics);
soldTics = findTotalQtytics - findTotalAvailableTics;
eventTransReport.setTotalRevenue(totalRevenue);
eventTransReport.setSoldToday(soldToday);
eventTransReport.setTicketsSold(soldTics);
return eventTransReport;
}catch(Exception e ){
e.printStackTrace();
}
return null;
}
How do i achive this using lamda expression.??
You are using itemList within a lambda expression. Therefore it has to be final.
Java 8 introduces the new concept of effectivly final, which means, the compiler checks, if a used variable is final in usage and does not force the developer to explicitly declare it as final.
So if you change your code to
final List<RestaurantOrderBook> itemList = new ArrayList<RestaurantOrderBook>();
you will see, that the compiler gives you an error at:
itemList = mongoTemplate.find(query, RestaurantOrderBook.class);
because you are reasigning itemList. That is why itemList is not effectivly final as well. If you squash these two lines to
List<RestaurantOrderBook> itemList = mongoTemplate.find(query, RestaurantOrderBook.class);
it should work.
Declare your variable itemList final:
final List<RestaurantOrderBook> itemList = mongoTemplate.find(query, RestaurantOrderBook.class);
As noted in the accepted answer by wumpz, the reason is that the variable being used has to be final or effectively final.
I would like to add the reason as to why it is so:
When we write a Lambda expression, we are effectively authoring an anonymous inner class. For Ex:
#FunctionalInterface
interface MyInterface{
public void print();
}
Used in our code as:
public static void main(String[] args) {
int i = 6;
new MyInterface() {
#Override
public void print() {
System.out.println(++i); // Remove ++ to resolve error
}
}.print();
}

How to get the current string from "Class.forName(name).newInstance()" using java

this is my code :
public static List populate(ResultSet rs, Class clazz) throws Exception {
ResultSetMetaData metaData = rs.getMetaData();
int colCount = metaData.getColumnCount();
List ret = new ArrayList();
Field[] fields = clazz.getDeclaredFields();
while (rs.next()) {
Object newInstance = clazz.newInstance();
for (int i = 1; i <= colCount; i++) {
try {
Object value = rs.getObject(i);
for (int j = 0; j < fields.length; j++) {
Field f = fields[j];
if (f.getName().replaceAll("_", "").equalsIgnoreCase(
metaData.getColumnName(i).replaceAll("_", ""))) {
BeanUtils.copyProperty(newInstance, f.getName(),
value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
ret.add(newInstance);
}
rs.close();
return ret;
}
and this is the method to call it :
public List getLastAddress(String terminal_id, String last_2) throws Exception {
String sql ="SELECT a.adress_reality from accounts_location_"+last_2+" AS a WHERE a.terminal_id = '"
+terminal_id+"' ORDER BY a.time_stamp DESC limit 1";
System.out.println(sql);
ResultSet rs = getDr().getSt().executeQuery(sql);
return populate(rs, Class.forName("hdt.ChineseAddressBean"));
and then :
List cn_address=sd.getLastAddress(toNomber,last_2);
System.out.println(cn_address.get(0));
but it show :
hdt.ChineseAddressBean#f0eed6
so How to get the current string from cn_address.get(0),
thanks
this is my ChineseAddressBean.java:
package hdt;
public class ChineseAddressBean {
String adress_reality = "";
public String getAdress_reality() {
return adress_reality;
}
public void setAdress_reality(String adress_reality) {
this.adress_reality = adress_reality;
}
}
updated1:
when i use this , it show error :
updated2:
this is the error :
Object address = cn_address.get(0);
ChineseAddressBean chineseaddressbean = (ChineseAddressBean)address;
System.out.println(chineseaddressbean.getAdress_reality());
The above lines is what you need to do to achieve what you want.Please let me know if its working.
Meybe you need to make method toString () in Your class instance.
Apparently you are getting a list of objects of class "ChineseAddressBean" in cn_address. Right?
Then if you do
List cn_address=sd.getLastAddress(toNomber,last_2);
System.out.println(cn_address.get(0));
It will take the first element in the list and print it. To print it, it will try to convert it to String by calling toString method of the object. So if you override toString method in class "ChineseAddressBean" and return whatever you want to print, it will do the trick
you dont have a toString() method in your bean.
public String toString() {
return adress_reality;
}
Missed in your example that you need to cast the objects retrieved from your list to the appropriate type.
So:
System.out.println((ChineseAddressBean)cn_address.get(0));
Returning List you access Object (not ChineseAddressBean). Also when you print it you call default toString() method which returns class name followed by hash code.
You have to return List<ChineseAddressBean> or cast the result to ChineseAddressBean (which you are doing wrong).
Try this one:
System.out.println(((ChineseAddressBean)(cn_address.get(0))).getAdress_reality());
You can also write toString() method for ChineseAddressBean which returns address string and then you dont have to call getAdress_reality().
cn_address.get(0) returns an object, you should convert it to a string

Categories

Resources