Android app NullPointerException where it should not happen? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have an Android app that is recently published, and I'm receiving crash reports from Google Play Console. One of the crashes is strange. It happens in code similar to the following:
private final List<Item> items = new ArrayList<>();
public void addItem(Item item) {
items.add(item); // NullPointerException here!!
}
Apparently items is null when addItem is called, but it seems to me that it's impossible—I've initialized it at the declaration site. I can't imagine a situation in which this could happen, yet it happens a lot. Any idea?

Alright, psychic debugging time. The only way this could happen is if something is calling it as part of the object init, either during setup of other variables or an explicit init { ... } block.
You are almost certainly doing something like this elsewhere in the code:
import java.util.*;
class Main {
private static class Item { }
private final Item firstItem = setUpItemsAndReturnFirst();
private final List<Item> items = new ArrayList<>();
public void addItem(Item item) {
items.add(item); // NullPointerException here!!
}
private Item setUpItemsAndReturnFirst() {
Item first = new Item();
Item second = new Item();
addItem(first);
addItem(second);
return first;
}
public static void main(String args[]) {
new Main();
}
}
This contains your sample code, and will crash on that line with a NullPointerException, because setUpItemsAndReturnFirst() is being called before items is initialized when it's used to initialize firstItem.
I assume it's behind some sort of conditional, in your case, since it presumably doesn't crash every time or you'd never have released it. But this is the general idea.

Related

How to check if an enum value changed? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm new to Java and development and don't know how to do most of the stuff. So I wanter to ask you guys how to check if an enum value changed. So I have this:
public enum GameState {
WAITING,
INTRO,
INTRO_WAIT,
INTRO_1,
INTRO_1_WAIT,
LOBBY_INTRO,
LOBBY,
INTRO_GAME1,
GAME1,
INTRO_GAME2,
GAME2;
}
So I want to know how to detect if an enum value changed from any of those to any of those. Hope you know what I'm try to say.
Thanks :)
I assume you mean that some other class has a field GameState state, and you want to know when it changes from one value to another.
There's not an "automatic" way to do that. Have that other class make that field be private (which is a good idea anyway), and any time it changes it (for instance, via a setState(GameState) method, it can perform whatever action you want — such as calling any GameStateListener that's been registered with that class, or whatever checking mechanism you want.
It might look something like this:
public interface GameStateListener {
void onChange(GameState changingFrom, GameState changingTo);
}
public class Game {
private GameState state = WAITING; // or whatever initial value
private final Collection<GameStateListener> listeners = new ArrayList<>();
public void registerListener(GameStateListener listener) {
listeners.add(listener);
}
public void changeState(GameState newState) {
for (GameStateListener listener : listeners) {
listener.onChange(state, newState);
}
this.state = newState;
}
...
}
Note that that code is not thread-safe, and making it be thread-safe would add a good deal of complexity. There are other ways to do it, too, but the above is a pretty standard pattern.

