Question

Curious as to how to convert the payload in my NdefRecord from the string it goes into, into an integer that can be used in the rest of my application. The parseint and valueof methods cause my application to crash. Somehow managed to narrow the fault to one line of code:

int newtimer = Integer.valueOf(newtimermsg);

This line causes a crash on my application, Newtimermsg is the string thats extracted from the payload of the received NdefRecord as shown in the code below:

String newtimermsg = new String(msg.getRecords()[0].getPayload());

this works as i've checked the application by a settext used on the newtimermsg which shows perfectly the received message but i would like to know how to convert it into an integer. Sounds very basic and silly to not know how to do this but any help would be appreciated.

Was it helpful?

Solution

That depends on how you initially stored the integer value in the NDEF record's payload.

  1. Converting to/from textual representation of the integer

    Convert integer to record payload:

    int myInteger = ...;
    String payloadString = Integer.toString(myInteger);
    byte[] payload = payloadString.getBytes("US-ASCII");
    

    Convert record payload to integer:

    byte[] payload = ...;
    String payloadString = new String(payload, "US-ASCII");
    int myInteger = Integer.parseInt(payloadString);
    
  2. Direct conversion between integer and byte array (more efficient in terms of storage)

    Convert integer to record payload:

    int myInteger = ...;
    ByteBuffer buffer = ByteBuffer.allocate(4);
    buffer.putInt(myInteger);
    byte[] payload = buffer.array();
    

    Convert record payload to integer:

    byte[] payload = ...;
    ByteBuffer buffer = ByteBuffer.wrap(payload);
    int myInteger = buffer.getInt();
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top