Android 在onresponse方法内调用函数

Android 在onresponse方法内调用函数,android,Android,我正在开发一款Android应用程序 这是片段中的一个函数: private void guardar_paciente() { String tag_string_req = "req_login"; StringRequest strReq = new StringRequest(Request.Method.POST, URL_CHECK, new Response.Listener&

我正在开发一款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);


    }
private void guardar_paciente(){
String tag\u String\u req=“req\u login”;
StringRequest strReq=新的StringRequest(Request.Method.POST,
URL\u检查,新响应。侦听器(){
@凌驾
公共void onResponse(字符串响应){
试一试{
JSONObject jObj=新的JSONObject(响应);
布尔错误=jObj.getBoolean(“错误”);
字符串id_paciente=jObj.getString(“id”);
字符串id_nhc=jObj.getString(“nhc”);
如果(!错误){
editor2.putString(“id\u paciente”,id\u paciente);
editor2.putString(“nhc”,id\u nhc);
editor2.apply();
}否则{
//登录时出错。获取错误消息
//String errorMsg=jObj.getString(“error_msg”);
}
}捕获(JSONException e){
//JSON错误
e、 printStackTrace();
//Toast.makeText(getActivity(),“Json错误:”+e.getMessage(),Toast.LENGTH\u LONG.show();
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Toast.makeText(getActivity(),
error.getMessage(),Toast.LENGTH_LONG).show();
}
}) {
@凌驾
受保护的映射getParams(){
//将参数发布到登录url
Map params=新的HashMap();
参数put(“nombre_completo”,nombre_completo);
参数put(“apellidos”,apellidos);
参数put(“tel1”,tel1);
参数put(“tel2”,tel2);
参数put(“电子邮件”,电子邮件);
参数put(“profession”,profession);
参数put(“sexo”,sexo);
参数put(“fecha_nacimiento”,fecha_nacimiento);
参数put(“edad”,edad);
参数put(“比索”,比索);
参数put(“塔拉”,塔拉);
参数put(“IMC”,IMC);
参数出售(“同意书”、“1”);
参数put(“临床医生/病人”,临床医生/实际);
参数put(“imagen_paciente”,imagen_paciente);
参数put(“firma_paciente”,numero+”.JPG);
参数put(“DNI”,DNI);
参数put(“direccion”,direccion);
参数put(“raza”,raza);
返回参数;
}
};
//将请求添加到请求队列
AppController.getInstance().addToRequestQueue(streq,标记字符串请求);
}
我需要的是在guardar_paciente()完成其所有方法并且可以安全地更改UI之后执行另一个函数,
abrirPaciente()

我尝试在
editor2.apply()之后调用abrirPaciente()
;,但应用程序崩溃。

利用回调:

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中,在触发回调之前,您还可以将其更改为主线程。您可以找到类似的帮助

您可以在onResponse中完成所需的操作后立即触发回调,然后您就知道它是正确的done@a_local_nobody,我将尝试实施您的建议,谢谢。没问题,您肯定可以使用回调在那里触发另一种方法,但是我不确定它是否能解决您在UI上安全调用的问题,您可以使用runnable或其他机制切换到主线程。我的java非常陈旧,但我可以尝试为您举个例子作为答案,不管您将接口放在何处