Help with java array nullpointerexception - java

I keep receiving a NullPointerException while trying to get a string from any array (that is encapsulated within a Vector). I cannot seem to stop the error from happening. It's got to be something simple, however I think that I have been looking at it for too long and I could sure use another set of eyes. Here is my code:
Vector<Event> details = vector.get(i).getEvent();
for (int x = 0; x < details.size(); x++) {
Event eDetails = details.get(x);
person = eDetails.getEventPerson();
place = eDetails.getEventPlace()[0];
time = eDetails.getEventTime()[0];
}
So when I try to get the item at position 0 in the array (when x is 0) that is returned from eDetails.getEventTime, a NullPointerException is thrown.
Now, when x is 0 I happen to know that the array element at position 0 of the getEventTime() array is an empty string, but it is NOT a null value. When x is 1 or 2, etc. I can retrieve the time just fine.
The problem is that I will still receive the NullPointerException when I try to do things like the following:
**System.out.println(eDetails.getEventTime.length);**
or
String result;
**if(eDetails.getEventTime[0] == null){**
result = "";
} else {
result = eDetails.getEventTime[0];
}
Any ideas?
Thanks!

Are you sure in your second example, it shouldn't be:
if(eDetails.getEventTime() == null)
Instead of:
if(eDetails.getEventTime[0] == null)
Are you making sure you leave the [0] off when you do the null check?
If the function eDetails.getEventTime() returns null, then you'll get a NullPointerException when you try to do eDetails.getEventTime()[0];

Seems that when you get details.get(0).getEventTime() the array returned is null.

The simplest way to figure this out is:
Vector<Event> details = vector.get(i).getEvent();
for (int x = 0; x < details.size(); x++) {
Event eDetails = details.get(x);
if (eDetails == null) {
throw new NullPointerException("eDetails on pos " + x + " is null");
}
person = eDetails.getEventPerson();
Something[] places = Details.getEventPlace();
if (places == null) {
throw ....
}
place = eDetails.getEventPlace()[0];
Something[] times = eDetails.getEventTime();
if (times == null) {
throw ....
}
time = eDetails.getEventTime()[0];
}
It may not look nice but at least it's informative.

Related

Copying i value from arraylist to array

