Stefan
Stefan

Reputation: 311

Read Variable from a Class

Hi after countless hours, I figured out what I really what my problem is but still cannot find an answer.

@Override
    public void onStampResult(StampResult result) {
    }

onStampResult returns a Class StampResult with the follwowing parameters:

public class StampResult implements Serializable {
  public SnowShoeError error;
  public SnowShoeStamp stamp;
  public boolean secure;
  public String receipt;
  public Date created;
}

SnowShoeStamp Class is:

public class SnowShoeStamp implements Serializable {
  public String serial;
}

And SnowShoeError Class is:

public class SnowShoeError implements Serializable {
  public int code;
  public String message;
}

In onStampResult I can write down logic depending on the output of result. On Success ´stamp´ gets initialized and ´error´ does not exist.

On Error, stamp does not exist and error gets initialized.

The result gets parsed to from JSON to the Class in the following way:

try {
     stampResult = gson.fromJson(result, StampResult.class);
      } catch (JsonSyntaxException jsonException) {
        stampResult = new StampResult();
        stampResult.error = new SnowShoeError();
        stampResult.error.message = result;
        }
    mOnStampListener.onStampResult(stampResult);
    mStampBeingChecked = false;
 }

How do I test if either error or stamp exists without getting a NullPointerExeption?

Upvotes: 0

Views: 44

Answers (1)

FD_
FD_

Reputation: 12919

Unless I misunderstood your question, you simply need to check for null.

In order to handle the different cases, you could do the following:

@Override
public void onStampResult(StampResult result) {
    if (result.error == null){
        SnowShoeStamp stamp = result.stamp;
        // Process stamp
    } else {
        SnowShoeError error = stampResult.error;
        // Process error
    }
}

Upvotes: 1

Related Questions