Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/228.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android onResponse改装的返回变量_Android_Retrofit_Response - Fatal编程技术网

Android onResponse改装的返回变量

Android onResponse改装的返回变量,android,retrofit,response,Android,Retrofit,Response,我对Web服务器进行API调用,并在方法onResponse中获取ID 现在我想保存这个ID,并在doLogin方法的返回中返回这个ID。如何在return语句中获取该变量ID 这是我的代码: public class LoginController { public static String doLogin(String loginMail, String loginPassword) { //Logging Retrofit final Http

我对Web服务器进行API调用,并在方法onResponse中获取ID

现在我想保存这个ID,并在doLogin方法的返回中返回这个ID。如何在return语句中获取该变量ID

这是我的代码:

public class LoginController {

    public static String doLogin(String loginMail, String loginPassword) {

        //Logging Retrofit
        final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("###URLTOAPICALL###")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        APIService service = retrofit.create(APIService.class);
        Call<JsonElement> call = service.doLogin(loginMail, loginPassword);

        call.enqueue(new Callback<JsonElement>() {
            @Override
            public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {

                if (response != null) {
                    JSONObject obj = null;

                    try {
                        obj = new JSONObject(response.body().toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    JSONObject setup = null;
                    try {
                        setup = obj.getJSONObject("setup");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    if(setup != null) {
                        try {
                            Setup stp = new Setup();
                            stp.setUserId(setup.getInt("id"));

                            //I WANT HERE TO SAVE MY ID

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                }
            }

            @Override
            public void onFailure(Call<JsonElement> call, Throwable t) {
                Log.v("ERROR", t+"");
            }


        });

        return "I WANT RETURN THAT ID HERE";
    }
}
公共类登录控制器{
公共静态字符串doLogin(字符串loginMail、字符串loginPassword){
//测井改造
最终HttpLoggingInterceptor拦截器=新HttpLoggingInterceptor();
拦截器.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient客户端=新建OkHttpClient.Builder().addInterceptor(拦截器).build();
改装改装=新改装.Builder()
.baseUrl(“####URLTOAPICALL###”)
.客户(客户)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService=reformation.create(APIService.class);
Call Call=service.doLogin(loginMail,loginPassword);
call.enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
if(响应!=null){
JSONObject对象j=null;
试一试{
obj=新的JSONObject(response.body().toString());
}捕获(JSONException e){
e、 printStackTrace();
}
JSONObject setup=null;
试一试{
setup=obj.getJSONObject(“setup”);
}捕获(JSONException e){
e、 printStackTrace();
}
如果(设置!=null){
试一试{
Setup stp=新设置();
stp.setUserId(setup.getInt(“id”);
//我想在这里保存我的身份证
}捕获(JSONException e){
e、 printStackTrace();
}
}
}
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
Log.v(“错误”,t+);
}
});
return“我想在这里返回该ID”;
}
}

因为改型是异步的,所以不要从方法返回,而是使用接口回调

public class LoginController {

    public interface LoginCallbacks{
        void onLogin(String id);
        void onLoginFailed(Throwable error);
    }

    public static void doLogin(String loginMail, String loginPassword, final LoginCallbacks loginCallbacks) {

        //Logging Retrofit
        final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("###URLTOAPICALL###")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        APIService service = retrofit.create(APIService.class);
        Call<JsonElement> call = service.doLogin(loginMail, loginPassword);

        call.enqueue(new Callback<JsonElement>() {
            @Override
            public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {

                if (response != null) {
                    JSONObject obj = null;

                    try {
                        obj = new JSONObject(response.body().toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    JSONObject setup = null;
                    try {
                        setup = obj.getJSONObject("setup");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    if(setup != null) {
                        try {
                            Setup stp = new Setup();
                            stp.setUserId(setup.getInt("id"));

                            //I WANT HERE TO SAVE MY ID
                            if (loginCallbacks != null)
                                loginCallbacks.onLogin(setup.getInt("id"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                }
            }

            @Override
            public void onFailure(Call<JsonElement> call, Throwable t) {
                Log.v("ERROR", t+"");
                if (loginCallbacks != null)
                    loginCallbacks.onLoginFailed(t);
            }


        });
    }
}

无法执行此操作,因为您请求的调用是异步的。如果要在同一线程中运行它,必须避免使用enqueue并使用execute()。请记住,您需要创建一个线程,因为您不能在同一个线程上使用网络操作

您可以使用Observable解决它,或者像在本例中一样使用execute(未测试)

注意,如果你想更新你的用户界面,你需要使用

runOnUiThread();
虽然call.execute()函数是同步的,但它会触发Android 4.0或更高版本上的应用程序崩溃,您将获得
NetworkOnMainThreadException
。必须执行异步请求,将全局变量初始化为可运行线程。在类名处添加Runnable实现。getDataFunction()将如下所示:

public void getData(){
    Call<JsonElement> call = service.doLogin(loginMail, loginPassword);

    call.enqueue(new Callback<JsonElement>() {
        @Override
        public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {

            if (response.isSuccessful() && response != null) {
                jsonObject = response.body().toString();//initialize your global variable
            }
        }

        @Override
        public void onFailure(Call<JsonElement> call, Throwable t) {
            Log.v("ERROR", t+"");
        }
    });

}

@Override
pulic void run(){
    getDataFunction();
    //here you can use your initialized variable
}

这就是它解决我的类似问题的方法。

您可以在改造调用的onResponse方法中使用setter方法。 举个例子,我有一个全局变量来保存从Google maps distance matrix API获得的两点之间的距离:

String final_distance;
这是我的改装电话:

call.enqueue(new Callback<JsonObject>() {
        
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            // TODO Auto-generated method stub
            JsonObject object = response.body();
            String distance = object.get("rows").getAsJsonArray().get(0).getAsJsonObject().get("elements").getAsJsonArray().
                    get(0).getAsJsonObject().get("distance").getAsJsonObject().get("value").getAsString();
            //The setter method to change the global variable
            setDistance(distance);

        }
        
        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            // TODO Auto-generated method stub
            
        }
    });

由于改型onResponse方法是异步的,因此在使用它之前,您需要始终首先检查最终的_距离是否为null

declare
int-idid=setup.getInt(“id”)。现在,
return id
在结尾,简短的回答是您不能……
onResponse
是异步回调。此注释根本没有帮助。onResponse是异步的,但response不是(如果您调用execute而不是enqueue)。创建回调以避免使用已创建的方法(execute())从来都不是一个好主意。嗨@EmanuelSeibold,Pratik Popat answer对我很有用,我可以问一下为什么你说这不是获得响应的好方法吗?你应该在排队中使用你的登录信息并在主/ui线程中运行来更新你的ui,或者使用ui线程中已经存在的线程并执行。创建“onLogin”和“onLoginFailed”是多余的,因为改装有onResponse和onFailure。我尝试了你的解决方案,但我不能写一份关于该职位的回报…?陛下。返回响应。body();最后返回null;或者你想返回的任何东西,以防失败。
public void getData(){
    Call<JsonElement> call = service.doLogin(loginMail, loginPassword);

    call.enqueue(new Callback<JsonElement>() {
        @Override
        public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {

            if (response.isSuccessful() && response != null) {
                jsonObject = response.body().toString();//initialize your global variable
            }
        }

        @Override
        public void onFailure(Call<JsonElement> call, Throwable t) {
            Log.v("ERROR", t+"");
        }
    });

}

@Override
pulic void run(){
    getDataFunction();
    //here you can use your initialized variable
}
Thread thread = new Thread(this);
thread.start();
String final_distance;
call.enqueue(new Callback<JsonObject>() {
        
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            // TODO Auto-generated method stub
            JsonObject object = response.body();
            String distance = object.get("rows").getAsJsonArray().get(0).getAsJsonObject().get("elements").getAsJsonArray().
                    get(0).getAsJsonObject().get("distance").getAsJsonObject().get("value").getAsString();
            //The setter method to change the global variable
            setDistance(distance);

        }
        
        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            // TODO Auto-generated method stub
            
        }
    });
private static void setDistance(String distance) {
    final_distance = distance;
}