I have a FileInputStream that reads data from arduino. On my java code reading function in an infinite while loop. read function works just once in the beginning and stop doing its work and jumps to catch block continuously.
Why does it do that ONCE? It should read data continuously. Any suggestions?
while(true)
{
try
{ byte[] inputmessage =new byte[1];
ret=mInputStream.read(inputmessage);
SystemClock.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
SystemClock.sleep(2000);
}
finally{
try {
if(mInputStream!=null){
mInputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
veri = Arrays.toString(inputmessage);
veri = veri.replace("[","");
veri = veri.replace("]","");
publishProgress(Integer.parseInt(veri));
SystemClock.sleep(2000);
}
}
An inputstream will go through data only once, you can check with "markSupported()" if you can set a mark in your stream, if you can, you can set it and use "reset" when you want to restart from scratch.
Related
I am creating new connection class for Bluetooth device on Android Studio.I cant figure out why thrown exception in design time.
public ConnectingThread(BluetoothDevice device,MainActivity activity,BluetoothAdapter adapter) {
mainActivity=activity;
bluetoothAdapter=adapter;
BluetoothSocket temp = null;
bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket = temp;
}
The line:
temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);
has the potential to throw a NoSuchMethodException. You do not have a catch block to handle this exception. So you have to add another catch block under your existing catch block as follows:
catch(NoSuchMethodException e){
//Insert code here
}
Also, that line of code will later throw the following exceptions so it is best to handle them as well: IllegalAccessException, and InvocationTargetException. Thus, your try-catch blocks should be as follows:
try {
temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);
} catch (IOException e) {
e.printStackTrace();
}
catch(NoSuchMethodException ex){
//Insert code here
}
catch(IllegalAccessException e){
//Insert code here
}
catch(InvocationTargetException e){
//Insert code here
}
Alternatively, you could handle every single exception with the general Exception class. In this case, your code should look something like this:
try {
temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);
} catch (Exception e) {
//Enter code here
}
I have a simple FTP upload App that normally works fine.
Sometimes in the middle of a Upload I might lose INTERNET (moving between wifi spots or something).
When this happens the Upload keeps trying to upload but makes no progress, doesn't timeout or cause any errors and since the service never finishes I can't restart it unless I force stop the App.
How can I set timeout options and any other useful tool prevent my App from doing this?
How do I implement and to what effect the following or any other:
client.setConnectTimeout(60); //Are this milliseconds, seconds or what?
client.setDefaultTimeout(300); //Are this milliseconds, seconds or what?
client.setControlKeepAliveTimeout(120); //Are this milliseconds, seconds or what?
Here is a shoetened version of my code for you to see.
myFTP.class
public class myFTP{
String ip;
String user;
String pass;
FTPClient client = new FTPClient();
public myFTP() {
ip = "someip";
user = "´someuser";
pass = "somepass";
client = new FTPClient();
}
public boolean connect() {
//Define vars
try{
//Connect and login
client.setConnectTimeout(60);
client.setDefaultTimeout(300);
client.setControlKeepAliveTimeout(120);
client.connect(ip);
client.login(user,pass);
if(FTPReply.isPositiveCompletion(client.getReplyCode())){
client.setFileType(FTP.BINARY_FILE_TYPE);
}else{
Log.e ("Coneccion FTP", "Fallo");
}
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (SocketException e){
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean upload (String fileName, File file, String dir){
//Cargo el archivo
try{
FileInputStream fis = new FileInputStream(file);
client.enterLocalPassiveMode();
Log.e("Subiendo", fileName);
boolean status = client.storeFile(dir+fileName,fis);
if (!status){
fis.close();
return false;
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
try {
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}
I made some changes.
Had the FTP server connect and stay connected for all files instead of connecting and disconnecting for every file.
Added timeouts after a lot of trying and failing that seem to work.
In the alarm I stopped the service and then started a new one. If the service is hangged up it will start again.
I have a thread inside which I catch an exception. What I want is that when this happens, the thread closes/quits/dies or whatever I should say, and an alert dialog is displayed (no like toasts!).
Here's my code:
t1 = new Thread(new Runnable()
{
public void run()
{
Looper.prepare();
StringBuffer stringBuffer = new StringBuffer("");
BufferedReader bufferedReader = null;
URI uri = null;
try
{
requestAndMakeSheet(stringBuffer, bufferedReader, uri);
}
catch (Exception e)
{
//Toast.makeText(getBaseContext(), "Web Request Error", Toast.LENGTH_LONG).show();
//Log.e("Web Request Error", e.getMessage());
t1.interrupt();
AlertDialog.Builder parsingErrorBox = new AlertDialog.Builder(ReservationInfo.this);
parsingErrorBox.setTitle("Login error");
parsingErrorBox.setMessage("You may have to check your credentials and then try again.");
parsingErrorBox.show();
}
finally
{
if (bufferedReader!=null)
{
try
{
bufferedReader.close();
}
catch (IOException ioe)
{
Log.e("Web Request Error", ioe.getMessage());
}
}
}
}
});
t1.start();
try
{
t1.join();
mWebview.loadUrl("file:///"+Environment.getExternalStorageDirectory()+"/MySheet.html");
setContentView(mWebview);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//End of le thread
}
This code crashes, I think it has something to do with t1.interrupt (tried stop instead, but didn't work either).
How can I fix this code?
Thank you in advance.
Why do you have the t1.interrupt() anyway? Seems like your thread will be terminated regardless so what is the reason for putting it there?
Android: I am downloading a file from the internet using this method:
InputStream in = null;
try {
in = connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
byte[] buffer = new byte[1024];
int length = 0;
try {
while ((length = in.read(buffer)) != -1) {
try {
fout.write(buffer, 0, length);
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
The problem is that when the internet is turned off, the read inoutstream stops reading on some device, but it continues reading on other devices! How to solve this problem? thanks in advance.
EDIT:
I found the solution, I have to set a connection's timeout.
When you establish a connection, put that into a try-catch to know if establishing a connection fails. Handle your problem in the catch block. I don't exactly know how you are establishing the connection, so won't be able to suggest further.
I'm currently working on a tcp client in Android.
I want to connect my android device to a tcp server on my computer and receive the data once every 2 seconds. The problem is that I'm getting force close on my application because of the while loop that I've implemented in the tcp client.
I've tried writing in different ways the loop that will make the tcp client checking the server socket, but with no success. How can make a loop that will check the server socket without getting the force close?
Here's my code that I'm currently using:
public class Connection implements Runnable {
#Override
public void run() {
try {
sk=new Socket(server,port);
viewsurface.setText("connected");
flag = true;
} catch (UnknownHostException e) {
viewsurface.setText("failed 1 socket");
flag = false;
} catch (IOException e) {
viewsurface.setText("failed 2 socket");
flag = false;
}
while (flag == true){
try {
checkin = sk.getInputStream();
checkint = checkin.available();
if (checkint > 0){
try {
BufferedReader in = new BufferedReader(new InputStreamReader(sk.getInputStream()));
received = in.readLine();
viewsurface.setText(received);
} catch (IOException e) {
viewsurface.setText("failed to receive");
}
}
Thread.sleep(2000);
} catch (IOException e) {
viewsurface.setText("checkin failed");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
You need to paste the exception that you are getting to cause the force close, before anyone can provide decent help.
But some suggestions that might solve the problem.
Most likely to be the problem, viewText.setText can only be called from the UI thread. There's quite a few ways to handle this. You can use AsyncTask or if you have an Activity reference you can use runOnUIThread and pass in a runnable that calls setText.
Move checkin = sk.getInputStream(); to before the loop. There's no reason to get the strem every cycle through the loop.
Do not create the BufferedReader every cycle through the loop. Move it before the loop
.sleep(2000) does not guarantee exactly 2 seconds.
I'm having some code formatting issues so I apologize.
private class DownloadFilesTask extends AsyncTask<Void, String, Void> {
protected Long doInBackground(Void... nothing) {
try {
sk=new Socket(server,port);
publishProgress("connected");
flag = true;
} catch (UnknownHostException e) {
publishProgress("failed 1 socket");
flag = false;
} catch (IOException e) {
publishProgress("failed 2 socket");
flag = false;
}
while (flag == true){
try {
checkin = sk.getInputStream();
checkint = checkin.available();
if (checkint > 0){
try {
BufferedReader in = new BufferedReader(new InputStreamReader(sk.getInputStream()));
received = in.readLine();
publishProgress(received);
} catch (IOException e) {
publishProgress("failed to receive");
}
}
Thread.sleep(2000);
} catch (IOException e) {
updateProgress(
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
protected void onProgressUpdate(String... progress) {
viewsurface.setText(progress[0]);
}
protected void onPostExecute(Void result) {
//nothing
}
}