我正在努力为我正在尝试创建的这个特定项目使用片段。我正在我创建的片段类中进行所有网络调用。当我调用建立连接的方法并将结果记录到控制台时,我从类中获取所有信息,但是当我尝试访问网络调用之外的实例时,我得到一个空指针异常。 我一直在查看文档和其他示例,但是大部分内容都与我需要的内容不同,文档没有提及在片段内使用 okhttp 。
我使用的代码是:
public void testAsyncCreate() {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(CREATE_MEDIA_TYPE, "data={\"process\":\"123\", \"phone\":\"111111111\"}");
Request request = new Request.Builder()
.url(ALLWAYS_API)
.post(body)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// any additional runnable items go in here
try {
String jsonData = response.body().string(); // the exception is caught at this point
Log.d("<Mensajes>",jsonData);
//extractCreate = parseExtractCreateDetails(jsonData);
if(response.isSuccessful()) {
extractCreate = parseExtractCreateDetails(jsonData);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d("<=====>", "check");
Log.d(TAG, "Is this even working?");
Log.d("The class has been ok",extractCreate.getCreateR().getAccount_id().toString());
Log.d("Another check", extractCreate.getStopsR()[1].getAddress());
}
});
}
//getStops(jsonData);
}catch(IOException e) {
}catch (JSONException e){
}
}
});
} // end of asyncCreate
然后在onCreateView()方法中:
ExtractCreate extractCreate = new ExtractCreate();
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragments_stops_list, container, false);
ButterKnife.bind(this, view);
if (savedInstanceState == null) {
testAsyncCreate();
}
Log.d("<extractCreateCheck>", String.valueOf(extractCreate.getCreateR().getAccount_id()));
return view:
}
我无法理解为什么在使用片段时这不起作用,我说这是因为如果我把它放在常规活动中并运行它我将能够在其他任何地方使用extractCreate的结果想要,但不是在这里。关于在片段中使用okhttp调用,我是否缺少任何步骤?目前这些文档对我来说并没有任何意义。 堆栈跟踪如下:
11-23 09:28:55.569 3288-3288/com.example.testC.demotrackertree E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.testC.demotrackertree, PID: 11142
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String at com.example.testC.demotrackertree.models.createmodels.CreateResponse.getAccount_id()' on a null object reference
at com.example.testC.demotrackertree.ui.fragments.StopCreateFragment.onCreateView(StopCreateFragment.java:95)
at android.app.Fragment.performCreateView(Fragment.java:2353)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:995)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1171)
at android.app.BackStackRecord.run(BackStackRecord.java:816)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1578)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:483)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
正如其中一个人建议的那样,我在响应中做了我想做的事情,
if(response.isSuccessful()) {
extractCreate = parseExtractCreateDetails(jsonData);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// Log.d("<=====>", "check");
// Log.d(TAG, "Is this even working?");
// Log.d("The class has been ok",extractCreate.getCreateR().getAccount_id().toString());
// Log.d("Another check", extractCreate.getStopsR()[1].getAddress());
Parcelable[] parcelable = extractCreate.getStopsR();
commodities = Arrays.copyOf(parcelable, parcelable.length, Stops[].class);
//Log.d("Commodities size check", String.valueOf(commodities.length));
StopsAdapter adapter = new StopsAdapter(extractCreate.getStopsR());
mRecyclerView.setAdapter(adapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity()); // sketchy on this part
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
Log.d(TAG, "This is being called from the onCreate method");
//();
}
});
}
//getStops(jsonData);
}catch(IOException e) {
}catch (JSONException e){
}
}
现在,视图的内容会相应更新,就像我在我的适配器中指定的那样(意味着适配器正在按照我的意图运行),但是在回调完成后才会添加适配器打印出来的堆栈跟踪
11-23 12:05:40.628 7270-7270/com.example.testC.demotrackertree E/RecyclerView: No adapter attached; skipping layout
不仅如此,而且在旋转屏幕时不会保留saveInstanceState。
答案 0 :(得分:2)
执行AsyncTask时,操作在后台线程上与UI线程同时运行。 Log语句就在execute语句之后,所以当执行Log语句时,AsyncTask还没有在变量中加载信息。