Execute code in seperate class when boolean changes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So, I'm creating a snakes and ladders game in javafx, that asks a question when the player lands on a ladder or snake, and decides whether to go up the ladder/down the snake or not based on whether the answer is correct or not.
I have a Question class that creates a new window and displays the question, as well as a place to answer it, and a 'correct' boolean value that I am hoping to essentially, return to the main class, when the button is clicked.
Since EventHandlers cannot directly return values, I am hoping to say 'if the value of this 'correct' variable has changed, execute a getter method to get and store the value' but I don't know how to create a listener to check if the value has changed.
Any help would be appreciated!
I would do something like this:
public class Question {
public enum State {UNANSWERED, CORRECT, INCORRECT}
private final ReadOnlyObjectWrapper<State> state
= new ReadOnlyObjectWrapper<>(State.UNANSWERED);
public ReadOnlyObjectProperty<State> stateProperty() {
return state.getReadOnlyProperty() ;
}
public final State getState() {
return stateProperty().get();
}
private Button button ;
public Question() {
// ...
button = new Button(...);
button.setOnAction( event -> {
if (checkAnswer()) {
state.set(State.CORRECT);
} else {
state.set(State.INCORRECT);
}
});
// etc..
}
public void showWindow() {
// display window with question and controls, etc...
}
}
Then you can do
Question question = new Question();
question.stateProperty().addListener((obs, oldState, newState) -> {
if (state == Question.State.CORRECT) { /* ...*/}
else if (state == Question.State.INCORRECT) { /* ... */}
});
question.showWindow();
I don't know what type of listener you want but I found this for javafx changelistener at http://docs.oracle.com/javafx/2/binding/jfxpub-binding.htm. This might help you get started
package propertydemo;
import javafx.beans.value.ObservableValue;
import javafx.beans.value.ChangeListener;
public class Main {
public static void main(String[] args) {
Bill electricBill = new Bill();
electricBill.amountDueProperty().addListener(new ChangeListener(){
#Override public void changed(ObservableValue o,Object oldVal,
Object newVal){
System.out.println("Electric bill has changed!");
}
});
electricBill.setAmountDue(100.00);
}
}
There is a great API built for Dialogs. It's going to become part of the official JavaFX API, but for now you can use the separate library:
Dialogs
Confirmation Dialog is probably the one you're looking for.

Android: Custom Parcelable Class Crashes App Without Throwing Exception

I've got an Android app with custom objects which implement the Parcelable interface. They way I have it set it up is that my program initially creates an ArrayList of a custom class Products from a file in the bundle. I can see and confirm that the arraylist and it's instance variabels are populated appropriately. This class has several instance variables along with one being another ArrayList but with the String class. Remember that fact.
I am trying to pass the ArrayList<Product> into a new activity like so:
try {
Intent i = new Intent(RootActivity.this, ProductsActivity.class); //Intent from this activity to the next
i.putParcelableArrayListExtra("Products", app_products); //Puts my ArrayList<Class A> as an extra
startActivity(i); //Launch the activity
}
catch(Exception e){
Log.d("Activity Error", "Error Here:" + e.getMessage());
}
I am collecting the information back from the intent in my new activity by pulling the ArrayList out by using
app_products = getIntent().getParcelableArrayListExtra("Products");
For my custom class, it looks something like this, along with the implemented Parcelable methods.
public class Product implements Parcelable{
private String name;
private String cost;
private ArrayList<String> similarItems;
public Product{
name = null;
cost = null;
similarItems = new ArrayList<String>();
}
public Product(String name, String cost){
this();
this.name = name;
this.cost = cost;
}
public addSimilarItem(String item){
similarItems.add(item);
}
public static final Parcelable.Creator<Product> CREATOR
= new Parcelable.Creator<Product>()
{
public Product createFromParcel(Parcel in) {
return new Product(in);
}
public Product[] newArray(int size) {
return new Product[size];
}
};
public int describeContents(){
return 0;
}
private Product(Parcel in){
name = in.readString();
cost = in.readString();
similarItems = in.readArrayList(String.class.getClassLoader());
}
public void writeToParcel(Parcel out, int flags){
out.writeString(name);
out.writeString(cost);
out.writeList(similarItems);
}
}
So this works well WITHOUT my String arraylist being added in the class
Comment out out.writeList(similarItems); and also similarItems = in.readArrayList(String.class.getClassLoader());
but once you add them back in into the class, the app crashes but it doesn't even throw a message for debugging. I've wrapped everything around try-catch statements and android doesn't even report the app crashed with the normal dialog on the springboard. I am truly at a loss.
It is worth mentioning that I've used some log statements to understand where the program is crashing despite the fact that android wont throw an exception. I can see that all of the items in my ArrayList undergoes the writeToParcelMethod and completes writing. The Product(Parcel in) method is never called. Lastly, I can also see the class I am launching the new activity from enters the Pause State and my new Activity is never created.
Let me know if I can provide any additional information.
Fairly certain your problem is the use of writeList(). writeList() seems to indicate that it follows the same contract as writeValue() for the items contained in the list. readList() however, seems to indicate that the values must be Parcelable (which String is not).
Either way, typically these calls have to be very specifically linked to their inverse (e.g. writeString() must be read in with readString(), not readValue()) so you should instead use the provided methods for reading/writing String Lists:
// Takes in a List<String> which may be null
out.writeStringList(similarItems);
// Returns either null or a new ArrayList<String> with the contents
similarItems = in.createStringArrayList();
These seemed to be due to some malformed XML which my app uses as a resource. Not sure why this was this issue but after many hours of hunting it down, I was able to remove the bad XML and will revisit this issue at a later date towards when I need to release the app.
Right now, I'm just gonna worry about continuing to develop it. I'll try to remember to check back here if I find anything interesting about my XML.