So I am making a program that needs to be overwrite value i from ArrayList to value i in array. For the life of me I cannot figure out what I should do. I've tried looking for similar problems here, but can't seem to find them. Obviously, my loop is very wrong as it is, as it is just overwriting the entire loop, but I can't figure it out. Any kind-hearted person want to help me?
BTW, I am using Java with Processing
Dot[] dots = new Dot[16];
ArrayList<Dot> extraDots = new ArrayList<Dot>();
Fill them with values and later ...
for (int i = 0; i < dots.length; ++i) {
if (dots[i].timeRemain == 0 && !dotTouch)
{
//arrayCopy(extraDots, i, dots, i, 1);
//this is basically what I want, but from an arraylist to the array
dots = extraDots.toArray(new Dot[i]); //So, so wrong, I know
dotTouch = true;
}
dotTouch = false;
You mean
dots[i] = extraDots.get(i);
???
i didn't get your problem..
simply you can do like below to copy from arraylist to array
why you are using dots[i].timeRemain and dotTouch. can you clarify??
for (int i = 0; i < dots.length; ++i) {
dots[i] = extraDots.get(i);
}

Break statement doesn't work

This is a small part of my code. Here the break statement doesn't work. The if condition is executed but the break statement takes the control to the start of the while loop. "assign" and "clsAssign" are two array list. "clustersRefGlobal()" is a function and I don't want to pass "assign" when it is empty. However due to break not working it is called even when "assign" is empty. I am not sure why break statement doesn't stop the while loop
Wh:while (i < n) {
System.out.println("Start");
get = clustersRefGlobal(assign);
clsAssign.add(get.get(0));
assign = get.get(1);
if(assign.isEmpty()){
System.out.println("Inside");
break Wh;
}
System.out.println("End");
i++;
}
Here is the output
Start
End
Start
Inside
Start
Exception in thread "main" java.lang.NullPointerException
at softwareClustering.DominantSetClustering.clustersRefGlobal(DominantSetClustering.java:54)
at softwareClustering.DominantSetClustering.buildDominatSetClustering(DominantSetClustering.java:76)
at trees.PrototypeSelectionTree.clustersRefLocal(PrototypeSelectionTree.java:214)
at trees.PrototypeSelectionTree.clustersRefGlobal(PrototypeSelectionTree.java:180)
at trees.PrototypeSelectionTree.buildTree(PrototypeSelectionTree.java:59)
at trees.PrototypeSelectionTree.buildClassifier(PrototypeSelectionTree.java:235)
at weka.classifiers.Evaluation.crossValidateModel(Evaluation.java:617)
at trees.TestClassifier.main(TestClassifier.java:45)
Java Result: 1
The exception is because the "clustersRefLocal()" function is called with empty "assign" parameter. If any one knows whats the problem or what I am missing?
public double[] buildDominatSetClustering(int n) throws Exception {
int i = 1;
ArrayList<ArrayList<Integer>> clsAssign = new ArrayList<>();
ArrayList<Integer> assign = new ArrayList<>();
ArrayList<ArrayList<Integer>> get;
for (int j = 0; j < data.numInstances(); j++) {
assign.add(j);
}
Wh:
while (i < n) {
System.out.println("hello");
get = clustersRefGlobal(assign);
clsAssign.add(get.get(0));
assign = get.get(1);
if(assign.isEmpty()){
System.out.println("inside "+assign.size());
break Wh;
}
System.out.println(assign.size());
i++;
}
if(!assign.isEmpty())
clsAssign.add(assign);
double[] indexAssToClus = new double[data.numInstances()];
int count = 0;
for (ArrayList<Integer> a : clsAssign) {
for (int k = 0; k < a.size(); k++) {
indexAssToClus[a.get(k)] = count;
}
count++;
}
return indexAssToClus;
}
This is the function in which the code exist
The simple explanation to what you are seeing is that in fact the break is stopping the loop ... but the code around the snippet you have shown us is starting it again.
This will be apparent if you add a traceprint immediately before the labelled while statement.
The exception is because the "clustersRefLocal()" function is called with empty "assign" parameter.
I suspect that you are confusing "empty" with null. An empty string is a non-null String that has zero length. If you try to test if a null String is empty by calling String.isEmpty() you will get an NPE. The correct test for a non-null, non-empty String is this:
if (assign == null || assign.isEmpty()) {
// null or empty ... bail out
break;
}
I recommend you simply reverse the logic:
if(! assign.isEmpty()){
i++;
}
But failing that, check what is happening to your variable i:
Your check is for: while (i < n)
But the only place i is ever changed, it is incremented.
labeling your loops and using break label is discouraged. (its like the goto and causes spaghetti code.)
Besides, it's not making sense here, since you don't have nested loops. You can just change break Wh; to break;

Handling null objects in an array

I have an array with 18 objects in it, and the array is allocated to have 25 objects in it (the remaining 7 objects are null for future use). I’m writing a program that prints out all the non-null objects, but I’m running in to a NullPointerException and I can’t figure out how to get around it.
When I try this, the program crashes with Exception in thread "main" java.lang.NullPointerException:
for(int x = 0; x < inArray.length; x++)
{
if(inArray[x].getFirstName() != null)//Here we make sure a specific value is not null
{
writer.write(inArray[x].toString());
writer.newLine();
}
}
And when I try this, the program runs, but still prints the nulls:
for(int x = 0; x < inArray.length; x++)
{
if(inArray[x] != null)//Here we make sure the whole object is not null
{
writer.write(inArray[x].toString());
writer.newLine();
}
}
Can anyone point me in the right direction for handling null objects in an array? All help is appreciated!
your check should be:
if(inArray[x] != null && inArray[x].getFirstName() != null)

Checking Left/Right in an int array for Tetris, Android/Java

I'm trying to make a tetris game for android to help learn game programming for android. My goLeft/Rights break right when the button is pressed, the code for going left is in a class separate of the fields int array, and the list parts array. The fields array is accessed by a referenced variable (TetrisWorld tetrisworld;). While part list array is public so accessed through a variable(part) code for which is in the goLeft() code. It breaks at: if(tetrisworld.fields[x][part.y] != 0) Code for left:
public void goLeft() {
int x = 0;
for(int i = 0; i < 4; i++) {
TetrisParts part = parts.get(i);
x = part.x - 1;
if(tetrisworld.fields[x][part.y] != 0) {
noleft = true;
break;
}
}
if(noleft == false) {
for(int i = 0; i < 4; i++) {
TetrisParts part = parts.get(i);
part.x--;
}
}
}
The code for the fields int array:
int fields[][] = new int[WORLD_WIDTH][WORLD_HEIGHT];
WORLD_WIDTH and WORLD_HEIGHT are both static final ints, width being 9 and height being 19
I've tried putting if(tetrisworld.fields[0][0] == 0) and it still crashes so I don't think it has to do with the variables. Also It doesn't go out of bound even if I haven't added the code to check for that yet because I have the teroid spawning around x = 5 and since I can't go left/right once there's not a chance of that happening
I've tried moving the goLeft/Right methods to the gamescreen class which has a "world = TetrisWorld();" and it still bugs out at the same spot
UPDATE:
Ok just adding:
tetrisworld != null
to the first if statement fixed it, my question now is, why did it fix it? Why can't I move without this check? It clearly isn't null cause as far as I know; it's fully responsive now.
But an easier way to have solved this which is SOOOO easy is changing fields to static... then access it lika so: TetrisWorld.fields so my updated code is:
public void goLeft()
{
noleft = false;
for (int i = 0; i < 4; i++)
{
part = parts.get(i);
if (part.x - 1 < 0 || TetrisWorld.fields[part.x - 1][part.y] != 0)
{
noleft = true;
break;
}
}
if (noleft == false)
{
for (int i = 0; i < 4; i++)
{
part = parts.get(i);
part.x--;
}
}
}
Looks like you are hitting IndexOutOfBoundsException.
When you are doing x = part.x - 1;, your x variable can become lesser tan zero, thus your code will act like if(tetrisworld.fields[-1][part.y] != 0
It looks like you're getting a java.lang.NullPointerException when trying to access the array in tetrisworld. In the line you mention there are several ways that this could occur:
if(tetrisworld.fields[x][part.y] != 0) {
tetrisworld could be null.
The fields member of tetrisworld could be null.
The second array that you're looking up by using tetrisworld.fields[x].
The value of part could be null.
Having a quick look through your source code it looks to me like you never initialise tetrisworld, either at declaration using:
TetrisWorld tetrisworld = new TetrisWorld();
Or at some other point which is certain to have happened before your goLeft() method is called.
Ok I believe I found the answer, referencing: http://en.wikipedia.org/wiki/Null_Object_pattern
Apparently java will throw an NPE if you don't check for it first if you have a null reference? Is there any way to initialize it without doing a TetrisWorld tetrisworld = new TetrisWorld(); because it's already created in a different class so i get a thousand errors, an actual stack overflow! lul... Still not 100% positive. Please comment to verify and possibly suggest a better way to go about this.

Java Array index problem

cantmano is the index, it starts on 0. Another method increases with cant++.
I recheck that 0 <= cantmano <= 10
public void dibujar(){
//actualiza la pantalla
if (cantmano >= 0 && cantmano < 10 && cantcroupier >= 0 && cantcroupier < 10){
TextView textomano = (TextView)findViewById(R.id.textView3);
TextView textocroupier = (TextView)findViewById(R.id.textView5);
CharSequence buffer = textomano.getText();
textomano.setText( buffer + " " +
String.valueOf(manojugador[cantmano].getPalo())+ " de " +
String.valueOf(manojugador[cantmano].getNumero()) ); // <-- ERROR
textocroupier.setText( String.valueOf(cantmano) );
}
}
I get a nice
Caused by: java.lang.NullPointerException
at com.pruebas.blackjack.blackjack.dibujar(blackjack.java:58)
at com.pruebas.blackjack.blackjack.onCreate(blackjack.java:23)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2717)
EDITS:
.getNumero() returns the int with the value of a requested CARD. (playing card type)
.getPalo() returns an int where 1= diamonds, etc.
initialization of manojugador:
Carta manojugador[]= new Carta[10];
constructor of Carta:
public Carta(){
int palo=0;
int numero=0;
}
MIDNIGHT UPDATE:
With some improvements i managed it to get over the error. BUT now the array has all 0 values when written. This has to be an easy to solve but that's the final step before accepting the best answer.
Here's the method that adds cards:
public void hit(View v){
//sacan cartas
if (cantmano < manojugador.length){
manojugador[cantmano]=mazo.darcarta(); //adds a random Card to the manojugador. mazo means deck.
manocroupier[cantcroupier]=mazo.darcarta(); //adds a random Card to the manojugador. mazo means deck.
cantmano++;
cantcroupier++;
}
dibujar();
}
You must initialize the array and it's elements. If you simply have this:
Carta manojugador[]= new Carta[10];
then all 10 elements of the array will be null. You must also initialize each element. Something like this:
for(int i=0, length=manojugador.length; i<length; i++) {
manojugador[i] = new Carta();
}
Update:
I see that in your hit() method, I see you have:
if (cantmano <= 8) {
Shouldn't that be:
if (cantmano < 10) {
Or even better:
if (cantmano < manojugador.length) {
I think that what is happening in your code to cause the NullPointerException is that manojugador[9] can never be initialized.
Your manojugador array null elements and your cantmano is somehow pointing to one of those null elements.
For instance, let's say you have:
ManoJugador [] cantmano = new ManoJugador[10];
cantmano[0] = new ManoJugador();
cantmano[1] = new ManoJugador();
cantmano[2] = new ManoJugador();
You array beyond index 3 you have nulls. That's why when your try to get the numero of null you get NullPointerException.
EDIT
As per your edit:
Yeap, definitely, you have a null value there. Debug that part and you'll see some null values
hint: System.out.println( java.util.Arrays.toString( someArray ));
Suerte!

Categories