public void bytesToHex(byte[] in) {
final StringBuilder builder = new StringBuilder();
int count=0;
final int BATCHSIZE=20;
sendingData = true;
Log.d("byteToHex", "sendingData = true, start sending data.");
sendSerial("w"); //write command
Log.d("byteToHex", "sending w");
for(byte b : in) {
//mBluetoothGatt.setCharacteristicNotification(characteristicRX, enabled);
//byte[] a = mBluetoothGatt.readCharacteristic(characteristicRX);
while(!newData){
if(resendData == true){//resends previously sent string
sendSerial(sendByte);
Log.d("byteToHex", "resendData = true, resending: " + sendByte);
resendData = false; //reset resendData flag
}
} //wait for next w from mcu
builder.append(String.format("%02x", b));
if(builder.length()== BATCHSIZE ){
sendByte= builder.toString();
sendSerial(sendByte);
newData = false;
Log.d("byteToHex", "newData = false");
count+=BATCHSIZE;
Log.d("byteToHex", "Sent " + count/2 + " bytes");
textViewFileProgress.setText(count/2 + "/" + fileLength); //<- THIS SETTEXT DOES NOT WORK
builder.setLength(0); //reset the string builder
}
} //for(byte b : in)
//send remaining bytes
sendByte= builder.toString();
sendSerial(sendByte);
newData = false;
Log.d("byteToHex", "newData = false");
count+=builder.length();
Log.d("byteToHex", "Sent " + count/2 + " byte");
textViewFileProgress.setText(count/2 + "/" + fileLength);//<- THIS SETTEXT WORKS
builder.setLength(0); //reset the string builder
sentTerminator = true; //flag to tell BLE service to check if terminator is received on mcu
sendSerial("||"); //terminating command, tell teensy last hex has been sent
while(sentTerminator == true){ //while terminator not yet received
if(resendTerminator == true){ //
sendSerial("||");
Log.d("byteToHex", "resending terminator");
resendTerminator = false; //Resend complete. reset resendTerminator flag.
}
}
sendingData = false;
//return builder.toString();
}//public void bytesToHex(byte[] in)
I am trying to set the text to my textview to display the current number of bytes sent.
Somehow, i have 2 of the exact same setText code in my function. textViewFileProgress.setText(count/2 + "/" + fileLength);
one of them is inside a for loop, which does not work.
the other is outside the for loop, which works.
I am sure the program ran that code, as I am able to see the debug messages before it in Android monitor.
Any idea what is the problem?
Try this .
Log.e("TAG",builder.length()+"");
if(builder.length()== BATCHSIZE ){
sendByte= builder.toString();
sendSerial(sendByte);
newData = false;
Log.d("byteToHex", "newData = false");
count+=BATCHSIZE;
Log.d("byteToHex", "Sent " + count/2 + " bytes");
textViewFileProgress.setText(count/2 + "/" + fileLength); //<- THIS SETTEXT DOES NOT WORK
builder.setLength(0); //reset the string builder
} else {
Log.e("TAG","length != 20");
}
And you can see the Logcatinfo
Consider this simple code. You implement your for loop in another background thread then set the text in main thread using onPostExecute()
Note that onPostExecute() run in the main thread while doInBackground() run in the background thread so you cannot set the text in doInBackground()
public void outSideFunction()
{
//pass a string to doInBackground()
new TextSetterTask.execute("");
}
//implement an inner class
private class TextSetterTask extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... params)
{
//loop
return //the string you want to set the text
//if the background thread is done it will call the onPostExecute
}
#Override
protected void onPostExecute(String result)
{
//set the text
}
}
Related
i'm design an app that gets values from an Arduino via bluetooth connection and it can get the data but some times it gets the data but with the 1st digit wrong.
Like it gets 840,564,0,0,0,0 instead of 540,564,0,0,0,0.
this only happens in my app. Via USB it works perfect.
here is the code for the arduino.
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(38400);
pinMode(7, INPUT);
pinMode(6, INPUT);
pinMode(5, INPUT);
pinMode(4, INPUT);
}
void loop() {
// read the input on analog pin 1:
int pot1 = analogRead(A1);
// read the input on analog pin 0:
int pot2 = analogRead(A0);
int switch1 = digitalRead(7);
int switch2 = digitalRead(6);
int switch3 = digitalRead(5);
int switch4 = digitalRead(4);
// print out the value you read:
Serial.print(pot1);
Serial.print(",");
Serial.print(pot2);
Serial.print(",");
Serial.print(switch1);
Serial.print(",");
Serial.print(switch2);
Serial.print(",");
Serial.print(switch3);
Serial.print(",");
Serial.println(switch4);
delay(100); // delay in between reads for stability
}
and here is some of the code for my app
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
// update TextView
dataFromArd=sbprint;
String segments[]=dataFromArd.split(",");
//angle1= -90 + (Integer.getInteger(segments[0]) - -333) * (90 - -90) / (333 - -333);
if (segments[0].length()>2 && segments[0].length()<4) {
int segmentInt1= Integer.parseInt(segments[0]);
int segmentInt2= Integer.parseInt(segments[1]);
if (segmentInt1 > 180 || segmentInt1 < 900) {
//angle1 = Integer.parseInt(segments[0]) - 529;
//angle1= -90 + (Integer.parseInt(segments[0]) - (515-333)) * (90 - -90) / (515+333) - (515-333);
int data1= (int) (0.27 * segmentInt1 - 139);
int data2=(int) (0.27 * segmentInt2 - 151);
if (data1!=angle1 && Math.abs(data1-angle1)<10){
angle1 = data1;
speedView.speedTo(angle1,5);
Log.d("int", segments[0] + "-" + Math.abs(data1-angle1) + "-" + angle1 + " " + segments[1] + "-" + Math.abs(data2-angle2) + "-" + angle2);
}
if (data2!=angle2 && Math.abs(data2-angle2)<25){
speedView2.speedTo(angle2,5);
angle2 = data2;
Log.d("int2", segments[0] + "-" + Math.abs(data1-angle1) + "-" + angle1 + " " + segments[1] + "-" + Math.abs(data2-angle2) + "-" + angle2);
}
//Log.d("int", Math.abs(data1-angle1) + "-" + angle1 + " " + Math.abs(data2-angle2) + "-" + angle2);
teste.setText("Data from Arduino: " + segments[0] + segments[1]);
}
}
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
};
};
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
}
public void run() {
byte[] buffer = new byte[256]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
}
It seems that the problem was excess usage of memory and that made the app skip frames and not getting the correct data.
I solved it by adding a dummy value for the first segment of data as a String and after filtering out the corrupt data (if the 1st segment != to String don't get data).
After that I made a lot of performance improvements that fixed the problem.
I wrote an Android app that plays multi-track audio files and it works completely in the simulator. On the device, it plays for a few seconds and then starts skipping and popping every few seconds. If I continuously tap the screen in the dead space of the app, the skipping doesn't occur and then recurs about 5 seconds after screen tapping ceases. I presume that this has something to do with thread priority, but I log the thread priority in the play loop and it never changes.
I'm hoping that somebody can tell me either:
a hack where I can simulate a screen tap every second so that I can run a beta test without the app skipping
explain a way to debug activity/thread/etc priority when it seems that my thread priority isn't changing when it seems like it is.
Here is how the player code is executed:
private class DecodeOperation extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... values) {
AudioTrackPlayer.this.decodeLoop();
return null;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
Here is the relevant player code:
private void decodeLoop()
{
ByteBuffer[] codecInputBuffers;
ByteBuffer[] codecOutputBuffers;
// extractor gets information about the stream
extractor = new MediaExtractor();
try {
extractor.setDataSource(this.mUrlString);
} catch (Exception e) {
mDelegateHandler.onRadioPlayerError(AudioTrackPlayer.this);
return;
}
MediaFormat format = extractor.getTrackFormat(0);
String mime = format.getString(MediaFormat.KEY_MIME);
// the actual decoder
codec = MediaCodec.createDecoderByType(mime);
codec.configure(format, null /* surface */, null /* crypto */, 0 /* flags */);
codec.start();
codecInputBuffers = codec.getInputBuffers();
codecOutputBuffers = codec.getOutputBuffers();
// get the sample rate to configure AudioTrack
int sampleRate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
Log.i(LOG_TAG,"mime "+mime);
Log.i(LOG_TAG,"sampleRate "+sampleRate);
// create our AudioTrack instance
audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC,
sampleRate,
AudioFormat.CHANNEL_OUT_5POINT1,
AudioFormat.ENCODING_PCM_16BIT,
AudioTrack.getMinBufferSize (
sampleRate,
AudioFormat.CHANNEL_OUT_5POINT1,
AudioFormat.ENCODING_PCM_16BIT
),
AudioTrack.MODE_STREAM
);
// start playing, we will feed you later
audioTrack.play();
extractor.selectTrack(0);
// start decoding
final long kTimeOutUs = 10000;
MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
boolean sawInputEOS = false;
boolean sawOutputEOS = false;
int noOutputCounter = 0;
int noOutputCounterLimit = 50;
while (!sawOutputEOS && noOutputCounter < noOutputCounterLimit && !doStop) {
//Log.i(LOG_TAG, "loop ");
noOutputCounter++;
if (!sawInputEOS) {
inputBufIndex = codec.dequeueInputBuffer(kTimeOutUs);
bufIndexCheck++;
// Log.d(LOG_TAG, " bufIndexCheck " + bufIndexCheck);
if (inputBufIndex >= 0) {
ByteBuffer dstBuf = codecInputBuffers[inputBufIndex];
int sampleSize =
extractor.readSampleData(dstBuf, 0 /* offset */);
//Log.d(LOG_TAG, "SampleLength = " + String.valueOf(sampleSize));
long presentationTimeUs = 0;
if (sampleSize < 0) {
Log.d(LOG_TAG, "saw input EOS.");
sawInputEOS = true;
sampleSize = 0;
} else {
presentationTimeUs = extractor.getSampleTime();
}
// can throw illegal state exception (???)
codec.queueInputBuffer(
inputBufIndex,
0 /* offset */,
sampleSize,
presentationTimeUs,
sawInputEOS ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0);
if (!sawInputEOS) {
extractor.advance();
}
}
else
{
Log.e(LOG_TAG, "inputBufIndex " +inputBufIndex);
}
}
int res = codec.dequeueOutputBuffer(info, kTimeOutUs);
if (res >= 0) {
//Log.d(LOG_TAG, "got frame, size " + info.size + "/" + info.presentationTimeUs);
if (info.size > 0) {
noOutputCounter = 0;
}
int outputBufIndex = res;
ByteBuffer buf = codecOutputBuffers[outputBufIndex];
final byte[] chunk = new byte[info.size];
buf.get(chunk);
buf.clear();
audioTrack.write(chunk,0,chunk.length);
if(this.mState != State.Playing)
{
mDelegateHandler.onRadioPlayerPlaybackStarted(AudioTrackPlayer.this);
}
this.mState = State.Playing;
}
codec.releaseOutputBuffer(outputBufIndex, false /* render */);
if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
Log.d(LOG_TAG, "saw output EOS.");
sawOutputEOS = true;
}
} else if (res == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
codecOutputBuffers = codec.getOutputBuffers();
Log.d(LOG_TAG, "output buffers have changed.");
} else if (res == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
MediaFormat oformat = codec.getOutputFormat();
Log.d(LOG_TAG, "output format has changed to " + oformat);
} else {
Log.d(LOG_TAG, "dequeueOutputBuffer returned " + res);
}
}
Log.d(LOG_TAG, "stopping...");
relaxResources(true);
this.mState = State.Stopped;
doStop = true;
// attempt reconnect
if(sawOutputEOS)
{
try {
AudioTrackPlayer.this.play();
return;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(noOutputCounter >= noOutputCounterLimit)
{
mDelegateHandler.onRadioPlayerError(AudioTrackPlayer.this);
}
else
{
mDelegateHandler.onRadioPlayerStopped(AudioTrackPlayer.this);
}
}
Have you monitored the CPU frequency while your application is running? The CPU governor is probably scaling the CPU up on touch and scaling back down on a timer. Increasing the priority on your background thread to THREAD_PRIORITY_DEFAULT will probably fix the issue, the default priority for AsyncTask is quite low and not appropriate for Audio.
You could also increase the size of the AudioTrack's buffer to some multiple of the value returned by getMinBufferSize, that method only returns the minimum possible buffer for the Class to operate, it does not guarantee smooth playback.
Good day. I am trying to get the code below to write to a txt file. Yet, I cannot get it to. It just prints the code within the ("") on the output section. My goal is to create the text file to store the output data to retrieve later.
public class Charlesshaw3Test {
public static void main(String[] args) throws Exception{
**//checking id command line argument provided
if(args.length==0) {
System.out.println("C:\\Users\\bryon\\Desktop\\Java Programming");
System.exit(1);
}
String fileName = args[0];
BufferedWriter out = null;
try {
FileWriter fstream = new FileWriter(fileName);
out = new BufferedWriter(fstream);
}
catch (IOException ex) {
System.out.println("\nCould not create file: "+ fileName+".");
System.exit(1);
}**
//a) 10 Instances of the violin testing.
CharlesShaw3Tst voilin[] = new CharlesShaw3Tst[10];
for (int i = 0; i < 10; i++) {
out.write("\n\n***Creating new violin object [" + (i + 1) + "]***");
voilin[i] = new CharlesShaw3Tst();
out.write("\nCreated");
//b) tune your instruments,
out.write("\nchecking if tuned?");
out.write("\nVoilin tuned? " + voilin[i].isTuned());
out.write("\nTuning...");
voilin[i].setTuned(true);
out.write("\nVoilin tuned? " + voilin[i].isTuned());
//c) Start playing your instrument,
out.write("\nVoilin playing? " + voilin[i].isPlaying());
out.write("\nVoilin tuned? " + voilin[i].isTuned());
out.write("\nCalling playVoilin method");
voilin[i].playViolin();
out.write("\nVoilin playing? " + voilin[i].isPlaying());
// d) Call your unique method, and
int num = voilin[i].getNumString();
out.write("\nNumber of strings: " + num);
out.write("\nString name: ");
String strings[] = voilin[i].getviolinStrings();
for (int s = 0; s < num; s++) {
out.write(strings[s] + " ");
}
out.write("\n");
//e) Stop playing your instruments.
out.write("\nStopping playing..");
voilin[i].stopViolin();
out.write("\nVoilin playing? " + voilin[i].isPlaying());
out.write("\nStopping tuning..");
voilin[i].stopTuneViolin();
out.write("\nVoilin tuned? " + voilin[i].isTuned());
}
//Close the output stream
out.close();
}
}
Try using FileWriter's append method:
try {
FileWriter writer = new FileWriter(file);
writer.append("Your string");
//Append all strings
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
The previous program it is referring to is:
public class CharlesShaw3Tst {
private final int numString = 5; // number of strings
private final String violinStrings[] = {"E", "B", "G", "D", "A"}; //an array of strings
//fields to determine if the instrument is tuned,
private boolean tuned;
//and if the instrument is currently playing.
private boolean playing;
//A constructor method that set the tuned and currently playing fields to false.
public CharlesShaw3Tst() {
this.tuned = false;
this.playing = false;
}
// Other methods
public boolean isPlaying() {
return playing;
}
public void setPlaying(boolean playing) {
this.playing = playing;
}
public boolean isTuned() {
return tuned;
}
public void setTuned(boolean isTuned) {
this.tuned = isTuned;
}
public void playViolin() {
System.out.println("The violin is now playing.");
playing = true;
}
public void stopViolin() {
System.out.println("The violin is now playing.");
playing = true;
}
public void tuneViolin() {
System.out.println("The violin is tuned.");
tuned = true;
}
public void stopTuneViolin() {
System.out.println("The violin is tuned.");
tuned = false;
}
public int getNumString() {
return this.numString ;
}
public String[] getviolinStrings() {
return violinStrings;
}
}
I'm taking Java Introductory Programming class and currently i'm working on a final project. The assignment description can be found here link
I'm having hard time with accomplishing this "Write the output from your Instrument class methods to a text file that a user entered from the command line arguments (e.g. java Mynamep3tst myfilename.txt)." Here's some of my code:
import java.io.*;
public class Test{
public static void main(String[] args) {
String outputFile = "";
if (0 < args.length) {
outputFile = args[0];
System.out.println("This program will write output to this file: " + outputFile + "\n");
try {
File file = new File(outputFile);
PrintWriter output = new PrintWriter(outputFile);
output.println("hello"); //to check if ir prints anything
Violin[] simpleViolin = new Violin[5];
//Create 5 violin objects
for (int i = 0; i < simpleViolin.length; i++){
simpleViolin[i] = new Violin();
}
output.println("\nLet's tune " + Violin.getNumberOfViolins() + " violins.");
for(int i = 0; i < simpleViolin.length; i++){
output.print(i + 1);
simpleViolin[i].tuneOn();
}
output.println("\nNow let's start playing " + Violin.getNumberOfViolins() + " violins.");
for(int i = 0; i < simpleViolin.length; i++){
output.print(i + 1);
simpleViolin[i].startPlaying();
}
output.println("\nIt looks like " + Violin.getNumberOfViolins() + " violins have untuned.");
for(int i = 0; i < simpleViolin.length; i++){
output.print(i + 1);
simpleViolin[i].tuneOff();
}
output.println("\nThis music is terrible! Let's stop it!");
for(int i = 0; i < simpleViolin.length; i++){
output.print(i + 1);
simpleViolin[i].stopPlaying();
}
output.close();
}
catch (IOException io){
System.out.println("Sorry that file is not found " + io);
}
}//end if
}//end main
}//end Test
class Violin{
private final int numberOfStrings = 4;
private final char[] stringNames = {'E', 'A', 'D', 'G'};
private boolean isTuned = false;
private boolean isPlaying = false;
private static int numberOfViolins = 0;
private PrintWriter output;
public Violin(){
numberOfViolins++;
}
public void startPlaying() {
isPlaying = true;
System.out.println(" violin is now playing.");
}
public void stopPlaying() {
isPlaying = false;
System.out.println(" violin has stopped playing.");
}
public void tuneOn() {
isTuned = true;
System.out.println(" violin is now tuned.");
}
public void tuneOff() {
isTuned = false;
System.out.println(" violin is untuned.");
}
static int getNumberOfViolins(){
return numberOfViolins;
}
}//end class Violin
So my question is how do I make my Violin class methods to print to a user specified file?
When you create your Violin object you can pass the output as a reference on the constructor so inside the violin you will use output instead of System.out.println.
Change the Violoin constructor to:
public Violin (PrintStream output){
this.output = output;
}
And then just use the outpu inside the violin.
I have a method which processes a line to seperate the first word which it puts into a string called cmd and the rest which it enters into a vector of strings for the parameters and then sends them to a function to process the command. The parameters are getting wrapped in square braces for some reason.
static private boolean processLine(String line) {
if (debug) System.out.println("DEBUG: processLine \"" + line + "\"");
line = new String(line.trim());
String cmd = new String();
Vector<String> params = new Vector<String>(3);
boolean hasparam = false;
Scanner s = new Scanner(line).useDelimiter(" ");
int x = 0;
while (s.hasNext()) {
if (x == 0) { cmd = s.next(); }
else if (x >= 1) {
params.add(s.next());
hasparam = true;
}
x++;
}
// Next we process the command.
processCmd(cmd, params);
return exit;
}
static private void processCmd(String cmd, Vector<String> params) {
boolean invalid = false;
if (debug) {
System.out.print("DEBUG: processCmd " + cmd);
if (params.size() == 0) System.out.println();
else for (String param : params)
System.out.println(" " + params);
}
Output:
> add hosting
DEBUG: processLine "add hosting"
DEBUG: processCmd add [hosting]
I'm not sure why I am getting this behaviour, and I would like an explanation as well as a solution.
The parameters are getting wrapped in square braces for some reason.
This is because you are printing the Vector itself rather than the element of Vector. So toString() method of Vector is calling out in following line:
System.out.println(" " + params);
Change this line to:
System.out.println(" " + param);