【问题标题】:okHttp :why my application is crashing didnt get responseokHttp:为什么我的应用程序崩溃没有得到响应
【发布时间】:2016-07-14 06:41:49
【问题描述】:

主要活动

公共类 MainActivity 扩展 AppCompatActivity { 字符串响应;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    }

公共无效点击(查看 v){ GetExample 示例 = new GetExample();

  try {
      response = example.run();
      Toast.makeText(MainActivity.this, "response is :" + response, Toast.LENGTH_LONG).show();

  } catch (IOException e) {
      Toast.makeText(MainActivity.this, "error" + e, Toast.LENGTH_LONG).show();

   }
  }
 }

GetExample 类

公共类 GetExample { OkHttpClient 客户端;

public String run() throws IOException {
     client = new OkHttpClient();
    Request request = new Request.Builder().url("http://grocit.pe.hu/getcategories.php").build();
    Response response = client.newCall(request).execute();
    return response.body().string();
}
}

Xml 文件

<RelativeLayout
  android:layout_height="match_parent"
   android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
<Button
    android:layout_width="300dp"
    android:layout_height="300dp"
    android:onClick="click"
    android:text="click me!"
    />
</RelativeLayout>

【问题讨论】:

    标签: android networking okhttp


    【解决方案1】:

    对于此类崩溃问题,您可以添加崩溃日志。我认为NetworkOnMainThreadException 会发生此崩溃。当您的应用程序尝试在其主线程上执行网络操作时会引发此异常。 您的网络操作必须在另一个线程上执行,例如:

        Thread thread = new Thread() {
                @Override
                public void run() {
                    // your run method
                }
            };
        thread.start();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 2018-04-03
      • 2017-06-28
      • 2014-09-20
      • 2010-09-20
      相关资源
      最近更新 更多