gpt4 book ai didi

java - Android Volley 同步请求不起作用

转载 作者:太空狗 更新时间:2023-10-29 15:50:41 25 4
gpt4 key购买 nike

我正在尝试使用 RequestFuture 向服务器发出一个同步请求,但它不起作用。使用异步完成时相同的请求工作正常。

这是我的代码:

 public void fetchModules(){
JSONObject response = null;
RequestQueue requestQueue = Volley.newRequestQueue(getContext());

RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(Url.ALL_MODULES_URL,null,future,future);
requestQueue.add(request);


try {
response = future.get(3, TimeUnit.SECONDS); // Blocks for at most 10 seconds.
} catch (InterruptedException e) {
Log.d(TAG,"interupted");
} catch (ExecutionException e) {
Log.d(TAG,"execution");
} catch (TimeoutException e) {
e.printStackTrace();
}

Log.d(TAG,response.toString());
}

我得到一个空指针异常:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference at com.maths.app.AllModules.fetchModules(AllModules.java:85) at com.maths.app.AllModules.onCreateView(AllModules.java:51) at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290) at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1677) at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:536) at android.os.Handler.handleCallback(Handler.java:746) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5443) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

它返回一个空响应。我该如何解决这个问题?

最佳答案

tl;博士;你被 try-catch 骗了

解释:因为 RequestFuture.get() 可能在 UI 线程上运行,您实际上在幕后得到了 java.util.concurrent.TimeoutException这是在主线程上执行调用时的默认行为。

try catch 阻止了应用程序崩溃,尽管如此,响应仍然是空引用,当您尝试记录结果时,它会导致应用程序崩溃。如果您评论以下行,您将看到该应用程序不再(在那里)崩溃。

Log.d(TAG,response.toString());

修复:在另一个线程上进行 RequestFuture 网络调用!

一种方法:

    public class TestVolley {

private String TAG = "SO_TEST";
private String url = "http://pokeapi.co/api/v2/pokemon-form/1/";


public JSONObject fetchModules(Context ctx){
JSONObject response = null;
RequestQueue requestQueue = Volley.newRequestQueue(ctx);


RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(url,null,future,future);
requestQueue.add(request);


try {
response = future.get(3, TimeUnit.SECONDS); // Blocks for at most 10 seconds.
} catch (InterruptedException e) {
Log.d(TAG,"interrupted");
} catch (ExecutionException e) {
Log.d(TAG,"execution");
} catch (TimeoutException e) {
e.printStackTrace();
}

Log.d(TAG,response.toString());

return response;
}
}

将进行网络调用的AsyncTask:

public class MyVolleyAsyncTask extends AsyncTask<String,String, JSONObject> {

private Context ctx;

public MyVolleyAsyncTask(Context hostContext)
{
ctx = hostContext;
}

@Override
protected JSONObject doInBackground(String... params) {

// Method runs on a separate thread, make all the network calls you need
TestVolley tester = new TestVolley();

return tester.fetchModules(ctx);
}


@Override
protected void onPostExecute(JSONObject result)
{
// runs on the UI thread
// do something with the result
}
}

主要 Activity :

public class MainActivity extends AppCompatActivity {

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

// this is your old code which will crash the app
//TestVolley tester = new TestVolley();
//tester.fetchModules(this);

// Works!
new MyVolleyAsyncTask(this).execute();
}
}

结果:

com.so.henriquems.testvolleyfuture D/SO_TEST: {"id":1,"pokemon":{"url":"http:\/\/pokeapi.co\/api\/v2\/pokemon\/1\/","name":"bulbasaur"},[...]

希望对你有帮助

干杯!

关于java - Android Volley 同步请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41724692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com