Home > Software engineering >  Null Pointer Exceptions on a non null List Float Object by calling get method
Null Pointer Exceptions on a non null List Float Object by calling get method

Time:10-13

I am using Java programming to approach Android Studio (Android API 32). The scenario is that some data received from an external device through WiFi are repeatedly stored in an array which will be converted in a Float List Object pitch_2, and at some point, this list will be averaged in next function.

This function is called in this loop:

private class Thread2 implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    byte[] buffX_2 = new byte[BUFFER_LENGTH*2-8];
                    if (btn_client_2.isEnabled()) {
                        int k_2 = inputStream_2.read(buffX_2);
                        byte[] c_2 = new byte[buffX_2.length   client2.length];
                        System.arraycopy(buffX_2, 0, c_2, 0, buffX_2.length);
                        System.arraycopy(client2, 0, c_2, buffX_2.length, client2.length);
                        fou.write(c_2);
                        float pitch_2 = from_bytes_to_float(buffX_2,18);
                        pitch_buff_2.add(pitch_2);
                        int [] data_2 = unpack(buffX_2);                       
                 
                    if (message != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (x%plot_freq==0) {
                                    float value_2 = average_list(pitch_buff_2, plot_freq);
                                    if (y>=4000) {
                                        series_2.resetData(new DataPoint[] {new DataPoint(x, value_2)});
                                        y = 0;
                                    } else {
                                        series_2.appendData(new DataPoint(x, value_2),true,500);
                                    }
                                    pitch_buff_2.clear();
                                    Log.v("Plot Update","OK");
                                }
                                x  = 1;
                                y  = 1;
                                Log.v("Plot Update",String.valueOf(x));
                            }
                        });
                    } else {
                        Thread1 = new Thread(new MainActivity.Thread1());
                        Thread1.start();
                        return;
                    }
                    Thread.sleep(1);
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

Here my function which is called average_list simply intends to take as input a List Object and do the average:

        if (list == null) {
            return 100/n_elements;
        } else {
            float value = 0;
            for(int j = 0; j < list.size(); j  ) {
                value = value   list.get(j);
            }
            return value/n_elements;
        }
    } 

In a totally randomic way, this function might generate the following error:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication.smart_crutches_app, PID: 25434
    java.lang.NullPointerException: Attempt to invoke virtual method 'float java.lang.Float.floatValue()' on a null object reference
        at com.example.myapplication.smart_crutches_app.MainActivity.average_list

I have put a not-null control (following this suggestion What is a NullPointerException, and how do I fix it?) in the average_list function in order to avoid this error but still happens. As far as I understand I call get method in a null object, but how is it possible if I have put an if statement? I am hundred per cent sure I am forgetting something, but I cannot figure out what yet.

What do you think? Your help would be really appreciated. Thanks.

CodePudding user response:

You're calling .floatValue() on an expression whose type is Float (SOURCE: Just read the error message you get!), but the expression resolves to null. Your if(list == null) check checks if the list is null which is therefore irrelevant to this problem: It's not about list being null. It's about some expression of type Float being null.

You don't appear to have any Float values anywhere; however, that's not quite true: Your list is filled with Float objects, and you are auto-unboxing it on your value = value list.get(j) line. Java only supports numeric math on primitives (float - primitives are the direct value and cannot be null - null is a reference, as in, this variable can point at an object, but currently it points at nothing).

And lists can only contain objects.

