凌空碎裂

时间:2019-07-04 04:26:26

标签: android android-fragments android-volley

我正在使用凌空从服务器获取数据。当我在活动中使用它时,一切正常,我得到了所需的输出,但是当我在片段中使用它时,应用程序崩溃了

我已经使用getActivity()作为片段中的上下文,但是它仍然崩溃,并且日志中没有显示错误

GetPinFragment:

    public class GetPinFragment extends Fragment implements VolleyListener {

        EditText et1_pin, et2_pin, et3_pin, et4_pin;
        TextView tv_forgotPasscode;
        Button btn_next;

        public GetPinFragment() {
            // Required empty public constructor
        }


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

            et1_pin = (EditText)view.findViewById(R.id.et1_pin);
            et2_pin = (EditText)view.findViewById(R.id.et2_pin);
            et3_pin = (EditText)view.findViewById(R.id.et3_pin);
            et4_pin = (EditText)view.findViewById(R.id.et4_pin);

            tv_forgotPasscode = (TextView)view.findViewById(R.id.tv_forgotPasscode);

            btn_next = (Button)view.findViewById(R.id.btn_next);

            tv_forgotPasscode.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view)
                {
                    Fragment forgotPasscodeFragment = new ForgotPasscodeFragment();

                    getFragmentManager().beginTransaction()
                            .replace(R.id.fragment_container, forgotPasscodeFragment)
                            .addToBackStack(null).commit();
                }
            });

            btn_next.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view)
                {
                    String pin = et1_pin.getText().toString().trim() + et2_pin.getText().toString().trim() +
                                 et3_pin.getText().toString().trim() + et4_pin.getText().toString().trim();

                    if(pin.length() == 4)
                    {
                        ServerManager serverManager = new ServerManager(getActivity());

                        Map<String, String> postParams = new HashMap<String, String>();
                        postParams.put("Email", "driver_18@gmcars.co");
                        postParams.put("Password", "Yahoo@123");

                        serverManager.jsonParse(Constants.LOGIN, postParams);
                    }
                }
            });

            return view;
        }
@Override
    public void loginRequestFinished(JSONObject response) throws JSONException {
        if(response.getJSONObject("DriverData").getString("ResponseCode").equals("0000"))
        {
            Toast.makeText(getActivity(),
                    Global.loginResponse.getDriverData().getDriverProfile().getName() + "\n"
                            + Global.loginResponse.getDriverData().getDriverProfile().getUserName() + "\n"
                            + Global.loginResponse.getDriverData().getDriverProfile().getPostcode() + "\n"
                            + Global.loginResponse.getDriverData().getDriverProfile().getMobileNumber() + "\n"
                            + Global.loginResponse.getDriverData().getDriverProfile().getCarNo() + "\n"
                            + Global.loginResponse.getDriverData().getDriverProfile().getBadgeno() + "\n"
                            + Global.loginResponse.getDriverData().getDriverProfile().getApplicationUserId() + "\n"
                            + Global.loginResponse.getDriverData().getDriverProfile().getAddress() + "\n"
                            + Global.loginResponse.getDriverData().getMessage() + "\n"
                            + Global.loginResponse.getDriverData().getResponseCode() + "\n"
                    ,Toast.LENGTH_LONG
            ).show();

            return;
        }

        if (response.getJSONObject("DriverData").getString("ResponseCode").equals("0001"))
        {
            Toast.makeText(getActivity(), response.getJSONObject("DriverData").getString("Message"), Toast.LENGTH_SHORT).show();
            return;
        }
    }

ServerManager:

public class ServerManager {

    Context ctx;

    public ServerManager(Context ctx)
    {
        this.ctx = ctx;
    }

    public void jsonParse(String siteURL, Map<String, String> postParams)
    {

        SSLVerification sslVerification = new SSLVerification(ctx);

        RequestQueue requestQueue = Volley.newRequestQueue(ctx, sslVerification.Certificate());

        String url = Constants.BASE_URL + siteURL;

        /******* Causing app to crash ********/
        final VolleyListener volleyListener = (VolleyListener) ctx;

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
                url, new JSONObject(postParams),
                new Response.Listener<JSONObject>()
                {
                    @Override
                    public void onResponse(JSONObject response)
                    {
                        try {
                            if(response != null)
                            {
                                if (response.getJSONObject("DriverData").getString("ResponseCode").equals("0000"))
                                {
                                    Gson gson = new Gson();
                                    LoginResponse loginResponse = gson.fromJson(response.toString(), LoginResponse.class);
                                    Global.loginResponse = loginResponse;

                                    /* Calling VolleyListener interface method and returning responseCode */
                                    volleyListener.loginRequestFinished(response);
                                } else {

                                    /* Calling VolleyListener interface method and returning responseCode */
                                    volleyListener.loginRequestFinished(response);

                                    Toast.makeText(ctx, response.getJSONObject("DriverData").getString("Message"), Toast.LENGTH_SHORT).show();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error)
            {
                Toast.makeText(ctx, error.getMessage(), Toast.LENGTH_LONG).show();
            }
        }) {

            /* Passing some request headers */
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json; charset=utf-8");
                return headers;
            }
        };

        // Adding request to request queue
        requestQueue.add(jsonObjReq);
    }
}

VolleyListener:

public interface VolleyListener {


