This is my code every time i touch the imageview my app waits about 5 secs and then chrashes
I have the INTERNET permission
On the server side i have a php page that reads the GET and insert it in a database
public class Home extends Activity {
ImageView lightbut;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ImageView lightbut = (ImageView) findViewById(R.id.light);
lightbut.setClickable(true);
lightbut.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("== My activity ===","OnClick is called");
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpGet httpPost = new HttpGet("http://192.168.0.102/HR/index.php?command=ligthsoff");
try {
HttpResponse response = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
}
});
}
A logcat would be very helpful but its probably from doing network stuff on the
UI
. You should move all of your network code to a backgroundThread
such as anAsyncTask
. This will easily allow you to do the network stuff in the background then update theUI
if needed in functions that run on theUI
.AsyncTask Docs
Here is an answer that shows the basic structure. Basically, you call the
AsyncTask
from theUI
such as in youronClick()
then you do network operations indoInBackground()
which is called when the task first starts then you can update theUI
in any of its other methods.Using the example I referenced, you would just put all of your network stuff, which looks like everything in your
onClick()
, inside thedoInBackground()
method of the example in the link. Then in youronClick()
you would do something like