1

我正在开发一个 Android 应用程序。

这是片段内的一个函数:

private void guardar_paciente() {
        
        String tag_string_req = "req_login";
 
        StringRequest strReq = new StringRequest(Request.Method.POST,
                URL_CHECK, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                
                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    String id_paciente = jObj.getString("id");
                    String id_nhc = jObj.getString("nhc");
                    
                    if (!error) {
                  

                        editor2.putString("id_paciente", id_paciente);
                        editor2.putString("nhc", id_nhc);
                        editor2.apply();
                        
                    } else {
                        // Error in login. Get the error message
                      //  String errorMsg = jObj.getString("error_msg");

                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                 //   Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(getActivity(),
                        error.getMessage(), Toast.LENGTH_LONG).show();

            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("nombre_completo", nombre_completo);
                params.put("apellidos", apellidos);
                params.put("tel1", tel1);
                params.put("tel2", tel2);
                params.put("email", email);
                params.put("profesion", profesion);
                params.put("sexo", sexo);
                params.put("fecha_nacimiento", fecha_nacimiento);
                params.put("edad", edad);
                params.put("peso", peso);
                params.put("talla", talla);
                params.put("IMC", IMC);
                params.put("consentimiento", "1");
                params.put("clinica_paciente", clinica_actual);
                params.put("imagen_paciente", imagen_paciente);
                params.put("firma_paciente", numero+".JPG");
                params.put("DNI", DNI);
                params.put("direccion", direccion);
                params.put("raza", raza);


                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);


    }

我需要的是abrirPaciente()在guardar_paciente() 完成所有方法之后执行另一个函数,并且可以安全地更改UI。我曾尝试在 ; 之后调用 abrirPaciente() editor2.apply(),但应用程序崩溃了。

4

1 回答 1

1

利用回调:

public class foo {


    interface ExampleInterface {

        void finishedServiceCallNoErrors();
        void finishedServiceCallWithError(String error);
    }

     void guardar_paciente(ExampleInterface exampleInterface) {

        ...

        @Override
        public void onResponse(String response) {
            ....
            
            //there was no error
            exampleInterface.finishedServiceCallNoErrors();
            
            //there was an error
            exampleInterface.finishedServiceCallWithError("your error message here");
            
            ....
            
            
        }
        ...
        
    }
}

以及如何使用它的示例:

public class bar implements foo.ExampleInterface {

//simple example of how you'd use this
    private void callingIt() {
        new foo().guardar_paciente(this); //here, we can pass `this` because our class is implementing the interface
    }

//these now get returned to the class making use of the service call, so you can easily handle things here, instead of worrying about the logic in your service call response
    @Override
    public void finishedServiceCallNoErrors() {
        //TODO("Handle the response with no error");
        //your call completed and everything was fine, now do something else
    }

    @Override
    public void finishedServiceCallWithError(String error) {
        // TODO("Handle the response with an error")
        // there was an error, handle it here
    }
}

我不确定如果从后台线程触发此回调模式是否可以安全使用,因此您需要在回调内部切换线程,因此在内部finishedServiceCallNoErrors和内部finishedServiceCallWithError您可能需要像 Runnable,所以你可以利用主线程,或者在服务调用的 onResponse 内部,在触发回调之前,你也可以在那里切换到主线程。你可以在这里找到类似的帮助

于 2020-10-27T19:54:11.093 回答