I’m writing an app that allows me to send a command through TCP/IP by clicking a button. However when I click to the button in the emulator it comes back with a message saying the button has stopped working. I was wondering if anyone could spot the error in my code.
CODE:
package button.test;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class ButtonActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View view) throws UnknownHostException, IOException
{
Socket socket = new Socket("192.168.2.92", 60128);
try{
dataOutputStream.Object BUFFER = null;
write(BUFFER);
String buffer="ISCP000000100000000701000000!1PWR010D";
OutputStream os=socket.getOutputStream();
os.write(buffer.getBytes());
} catch(IOException e)
{
//error code
}
}
private void write(Object BUFFER) {
// TODO Auto-generated method stub
}
}
1. You missed declaring the button, and initializing it…
Eg:
– Make a note that you must initialize the views only after the setContentView(), else your views won’t get the id and will make your App to crash.
2. Its always advisable to keep the UI work on UI thread, and Non-UI work on Non-UI thread, but that became a law with the arrival of HoneyComb android version.
3. You can use
Thread with a Handlerto sync UI and Non-UI thread.4.
AsyncTaskwhich is known as Painless Threading was introduced specially in android for this.See this link for tutorials on Threads, Handlers and AsyncTask:
http://www.vogella.com/articles/AndroidPerformance/article.html