So, seemingly, value = value list.get(j) is impossible: list.get(j) returns objects (Floats to be specific, which aren't the same as floats), and objects don't do math.

However, what's happening here is auto-unboxing: Anytime the code doesn't make sense, but it would make sense if you 'unbox' the primitive wrapper type (Float is the wrapper type for float), then java assumes you meant to invoke .floatValue() on your Float object.

So java just inserts that for you. And like all instance method invocations, if the receiver (the thing to the left of the dot) is null, you get a NullPointerException - and that's where its coming from. list.get(j) is returning null and that causes an NPE.

So, the real question is, how did nulls end up in your list?

There's no way to answer that question; you did not include the relevant code. In general, when asking SO questions, try to paste a complete snippet that anybody can just paste into a terminal and run.

CodePudding user response:

Here the entire code @rzwitserloot

//Some import

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.os.VibrationEffect;
import android.os.Vibrator;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;


@SuppressLint("SetTextI18n")
public class MainActivity extends AppCompatActivity {
    ServerSocket serverSocket;
    ServerSocket serverSocket_2;
    ServerSocket serverSocket_3;
    Thread Thread1 = null;
    Thread Thread11 = null;
    Thread Thread111 = null;
    TextView tvMessages;
    Button btnStart, btnEnd, btnConnect;
    GraphView graph;
    GraphView graph2;
    LineGraphSeries<DataPoint> series;
    LineGraphSeries<DataPoint> series_2;
    LineGraphSeries<DataPoint> series_3;
    LineGraphSeries<DataPoint> lc;
    LineGraphSeries<DataPoint> lc2;
    LineGraphSeries<DataPoint> lc3;
    String message,current_time;
    public static String SERVER_IP = "";
    public static final int SERVER_PORT = 8080;
    public static final int SERVER_PORT_2 = 50000;
    public static final int SERVER_PORT_3 = 40000;
    public static final int BUFFER_LENGTH = 20;
    int x, y, client_connected;
    int plot_freq;
    private PrintWriter output;
    private PrintWriter output_2;
    private PrintWriter output_3;
    private  DataInputStream inputStream;
    private  DataInputStream inputStream_2;
    private  DataInputStream inputStream_3;
    FileOutputStream fou;
    OutputStreamWriter saveStream;
    RadioButton btn_client_1,btn_client_2,btn_client_3;
    byte [] client1 = {0,0};
    byte [] client2 = {1,1};
    byte [] client3 = {2,2};
    Socket socket_3;
    Socket socket_2;
    Socket socket;
    List<Float> pitch_buff_1 = new ArrayList<>();
    List<Float> pitch_buff_2 = new ArrayList<>();
    List<Float> pitch_buff_3 = new ArrayList<>();
    List<Integer> lc_buff_1 = new ArrayList<>();
    List<Integer> lc_buff_2 = new ArrayList<>();
    List<Integer> lc_buff_3 = new ArrayList<>();
    Map<Integer, String> data;
    Map<Integer, Integer> sounds;
    public int ID_audio;
    public int flag_Acq = 1;
    public int flag_Acq_1 = 1;
    public int flag_Acq_2 = 1;
    public int flag_Acq_3 = 1;
    ColorStateList colorStateList = new ColorStateList(
            new int[][]
                    {
                            new int[]{-android.R.attr.state_enabled}, // Disabled
                            new int[]{android.R.attr.state_enabled}   // Enabled
                    },
            new int[]
                    {
                            Color.GRAY, // disabled
                            Color.GREEN   // enabled
                    }
    );
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvMessages = findViewById(R.id.tvMessages);
        tvMessages.setMovementMethod(new ScrollingMovementMethod());
        btnStart = findViewById(R.id.btnStart);
        btnEnd = findViewById(R.id.btnEnd);
        btnConnect = findViewById(R.id.btnConnect);
        Spinner mySpinner_ID = findViewById(R.id.spinner);
        graph = findViewById(R.id.graph);
        graph2 = findViewById(R.id.graph2);
        series = new LineGraphSeries<>();
        series_2 = new LineGraphSeries<>();
        series_3 = new LineGraphSeries<>();
        lc = new LineGraphSeries<>();
        lc2 = new LineGraphSeries<>();
        lc3 = new LineGraphSeries<>();
        series_2.setColor(Color.RED);
        series_3.setColor(Color.DKGRAY);
        lc2.setColor(Color.RED);
        lc3.setColor((Color.DKGRAY));
        graph.addSeries((series));
        graph.addSeries(series_2);
        graph.addSeries(series_3);
        graph.getViewport().setScalable(true);  // activate horizontal zooming and scrolling
        graph.getViewport().setScrollable(true);  // activate horizontal scrolling
        graph.getViewport().setMinY(-201);
        graph.getViewport().setMaxY(201);
        graph.getViewport().setMaxX(2001);
        graph.getViewport().setMinX(0);
        graph.getViewport().setYAxisBoundsManual(true);
        graph.setTitle("Pitch [°]");

        graph2.addSeries((lc));
        graph2.addSeries(lc2);
        graph2.addSeries(lc3);
        graph2.getViewport().setScalable(true);  // activate horizontal zooming and scrolling
        graph2.getViewport().setScrollable(true);  // activate horizontal scrolling
        graph2.getViewport().setMinY(400);
        graph2.getViewport().setMaxY(2000);
        graph2.getViewport().setMaxX(2001);
        graph2.getViewport().setMinX(0);
        graph2.getViewport().setYAxisBoundsManual(true);
        graph2.setTitle("Applied Weight [N]");



        SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy_HHmmss", Locale.getDefault());
        current_time = sdf.format(new Date());
        File folder = getExternalFilesDir("Data_Server_ClientS");
        File output = new File(folder,current_time ".txt");
        btn_client_1 = findViewById(R.id.btn_client_1);
        btn_client_2 = findViewById(R.id.btn_client_2);
        btn_client_3 = findViewById(R.id.btn_trunk);
        btn_client_1.setButtonTintList(colorStateList); // set the color tint list
        btn_client_1.invalidate(); // Could not be necessary
        btn_client_2.setButtonTintList(colorStateList); // set the color tint list
        btn_client_2.invalidate(); // Could not be necessary
        btn_client_3.setButtonTintList(colorStateList); // set the color tint list
        btn_client_3.invalidate(); // Could not be necessary
        btn_client_1.setEnabled(false);
        btn_client_2.setEnabled(false);
        btn_client_3.setEnabled(false);

        data = new HashMap<>();
        data.put(1, "Vibration");
        data.put(2, "Audio");
        data.put(3, "Both");
        sounds = new HashMap<>();
        sounds.put(1, R.raw.crutch_left);
        sounds.put(2, R.raw.crutch_right);
        sounds.put(3, R.raw.trunk_down);
        sounds.put(4, R.raw.trunk_up);
        sounds.put(5,R.raw.sampling_sx);
        sounds.put(6,R.raw.sampling_dx);
        sounds.put(7,R.raw.sampling_trunk);
        sounds.put(8,R.raw.start);
        sounds.put(9,R.raw.end);

        tvMessages.setText("Not yet connected crutches\n");
        btnConnect.setOnClickListener(v -> {
            try {
                fou = new FileOutputStream(output);
                saveStream = new OutputStreamWriter(fou);
                Toast.makeText(MainActivity.this, "Done"   folder.getAbsolutePath(), Toast.LENGTH_SHORT).show();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            try {
                SERVER_IP = getLocalIpAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            Thread1 = new Thread(new Thread1());
            Thread1.start();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Thread11 = new Thread(new Thread11());
            Thread11.start();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Thread111 = new Thread(new Thread111());
            Thread111.start();
        });
        try {
            fou = new FileOutputStream(output);
            saveStream = new OutputStreamWriter(fou);
            Toast.makeText(this, "Done"   folder.getAbsolutePath(), Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            SERVER_IP = getLocalIpAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        Thread1 = new Thread(new MainActivity.Thread1());
        Thread1.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Thread11 = new Thread(new MainActivity.Thread11());
        Thread11.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Thread111 = new Thread(new MainActivity.Thread111());
        Thread111.start();
        /*
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                message = etMessage.getText().toString().trim();
                if (!message.isEmpty()) {
                    new Thread(new MainActivity.Thread3(message)).start();
                }
            }
        });
        */
        btnStart.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View v) {
                message = "S";
                new Thread(new MainActivity.Thread3(message)).start();
                plot_freq= 10;
                ID_audio = Integer.parseInt(mySpinner_ID.getSelectedItem().toString());
                if (btn_client_1.isEnabled()) {
                    pitch_buff_1.clear();
                    lc_buff_1.clear();
                }
                if (btn_client_2.isEnabled()) {
                    pitch_buff_2.clear();
                    lc_buff_2.clear();
                }
                if (btn_client_3.isEnabled()) {
                    pitch_buff_3.clear();
                    lc_buff_3.clear();
                }
                new Thread(new MainActivity.Thread2()).start();
                new Thread(new MainActivity.Thread_BioFeedback(8,2)).start();
            }
        });
        btnEnd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                message = "E";
                new Thread(new MainActivity.Thread3(message)).start();
                try {
                    new Thread(new MainActivity.Thread_BioFeedback(9,2)).start();
                    saveStream.close();
                    Thread.sleep(2000);
                    finishAndRemoveTask();
                    if (btn_client_1.isEnabled()) {
                        serverSocket.close();
                        socket.close();
                    }
                    if (btn_client_2.isEnabled()) {
                        serverSocket_2.close();
                        socket_2.close();
                    }
                    if (btn_client_3.isEnabled()) {
                        serverSocket_3.close();
                        socket_3.close();
                    }
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void Vibrate(int time) {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            vibrator.vibrate(VibrationEffect.createOneShot(time,VibrationEffect.DEFAULT_AMPLITUDE));
        } else {
            //deprecated in API 26
            vibrator.vibrate(time);
        }
        // vibrator.vibrate(VibrationEffect.createOneShot(time,VibrationEffect.DEFAULT_AMPLITUDE));
    }

    public void Sound(int action) {
        int so_sound = sounds.get(action);
        final MediaPlayer audio = MediaPlayer.create(this,so_sound);
        audio.start();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void run_feedback(int sound_ID, int time_vibration, int ID){
        switch (ID){
            case 1:
                Vibrate(time_vibration);
                break;
            case 2:
                Sound(sound_ID);
                break;
            case 3:
                Vibrate(time_vibration);
                Sound(sound_ID);
                break;
            default:
                Vibrate(time_vibration);
                Sound(sound_ID);
                break;
        }
    }

    private String getLocalIpAddress() throws UnknownHostException {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        assert wifiManager != null;
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipInt = wifiInfo.getIpAddress();
        return InetAddress.getByAddress(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(ipInt).array()).getHostAddress();
    }

    public static int[] unpack(final byte[] byte_array) {
        final int[] integerReadings = new int[byte_array.length / 2];
        for(int counter = 0, integerCounter = 0; counter < byte_array.length;) {
            integerReadings[integerCounter] = convertTwoBytesToInteger(byte_array[counter], byte_array[counter   1]);
            counter  = 2;
            integerCounter  ;
        }
        return integerReadings;
    }

    private static int convertTwoBytesToInteger(final byte byte1, final byte byte2) {
        final int unsignedInteger1 = getUnsignedInteger(byte2);
        final int unsignedInteger2 = getUnsignedInteger(byte1);
        int unsignedInteger = unsignedInteger1 * 256   unsignedInteger2;
        if ((unsignedInteger)>32768) {
            unsignedInteger = unsignedInteger - 65536;
        }
        return unsignedInteger;
    }

    private static int getUnsignedInteger(final byte b) {
        int unsignedInteger = b;
        if(b < 0) {
            unsignedInteger = b   256;
        }
        return unsignedInteger;
    }

    public static float from_bytes_to_float (byte [] array, int index)  {
        byte [] bytes = new byte [4];
        for(int j = 0; j < bytes.length; j  ) {
            bytes[j] = array[index j];
        }
        int asInt = (bytes[0] & 0xFF)
                | ((bytes[1] & 0xFF) << 8)
                | ((bytes[2] & 0xFF) << 16)
                | ((bytes[3] & 0xFF) << 24);

        return Float.intBitsToFloat(asInt);
    }

    public static float average_list (List<Float> list, int n_elements) {
        if (list == null) {
            return 100/n_elements;
        } else {
            float value = 0;
            for(int j = 0; j < list.size(); j  ) {
                value = value   list.get(j);
            }
            return value/n_elements;
        }
    }

    public static float average_listInt (List<Integer> list, int n_elements) {
        if (list == null) {
            return 100/n_elements;
        }
        else {
            float value = 0;
            for(int j = 0; j < list.size(); j  ) {
                value  = list.get(j);
            }
            return value/n_elements;
        }
    }

    class Thread1 implements Runnable {
        @Override
        public void run() {
            // Socket socket;
            try {
                serverSocket = new ServerSocket(SERVER_PORT);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                    }
                });
                try {
                    socket = serverSocket.accept();
                    client_connected   ;
                    output = new PrintWriter(socket.getOutputStream());
                    inputStream = new DataInputStream(socket.getInputStream());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvMessages.append("Client 1 Connected\n");
                            btn_client_1.setEnabled(true);
                            if(client_connected == 3) {
                                // new Thread(new MainActivity.Thread2()).start();
                                tvMessages.append("You can start your recording...\n");
                            }
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    class Thread11 implements Runnable {
        @Override
        public void run() {
            try {
                serverSocket_2 = new ServerSocket(SERVER_PORT_2);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run(){
                    }
                });
                try {
                    socket_2 = serverSocket_2.accept();
                    client_connected   ;
                    output_2 = new PrintWriter(socket_2.getOutputStream());
                    inputStream_2 = new DataInputStream(socket_2.getInputStream());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvMessages.append("Client 2 Connected\n");
                            btn_client_2.setEnabled(true);
                            if(client_connected == 3) {
                                tvMessages.append("You can start your recording...\n");
                            }
                        }
                    });
                 
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    class Thread111 implements Runnable {
        @Override
        public void run() {
            try {
                serverSocket_3 = new ServerSocket(SERVER_PORT_3);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run(){

                    }
                });
                try {
                    socket_3 = serverSocket_3.accept();
                    client_connected   ;
                    output_3 = new PrintWriter(socket_3.getOutputStream());
                    inputStream_3 = new DataInputStream(socket_3.getInputStream());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvMessages.append("Client 3 Connected\n");
                            btn_client_3.setEnabled(true);
                            if(client_connected == 3) {
                                tvMessages.append("You can start your recording...\n");
                            }
                        }
                    });
                   
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    class Thread_BioFeedback implements  Runnable {
        private int case_audio;
        private int ID;
        Thread_BioFeedback(int case_audio, int ID) {
            this.case_audio = case_audio;
            this.ID = ID;
        }
        @Override
        @RequiresApi(api = Build.VERSION_CODES.O)
        public void run() {
            int time_vibration = 2000;
            run_feedback(case_audio,time_vibration, ID);
        }
    }


    public class TimeStamp {
        int prevSample1;
        int prevSample2;
        int prevSample3;
        int currSample1;
        int currSample2;
        int currSample3;
    }

    public void checkSampleTime(TimeStamp timeStamp) {
        if (btn_client_1.isEnabled()) {
            int diff_1 = timeStamp.currSample1 - timeStamp.prevSample1;
            if (diff_1 != 10) {
                tvMessages.append("sampleTime1 Failure\n");
                new Thread(new MainActivity.Thread_BioFeedback(5,3)).start();
            }
        }
        if (btn_client_2.isEnabled()) {
            int diff_2 = timeStamp.currSample2 - timeStamp.prevSample2;
            if (diff_2 != 10) {
                tvMessages.append("sampleTime2 Failure\n");
                new Thread(new MainActivity.Thread_BioFeedback(6,3)).start();
            }
        }
        if (btn_client_3.isEnabled()) {
            int diff_3 = timeStamp.currSample3 - timeStamp.prevSample3;
            if (diff_3 != 10) {
                tvMessages.append("sampleTime3 Failure\n");
                new Thread(new MainActivity.Thread_BioFeedback(7,3)).start();
            }
        }
    }

    private class Thread2 implements Runnable {
        @Override
        public void run() {
            TimeStamp timeStamp = new TimeStamp();
            while (true) {
                try {
                    byte[] buffX = new byte[BUFFER_LENGTH*2-8];
                    byte[] buffX_2 = new byte[BUFFER_LENGTH*2-8];
                    byte[] buffX_3 = new byte[BUFFER_LENGTH*2-8];
                    if (btn_client_1.isEnabled()) {
                        int k = inputStream.read(buffX);
                        byte[] c = new byte[buffX.length   client1.length];
                        System.arraycopy(buffX, 0, c, 0, buffX.length);
                        System.arraycopy(client1, 0, c, buffX.length, client1.length);
                        fou.write(c);
                        float pitch_1 = from_bytes_to_float(buffX,18);
                        pitch_buff_1.add(pitch_1);
                        int [] data = unpack(buffX);
                        lc_buff_1.add(data[13]);
                        if (flag_Acq_1 == 1){
                            // timeStamp.currSample1 = (data[16]<<16) | (data[15] & 0xFFFF);
                            timeStamp.currSample1 = (data[15]<<16) | (data[14] & 0xFFFF);
                            flag_Acq_1 = 0;
                        } else {
                            timeStamp.prevSample1 = timeStamp.currSample1;
                            timeStamp.currSample1 = (data[15]<<16) | (data[14] & 0xFFFF);
                        }
                    }
                    if (btn_client_2.isEnabled()) {
                        int k_2 = inputStream_2.read(buffX_2);
                        byte[] c_2 = new byte[buffX_2.length   client2.length];
                        System.arraycopy(buffX_2, 0, c_2, 0, buffX_2.length);
                        System.arraycopy(client2, 0, c_2, buffX_2.length, client2.length);
                        fou.write(c_2);
                        float pitch_2 = from_bytes_to_float(buffX_2,18);
                        pitch_buff_2.add(pitch_2);
                        int [] data_2 = unpack(buffX_2);
                        lc_buff_2.add(data_2[13]);
                        if (flag_Acq_2 == 1){
                            timeStamp.currSample2 = (data_2[15]<<16) | (data_2[14] & 0xFFFF);
                            flag_Acq_2 = 0;
                        } else {
                            timeStamp.prevSample2 = timeStamp.currSample2;
                            timeStamp.currSample2 = (data_2[15]<<16) | (data_2[14] & 0xFFFF);
                        }
                    }
                    if (btn_client_3.isEnabled()) {
                        int k_3 = inputStream_3.read(buffX_3);
                        byte[] c_3 = new byte[buffX_3.length   client3.length];
                        System.arraycopy(buffX_3, 0, c_3, 0, buffX_3.length);
                        System.arraycopy(client3, 0, c_3, buffX_3.length, client3.length);
                        fou.write(c_3);
                        float pitch_3 = from_bytes_to_float(buffX_3,18);
                        pitch_buff_3.add(pitch_3);
                        int [] data_3 = unpack(buffX_3);
                        lc_buff_3.add(data_3[13]);
                        if (flag_Acq_3 == 1){
                            timeStamp.currSample3 = (data_3[15]<<16) | (data_3[14] & 0xFFFF);
                            flag_Acq_3 = 0;
                        } else {
                            timeStamp.prevSample3 = timeStamp.currSample3;
                            timeStamp.currSample3 = (data_3[15]<<16) | (data_3[14] & 0xFFFF);
                        }
                    }
                    if (flag_Acq == 1) {
                        flag_Acq = 0;
                    } else {
                        checkSampleTime(timeStamp);
                    }

                   
                    if (message != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (x%plot_freq==0) {
                                    float value = average_list(pitch_buff_1, plot_freq);
                                    float value_2 = average_list(pitch_buff_2, plot_freq);
                                    float value_3 = average_list(pitch_buff_3, plot_freq);
                                    float lc_avg = average_listInt(lc_buff_1, plot_freq);
                                    float lc_avg_2 = average_listInt(lc_buff_2, plot_freq);
                                    float lc_avg_3 = average_listInt(lc_buff_3, plot_freq);
                                    if (y>=4000) {
                                        
                                        series.resetData(new DataPoint[] {new DataPoint(x, value)});
                                        series_2.resetData(new DataPoint[] {new DataPoint(x, value_2)});
                                        series_3.resetData(new DataPoint[] {new DataPoint(x, value_3)});
                                        lc.resetData(new DataPoint[] {new DataPoint(x, lc_avg)});
                                        lc2.resetData(new DataPoint[] {new DataPoint(x, lc_avg_2)});
                                        lc3.resetData(new DataPoint[] {new DataPoint(x, lc_avg_3)});
                                        y = 0;
                                    } else {
                                        series.appendData(new DataPoint(x, value),true,500);
                                        series_2.appendData(new DataPoint(x, value_2),true,500);
                                        series_3.appendData(new DataPoint(x, value_3),true,500);
                                        lc.appendData(new DataPoint(x, lc_avg),true,500);
                                        lc2.appendData(new DataPoint(x, lc_avg_2),true,500);
                                        lc3.appendData(new DataPoint(x, lc_avg_3),true,500);
                                    }
                                    pitch_buff_1.clear();
                                    pitch_buff_2.clear();
                                    pitch_buff_3.clear();
                                    lc_buff_1.clear();
                                    lc_buff_2.clear();
                                    lc_buff_3.clear();
                                    Log.v("Plot Update","OK");
                                }
                                x  = 1;
                                y  = 1;
                                Log.v("Plot Update",String.valueOf(x));
                            }
                        });
                    } else {
                        Thread1 = new Thread(new MainActivity.Thread1());
                        Thread1.start();
                        return;
                    }
                    Thread.sleep(1);
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class Thread3 implements Runnable {
        private String message;
        Thread3(String message) {
            this.message = message;
        }
        @Override
        public void run() {
            if (btn_client_1.isEnabled()) {
                output.write(message);
                output.flush();
            }
            if (btn_client_2.isEnabled()) {
                output_2.write(message);
                output_2.flush();
            }
            if (btn_client_3.isEnabled()) {
                output_3.write(message);
                output_3.flush();
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvMessages.append("server: "   message   "\n");
//                    etMessage.setText("");
                }
            });
        }
    }

}
  • Related