每次我发出http请求时,应用程序都会崩溃

时间:2013-08-22 18:43:43

标签: android http crash request

这是我的代码 每次我触摸imageview,我的应用程序等待大约5秒,然后崩溃

我有INTERNET权限

在服务器端,我有一个读取GET并将其插入数据库的php页面

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();
            }
        }
    });
}

1 个答案:

答案 0 :(得分:3)

logcat会非常有用,但可能来自UI上的网络内容。您应该将所有网络代码移至后台Thread,例如AsyncTask。这将很容易让您在后台执行网络内容,然后在UI上运行的函数中更新UI

AsyncTask Docs

显示基本结构的

Here is an answer。基本上,您拨打AsyncTask中的UI,例如onClick()中的doInBackground(),然后在UI中进行网络操作,当任务首次启动时调用该网络操作,然后您可以更新onClick()用于其他任何方法。

使用我引用的示例,您只需将链接中示例的doInBackground()方法中的所有网络内容(看起来像onClick()中的所有内容)放入其中。然后在你的lightbut.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { TalkToServer task = new TalkToServer(); // could pass params to constructor here but might not be needed in this situation task.execute(); // could pass in params for `doInBackground()` such as url, etc... but again maybe not needed for this situation } 中你会做类似

的事情
{{1}}
相关问题