Search code examples
javaandroidarraysrfduino

How to store received data in an array?


I am working on an Android application which receives data from an RFDuino and displays it on a Line Chart.

In my Mainactivity, the broadcastReceiver sends data into a method addData on receiving.

private final BroadcastReceiver rfduinoReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (RFduinoService.ACTION_CONNECTED.equals(action)) {
            upgradeState(STATE_CONNECTED);
        } else if (RFduinoService.ACTION_DISCONNECTED.equals(action)) {
            downgradeState(STATE_DISCONNECTED);
        } else if (RFduinoService.ACTION_DATA_AVAILABLE.equals(action)) {
            addData(intent.getByteArrayExtra(RFduinoService.EXTRA_DATA));
        }
    }
};

The addData method is as follows:

 public void addData(byte[] data) {

    View view = getLayoutInflater().inflate(android.R.layout.simple_list_item_2, dataLayout, false);

    TextView text1 = (TextView) view.findViewById(android.R.id.text1);

       String riz = HexAsciiHelper.bytesToHex(data);
       t1 = Integer.parseInt(riz, 16);
       String testString = String.valueOf(t1);
       text1.setText(testString);

        dataLayout.addView(view,LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
    }

Now, I want to store value of t1 into an array. The problem is that when I try to do it, a NullPointerException occurs and the program stops.

Any help would be appreciated.


Solution

  • Declare ArrayList<Integer> and Store the t1 value after doing null check.

    ArrayList <Integer> t1array = new ArrayList <Integer> ();
    String riz = HexAsciiHelper.bytesToHex(data);
    
    if (riz != null) {
        Integer t1 = t1 = Integer.parseInt(riz, 16);
        t1array.Add(t1);
    }