    public void loginRequestFinished(JSONObject response) throws JSONException;
}

日志:

07-04 09:32:23.129 3086-13677/com.example.admin.gmcars V/FA: Recording user engagement, ms: 1441577
07-04 09:32:23.134 3086-13677/com.example.admin.gmcars V/FA: Connecting to remote service
07-04 09:32:23.239 3086-13677/com.example.admin.gmcars V/FA: Activity paused, time: 150707064
07-04 09:32:23.279 3086-13677/com.example.admin.gmcars D/FA: Logging event (FE): user_engagement(_e), Bundle[{firebase_event_origin(_o)=auto, firebase_screen_id(_si)=3960614141377066253, engagement_time_msec(_et)=1441577, firebase_screen_class(_sc)=LoginActivity}]
07-04 09:32:23.279 3086-3086/com.example.admin.gmcars V/FA: onActivityCreated
07-04 09:32:23.369 3086-13677/com.example.admin.gmcars V/FA: Connection attempt already in progress
07-04 09:32:23.399 3086-13677/com.example.admin.gmcars V/FA: Connection attempt already in progress
07-04 09:32:23.399 3086-13677/com.example.admin.gmcars V/FA: Activity resumed, time: 150707339
07-04 09:32:23.404 3086-13677/com.example.admin.gmcars D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_previous_class(_pc)=LoginActivity, firebase_event_origin(_o)=auto, firebase_screen_id(_si)=-8935344662706588953, firebase_screen_class(_sc)=FragmentLoaderActivity, firebase_previous_id(_pi)=3960614141377066253}]
07-04 09:32:23.444 3086-13677/com.example.admin.gmcars V/FA: Connection attempt already in progress
07-04 09:32:23.444 3086-13677/com.example.admin.gmcars D/FA: Connected to remote service
07-04 09:32:23.444 3086-13677/com.example.admin.gmcars V/FA: Processing queued up service tasks: 4
07-04 09:32:23.499 9287-13679/? V/FA-SVC: Logging event: origin=auto,name=user_engagement(_e),params=Bundle[{firebase_event_origin(_o)=auto, firebase_screen_id(_si)=3960614141377066253, engagement_time_msec(_et)=1441577, firebase_screen_class(_sc)=LoginActivity}]
07-04 09:32:23.564 9287-13679/? V/FA-SVC: Saving event, name, data size: user_engagement(_e), 69
07-04 09:32:23.574 9287-13679/? V/FA-SVC: Event recorded: Event{appId='com.example.admin.gmcars', name='user_engagement(_e)', params=Bundle[{firebase_event_origin(_o)=auto, firebase_screen_id(_si)=3960614141377066253, firebase_screen_class(_sc)=LoginActivity, engagement_time_msec(_et)=1441577}]}
07-04 09:32:23.584 9287-13679/? V/FA-SVC: Upload scheduled in approximately ms: 1689228
07-04 09:32:23.604 9287-13679/? V/FA-SVC: Scheduling upload with GcmTaskService
07-04 09:32:23.604 9287-13679/? V/FA-SVC: Scheduling task with Gcm. time: 1689228
07-04 09:32:23.614 9287-13679/? V/FA-SVC: Background event processing time, ms: 119
07-04 09:32:23.664 9287-13679/? V/FA-SVC: Logging event: origin=auto,name=screen_view(_vs),params=Bundle[{firebase_previous_class(_pc)=LoginActivity, firebase_event_origin(_o)=auto, firebase_screen_id(_si)=-8935344662706588953, firebase_screen_class(_sc)=FragmentLoaderActivity, firebase_previous_id(_pi)=3960614141377066253}]
07-04 09:32:23.679 9287-13679/? V/FA-SVC: Saving event, name, data size: screen_view(_vs), 107
07-04 09:32:23.679 9287-13679/? V/FA-SVC: Event recorded: Event{appId='com.example.admin.gmcars', name='screen_view(_vs)', params=Bundle[{firebase_previous_class(_pc)=LoginActivity, firebase_event_origin(_o)=auto, firebase_screen_id(_si)=-8935344662706588953, firebase_screen_class(_sc)=FragmentLoaderActivity, firebase_previous_id(_pi)=3960614141377066253}]}
07-04 09:32:23.684 9287-13679/? V/FA-SVC: Upload scheduled in approximately ms: 1689129
07-04 09:32:23.689 9287-13679/? V/FA-SVC: Scheduling upload with GcmTaskService
07-04 09:32:23.689 9287-13679/? V/FA-SVC: Scheduling task with Gcm. time: 1689129
07-04 09:32:23.704 9287-13679/? V/FA-SVC: Background event processing time, ms: 42
07-04 09:32:27.579 3086-3086/com.example.admin.gmcars W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
07-04 09:32:28.524 3086-13677/com.example.admin.gmcars V/FA: Inactivity, disconnecting from the service

我希望输出的内容与我参加活动的情况相同

更新:

我正在使用导致应用程序崩溃的界面,我已经更新了代码。 如何从片段中使用它?

2 个答案:

答案 0 :(得分:0)

您正在片段内部使用getFragmentManager()

getFragmentManager().beginTransaction()
                    .replace(R.id.fragment_container, forgotPasscodeFragment)
                    .addToBackStack(null).commit();

替换为该代码

getChildFragmentManager().beginTransaction()
                    .replace(R.id.fragment_container, forgotPasscodeFragment)
                    .addToBackStack(null).commit();

答案 1 :(得分:0)

我解决了我的问题。问题不在于代码,而在于我的方法。我在片段中使用接口回调,这导致应用程序崩溃。当我在活动中使用回调方法时,一切正常。