So I am new to Java and android development. So far I have been creating an app that is able to connect and interface with an arduino. I have a method that is able to read the data from the arduino (in bytes ) and then print the data as a string in UTF-8....However, I simply want this method to read and interpret the data, and have the interpreted data to be callable from another method, say button from android. Following is code that reads the data.
public class MainActivity extends AppCompatActivity {
public final String Action_USB_Permission = "com.example.myapplication.USB_PERMISSION";
UsbManager usbManager;
UsbDevice device;
UsbSerialDevice serial;
UsbDeviceConnection connection;
String data;
String adata;
TextView textView;
Button tempButton
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
@Override
public void onReceivedData(byte[] arg0) {
try {
data = new String(arg0, "UTF-8"); //edit (removed String in "String data =" )
} catch (UnsupportedEncodingException e) {
e.getStackTrace();
}
}
};
// Serial codes and commands
public void pushcmd(String command) { //command for serial
serial.write(command.getBytes());
}
public void gettemp() {
pushcmd("T\n");
serial.read(mCallback);
adata = data;
}
//This is for the app creation i think
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usbManager = (UsbManager) getSystemService(this.USB_SERVICE);
tempButton = (Button) findViewById(R.id.buttontemp);
}
public void onClickTemp(View view) { //This is the command to print data
gettemp();
tvAppend(textView, "\n Measured temperature \n" + adata);
}
private void tvAppend(TextView tv, CharSequence text) {
final TextView ftv = tv;
final CharSequence ftext = text;
runOnUiThread(new Runnable() {
@Override
public void run() {
ftv.append(ftext);
}
});
}
}
tvAppend is a method that prints the string on a textview on the screen. I got the libraries from https://github.com/felHR85/UsbSerial and it says to simply reference it with
serial.read(mcallback), I have tried the command, but I receive a "measured temperaturenull" then the measurement is printed after, which is from the onReceivedData method . Any suggestions would be greatly appreciated.Or if I'm not clear, let me know, I'll try to clear things up some more.
Edit: I added my tvAppend method, defined a textview field and a button. I am also pointing out that I don't have the whole program included, I followed the implementation from all about circuits http://www.allaboutcircuits.com/projects/communicate-with-your-arduino-through-android/ Thanks again for the feedback
COMMENT about edit: when the code is changed to how it is above. the adata is not displayed, only "Measured temperature".