I'm successfully receiving data from microcontroller using bluetoth serial protocol as described, for example, in this tutorial:
http://solderer.tv/data-transfer-between-android-and-arduino-via-bluetooth/
I'am able to display the values I receive in a textView, but as soon as I try to graphically display the values, by adding a line whose length depends on the value, the application crashes.
I think I'm ok with the drawing functions themselves because I'm able to draw static pictures when the app starts:
Bitmap bg = Bitmap.createBitmap(480, 800, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bg);
Paint paint = new Paint();
paint.setColor(Color.parseColor(#6b8728));
paint.setXfermode(null);
canvas.drawLine(x, y, x2, y2, paint);
Bt maybe at the end should i use another way.
Anyway, this introduced, here's my problem. When I implement those drawing functions in the data listening thread, the app crashes. Hence I do not know how to perform the line drawing: new thread needed?( and how to do that?), painting has to be done in specific parts? Specific functions to use?...
I hope my question is clear, otherwise I'll be happy to add more details.
Thank you in advance for your help.
Kind regards,
Sylvain
Edit:
Adding my function:
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
final TextView t = (TextView)findViewById(R.id.textView);
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
Toast.makeText(MainActivity.this, data,
Toast.LENGTH_SHORT).show();
handler.post(new Runnable()
{
public void run() {
t.setText(data);
String[] separated = data.split(":");
separated[1].trim();
if ((separated[0].length() != 0)&& (separated[1].length() != 0)) {
t.append("\n" + separated[0]);
t.append("\n" + separated[1]);
t.append("\ntest");
String s_angle = separated[0];
String s_value = separated[1];
final Integer angle = Integer.parseInt(s_angle);
final Integer value = Integer.parseInt(s_value)/1000;
// Crashing here
Paint paint = new Paint();
paint.setColor(Color.parseColor("#6b8728"));
int width = canvas.getWidth()/2;
int height = canvas.getHeight()/2;
canvas.drawLine(width,height,150,50, paint);
}
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
else
{
//t.append(bytesAvailable+"\n");
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}