Adding elements to an empty ArrayList<T> [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am adding objects to an ArrayList that is initialized as null inside a for each loop, but SonarLint is giving me a "NullPointerException" could be thrown when I try to add each object. Why is this error being pointed out?
public List<SatelliteData> getData()
{
SatelliteData satellite;
ArrayList<SatelliteData> satelliteList = null;
try(FileInputStream file = new FileInputStream(satelliteOutputFile))
{
TLEParser parsedFile = new TLEParser();
List<TLE> tleList = parsedFile.readFile(file);
for (TLE tle : tleList)
{
satellite = new SatelliteData(tle);
satellite.collectSatelliteData();
satelliteList.add(satellite); //A "NullPointerException" could be thrown; "satelliteList" is nullable here
}
}
catch (IOException ex)
{
LOGGER.error("IO Exception: " + ex);
notifyTheObservers("IO Exception: " + ex);
}
return satelliteList;
}

You shouldn't call member methods on variables that have been initialized to nothing/null.
In this case you have
ArrayList<SatelliteData> satelliteList = null;
This variable does not have any memory allocated to it.
At this point your computer knows : Okay there exists something
called satelliteData but it actually doesn't know where it is?
Calling add() method on it, is likely to throw a NullPointerException because this variable is a reference that is pointing to null/nothing.
To overcome this, You need to initialize the variable like this :
ArrayList<SatelliteData> satelliteList = new ArrayList<SatelliteData>();
At this point your computer created that satteliteData and knows
exactly where it exists hence it can happily operate upon it.
This will allocate some memory to this variable and now it has its own methods you can call.

Related

null pointer exception when I check if a blob exists [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 9 months ago.
I have a com.google.cloud.storage.Blob object. I have been able to download and upload just fine with this object in my java code, but I wanted to check if something exists before starting a process.In a nutshell here is the part of my code giving me issues.
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
public class Function implements BackgroundFunction<GcsEvent> {
public void accept(GcsEvent event, Context context) {
String bucketname = "my_bucket";
String blob_path = "path/to/my/object.jpg";
Storage storage = StorageOptions.newBuilder().setProjectId("my_project_id").build().getService();
Blob b = storage.get(BlobId.of(bucketname, blob_path));
// this is where the null pointer exception occurs
boolean exists = b.exists();
if (exists) {
//do something
}
}
}
Eclipse doesn't seem to catch it in the IDE. and the examples seem to follow this layout as well. Would anyone know what is going on?
I am running on a Linux environment machine. (it failed in cloud function as well).
I am using the Java 11 runtime.
I feel silly. I found out that storage.get(BlobId.of(bucketname, blob_path)); will return null if it can't find the object. instead of using b.exists(), one should check if it is null with if (b != null) { //do stuff }.

java.lang.UnsupportedOperationException when trying to delete from an #FXML TableView [duplicate]

This question already has answers here:
java.lang.UnsupportedOperationException for removing a row from the javafx tableview
(2 answers)
Closed 4 months ago.
I don't understand why this method wont work because it worked literally three days ago. Whenever I try to use the method(press the button), The database operations work fine but the program throws an error whenever I try to remove from the actual table view so that the user wont see that row anymore. I added a filtered list to the initialize method and i am concerned that might be the cause of the problem. Here is my code:
Initialize Method:
private void initialize()
{
ObservableList<BloomClient> clients = FXCollections.observableArrayList();
firstNames.setCellValueFactory(new PropertyValueFactory<>("FirstName"));
lastNames.setCellValueFactory(new PropertyValueFactory<>("LastName"));
phoneNumbers.setCellValueFactory(new PropertyValueFactory<>("PhoneNumber"));
birthdays.setCellValueFactory(new PropertyValueFactory<>("Birthday"));
startDates.setCellValueFactory(new PropertyValueFactory<>("StartDate"));
endDates.setCellValueFactory(new PropertyValueFactory<>("ExpireDate"));
try {
clients = dBconnect.getClientList();
} catch (Exception e) {
e.printStackTrace();
}
FilteredList<BloomClient> filteredList = new FilteredList<BloomClient>(clients,b -> true);
filteredSearch.textProperty().addListener(((observable, oldValue, newValue) ->
filteredList.setPredicate(person ->
{
if(newValue == null || newValue.isEmpty())
return true;//nothing in text field
String lowerCaseFilter = newValue.toLowerCase();
if (person.getFirstName().toLowerCase().contains(lowerCaseFilter))
return true;//check first name
else if (person.getLastName().toLowerCase().contains(lowerCaseFilter))
return true;//check last name
else
return false;
})
));
SortedList<BloomClient> sortedList = new SortedList<>(filteredList);
sortedList.comparatorProperty().bind(clientList.comparatorProperty());
clientList.setItems(sortedList);
}
public void freezeAccount() throws SQLException, ParseException {
BloomClient person = clientList.getSelectionModel().getSelectedItem();
dBconnect.sendToFreeze(person);//this works
dBconnect.deleteClient(person);//this works
clientList.getItems().remove(person);//java.lang.UnsupportedOperationException
clientList.refresh();
}
Well, it's just a guess. But it's possible that the clientList is a List<> type that was created using Collections.unmodifiableList(). When you try to modify one of those, an UnsupportedOperationException is thrown.
public static List unmodifiableList(List<? extends T> list)
Returns an unmodifiable view of the specified list. This method allows
modules to provide users with "read-only" access to internal lists.
Query operations on the returned list "read through" to the specified
list, and attempts to modify the returned list, whether direct or via
its iterator, result in an UnsupportedOperationException.
See: https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableList-java.util.List-
Figured it out in a way but would like a deeper explanation. I ended up instead of deleting from the clientList(TableView) I deleted directly from the clients(ObservableList) and made that variable global to be reached by other methods. I'm not sure of the reasoning behind the initial problem.
BloomClient person = clientList.getSelectionModel().getSelectedItem();
dBconnect.deleteClient(person);
clients.remove(person);
clientList.refresh();
}

What is the purpose of NoSuchMethodException instead of returning null [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
In Java, Foo.class.getMethod("bar") declares a checked exception of type NoSuchMethodException (among others).
What is the purpose of this exception? Isn't returning null sufficient to indicate that it was not found? What information or utility does throwing an exception add? Aside from forcing the user to explicitly be aware that it's possible for it to not be found, this seems superfluous. Returning null when something doesn't exist is a common pattern in Java, and this seems to be a prime candidate for that. So what was the reasoning behind this?
It appears that the designers of Java APIs made a distinction between situations when it's OK to ask for something that is missing and situations when you are supposed to ask only for things that exist.
They decided that asking for a missing key in a Map is OK, because the content of a map is something your program controls at runtime. Therefore, designers of the class library decided that it is unreasonable to ask programmers to check if a value is present before calling Map.get, and decided to return null instead.
The list of methods in a class, however, remains static at all times during a particular run, so it becomes reasonable to ask programmers to call getMethod only for methods that do exist. There are two consequences to this approach:
You can request multiple methods without checking each one - if you have a list of methods that must exist, for example, in a plugin component, you can get their Method reflection objects without checking the return value of individual getMethod calls, and
When you do not know if a method exists, call getMethods() - You can still examine all methods without knowing their names by getting a full list from the Class object.
Here is a code example to illustrate the first point. Current API lets you write this:
class Plugin {
private final Method init;
private final Method start;
private final Method stop;
public Plugin(Class cl) throws PluginException, SecurityException {
try {
init = cl.getMethod("init");
start = cl.getMethod("start");
stop = cl.getMethod("stop");
} catch (NoSuchMethodException ex) {
throw new PluginException("Plugin is missing a required method", ex);
}
}
...
}
instead of this:
class Plugin {
private final Method init;
private final Method start;
private final Method stop;
public Plugin(Class cl) throws PluginException, SecurityException {
init = cl.getMethod("init");
if (init == null) {
throw new PluginException("Plugin is missing init method");
}
start = cl.getMethod("start");
if (start == null) {
throw new PluginException("Plugin is missing start method");
}
stop = cl.getMethod("stop");
if (stop == null) {
throw new PluginException("Plugin is missing stop method");
}
}
...
}

Not sure why this Java Null Pointer Exception is happening [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a method that return an array of files in a given directory that is giving me a null pointer exception when executed. I can't figure out why.
private ArrayList<File> getFiles(String path) {
File f = new File(path);
ArrayList<File> files = new ArrayList<>(Arrays.asList(f.listFiles()));
return files;
}
thanks for your help
This NullPointerException is thrown when the path specified while initializing the file is incorrect (doesn't exist).
In such cases it is always advisable to add some null checks(protective code) in your method.
eg:
if( f != null) { //get the list of files }
may be casue by f.listFiles() return one null array.you can watch the variables in debug model

Null pointer exception with configuration

This is my code. It thinks that the config area section = null.
Heres the code:
public void loadArenas() {
fc1 = new File(plugin.getDataFolder(), "config.yaml");
if (!fc1.exists()) {
try {
fc1.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
fc = YamlConfiguration.loadConfiguration(fc1);
for (String keys : fc.getConfigurationSection("Arenas.").getKeys(false)) {
Oh and heres the error:
Error
fc1 is initialized, but fc is not.
You should print out the contents of fc1 at the top. It is very likely that you are running into path-related issues and so a new, EMPTY, configuration file is created.
That new file is then used as the input to fc, and naturally the "Arenas." section wouldn't exist. The NPE would either be thrown when you try to access the non-existent section's keys via getKeys().
Either way, if you are not sure what the problem is, you can either step through it with a debugger or just throw print statements everywhere to determine that things are what you expect.

Categories