首页 > 解决方案 > 在凌空响应之前片段更改时应用程序崩溃

问题描述

我有底部导航视图,其中有 3 个名为 Home、Notifications 和 Account 的片段。在主页片段中,我正在发出使用用户最后已知位置的凌空发布请求,并在此基础上从服务器获取响应。我想知道:

  1. 当我在凌空响应之前在片段之间切换时,我的应用程序崩溃了,而当我在响应完成后切换时,没有应用程序崩溃。

  2. 活动第一次启动时没有显示来自服务器的响应。它显示我何时在片段之间切换并再次返回。

它显示错误日志:

 java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
    at android.widget.Toast.<init>(Toast.java:138)
    at android.widget.Toast.makeText(Toast.java:385)
    at tiffino.app.com.Home$1.onResponse(Home.java:245)
    at tiffino.app.com.Home$1.onResponse(Home.java:240)
    at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
    at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
    at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
    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:6776)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)

主页.java

public class Home extends Fragment implements GoogleApiClient.OnConnectionFailedListener,
    GoogleApiClient.ConnectionCallbacks,
    com.google.android.gms.location.LocationListener {

    TextView fragText;
    GoogleApiClient mGoogleApiClient;
    LocationRequest mLocationRequest;
    Location mLocation;
    RequestQueue requestQueue;
    StringRequest stringRequest;
    public static final String TAG = "MyTag";
    private static final String URL = "https://google.com";

    public Home() { }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        fragText = view.findViewById(R.id.fragText);

        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

        return view;
    }


    @Override
    public void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    public void onStop() {
        super.onStop();
        if(mGoogleApiClient.isConnected() && requestQueue != null){
            mGoogleApiClient.disconnect();
            requestQueue.cancelAll(TAG);
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if(mLocation != null) {
            String str1 = hereLocation(mLocation.getLatitude(),mLocation.getLongitude());
            fragText.setText(str1);
            sendLocation(str1);
        }
    }

    @Override
    public void onConnectionSuspended(int i) { }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { }

    private void sendLocation(final String str1) {
        requestQueue = Volley.newRequestQueue(getContext());
        stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Toast.makeText(getActivity(),""+response,Toast.LENGTH_SHORT).show();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) { }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String,String> map = new HashMap<>();
                map.put("name",str1);
                return map;
            }   
        };
        stringRequest.setTag(TAG);
        requestQueue.add(stringRequest);
    }

    private String hereLocation(double lat, double lon) {
        String city = "";
        Geocoder geo = new Geocoder(getContext(), Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = geo.getFromLocation(lat,lon,10);
            if(addresses.size()>0) {
                for (Address adr: addresses) {
                    if(adr.getLocality()!=null && adr.getLocality().length()>0) {
                        city = adr.getLocality();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return city;
    }
}

请让我知道为什么应用程序崩溃。

谢谢

标签: androidandroid-volley

解决方案


问题可能出在 onRespones 中的 getActivity() 上。由于您现在位于另一个片段中,因此片段现在未附加到 getActivity。

你可以做:

if(isAdded()) { 
   Toast.makeText(getActivity(),""+response,Toast.LENGTH_SHORT).show();
}

推荐阅读