Java singleton - null static variable (can't explain) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
Can someone please explain how is possible, that method obtain(..) throws IllegalStateException for input ConfiguratorType.SKODA (the variable configurators contains {SKODA=null})? How can it be null, I do not understand why SkodaConfigurator.INSTANCE returns null. It should never be null or am i mistaken? The code is executed in servlet environment, Java 7.
Thank you
public class CarConfigurators {
private static Map<ConfiguratorType, CarConfigurator> configurators
= new EnumMap<ConfiguratorType, CarConfigurator>(ConfiguratorType.class);
static {
configurators.put(ConfiguratorType.SKODA, SkodaConfigurator.INSTANCE);
// ..
}
public static CarConfigurator obtain(ConfiguratorType type) {
CarConfigurator configurator = configurators.get(type);
if (configurator == null)
throw new IllegalStateException("Car configurator of type " + type + " is not registered.");
return configurator;
}
...
}
public class SkodaConfigurator extends CarConfigurator {
public static final SkodaConfigurator INSTANCE = new SkodaConfigurator();
...
}
public enum ConfiguratorType {
SKODA,
// ..
}
Static code cannot all run simultaneously, the various bits of static initialization going on have to happen in a given order. Clearly in this case, your static block which does configurations.put(...) is running before the static variable in SkodaConfiguration is initialized.
This is related to static initialization order.
I found this from another answer
public class Main {
{
System.out.printf("NON-STATIC BLOCK\n");
}
static{
System.out.printf("STATIC BLOCK\n");
}
public static Main m = new Main();
public Main(){
System.out.printf("MAIN CONSTRUCTOR\n");
}
public static void main(String... args) {
//Main m = new Main();
System.out.printf("MAIN METHOD\n");
}
}
Output :
STATIC BLOCK
NON-STATIC BLOCK
MAIN CONSTRUCTOR
MAIN METHOD
Please go through this : Java Static Initialization Order

Control doesn't comeback to Swinkworker when I call another class from it

I have a class that extends SwingWorker
public class PowerVCImageDeployer extends SwingWorker<Boolean,String>{
protected Boolean doInBackground() throws Exception {
PowerVCImageDeployer imageDeployer = new PowerVCImageDeployer();
imageDeployer.makeAConnection();
imageDeployer.makeNameIdMap();
// more code
return null;
}
public HashMap<String,String> makeNameIdMap(){
System.out.println("I am in make NameIdMap");
VolumeNameGetter idToName = new VolumeNameGetter();
ArrayList<String> list = (ArrayList<String>)volIDMap.keySet();
idNameMap = idToName.volNameGetter(list);
This is the trouble point. The control goes class idToName and it looks as if it doesn't come back. I have fully tested the class VolumeNameGetter using main method. The class is working good. There is no problem with it. So that looks as if once the control goes away from the SwingWorker it is unable to get it back ?? I have posted the output in the last line
System.out.println("The name Id Map is "+idNameMap);
System.out.println("Checking if the control comes back here");
return idNameMap;
}
}
The output of the code is
I am in make NameIdMap
This is troubling me a lot. Any help would be highly appreciated. Thanx in advance.
Debugger Output
and line number 127 is
return voulmeMap;

Categories