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

标签 android http crash request

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

我有上网权限

在服务器端,我有一个读取 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();
            }
        }
    });
}

最佳答案

logcat 会非常有用,但它可能来自于在 UI 上执行网络操作。您应该将所有网络代码移至后台 Thread,例如 AsyncTask。这将使您可以轻松地在后台执行网络操作,然后在 UI 上运行的函数中根据需要更新 UI

AsyncTask Docs

显示基本结构的 Here is an answer。基本上,您从 UI 中调用 AsyncTask,例如在您的 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 
}

关于android - 每次我发出 http 请求时,应用程序都会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18388468/

相关文章:

android - 从 Play 商店安装应用程序后获取推荐人详细信息

android - Android 中保存到数据库时去掉括号

android - 使用 Gradle 在 Android Studio 中导入 BuildConfig

ruby - 无法使用 Ruby 1.9.3 正确读取 HTTP 请求 header

apache-flex - 启用rtmfp时,FMS服务器每天都会死亡

android - TextInputLayout 和 TextView 之间的额外空间

ios ->= 400 错误代码与 apple-app-site-association json 文件

java - 我怎样才能在 java 中克服这个 HTTP GET 404 错误?

android - FragmentActivity 导致 ClassNotFoundException

C++ 程序已停止工作 - 求解常微分方程