0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Volleyの同期処理を試そうとして詰まった件(Java)

Posted at

同期処理を試す

Volleyでも同期処理ができるという情報をもとに、以下の様なソースを実行させました。

app/build.gradle
dependencies {
    implementation 'com.android.volley:volley:1.1.1'
}
MyActivity.java
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String url = "https://example.com/";

        RequestFuture<String> future = RequestFuture.newFuture();
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, future, future);

        RequestQueue queue = Volley.newRequestQueue(MyActivity.this);
        queue.add(stringRequest);

        try {
            String result = future.get(10000, TimeUnit.MILLISECONDS);
            Log.d(TAG, result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

タイムアウトが発生

java.util.concurrent.TimeoutExceptionが発生します。
Logcatを読んでも例外が投げられたとしか分からないため原因が見えず。

非UIスレッドで実行(解決)

Android3.0以降、UIスレッドで同期処理を実行するとNetworkOnMainThreadExceptionが発生します。
どうやらVolleyの場合は落ちずにタイムアウトになるようです。
※厳密には別の原因かもしれませんが不明

AsyncTaskを使って以下のように書き換えると、正常に取得できました。

MyActivity.java
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] objects) {
                String url = "https://example.com/";

                RequestFuture<String> future = RequestFuture.newFuture();
                StringRequest stringRequest = new StringRequest(Request.Method.GET, url, future, future);

                RequestQueue queue = Volley.newRequestQueue(MyActivity.this);
                queue.add(stringRequest);

                try {
                    String result = future.get(10000, TimeUnit.MILLISECONDS);
                    Log.d(TAG, result);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return null;
            }
        }.execute();
    }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?