Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/179.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
Java android studio中的同步连接到API不工作,但异步工作_Java_Android_Api_Retrofit - Fatal编程技术网

Java android studio中的同步连接到API不工作,但异步工作

Java android studio中的同步连接到API不工作,但异步工作,java,android,api,retrofit,Java,Android,Api,Retrofit,我有一个api,它可以在异步模式下工作,但不能在同步模式下工作。 我有一门ApiUtils课程: public class ApiUtils { private ApiUtils() {} public static final String BASE_URL = "http://jsonplaceholder.typicode.com/"; public static APIServices getAPIService() { return Retr

我有一个api,它可以在异步模式下工作,但不能在同步模式下工作。 我有一门ApiUtils课程:

public class ApiUtils {
    private ApiUtils() {}

    public static final String BASE_URL = "http://jsonplaceholder.typicode.com/";
    public static APIServices getAPIService() {

        return RetrofitClient.getClient(BASE_URL).create(APIServices.class);
    }
}
并具有以下客户端类:

public class RetrofitClient {
    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {

        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
我的Post ViewModel类是:

public class Post {
    @SerializedName("title")
    @Expose
    private String title;
    @SerializedName("body")
    @Expose
    private String body;
    @SerializedName("userId")
    @Expose
    private Integer userId;
    @SerializedName("id")
    @Expose
    private Integer id;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Post{" +
                "title='" + title + '\'' +
                ", body='" + body + '\'' +
                ", userId=" + userId +
                ", id=" + id +
                '}';
    }
}
我的gradle相关性是:

implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.google.code.gson:gson:2.8.4'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
我在android清单中授予了互联网权限。 我为该api编写了两个异步调用和同步调用函数。但问题是我的异步方法有效,但我的同步方法无效:

//Not work
    private void SyncCall() {
         Call<Post> ins= mAPIServices.savePost("test title", "test body", 12);
        try {
            String s =ins.execute().body().toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //Worked
    private void AsyncCall() {
        mAPIServices.savePost("test title", "test body", 12)
                .enqueue(new Callback<Post>() {
                    @Override
                    public void onResponse(Call<Post> call, Response<Post> response) {
                        String s = response.body().toString();
                    }

                    @Override
                    public void onFailure(Call<Post> call, Throwable t) {
                    }
                });
    }
//不工作
私有void SyncCall(){
Call-ins=mAPIServices.savePost(“测试标题”、“测试正文”,12);
试一试{
字符串s=ins.execute().body().toString();
}捕获(IOE异常){
e、 printStackTrace();
}
}
//工作
私有void异步调用(){
mAPIServices.savePost(“测试标题”、“测试正文”,12)
.enqueue(新的回调函数(){
@凌驾
公共void onResponse(调用、响应){
字符串s=response.body().toString();
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
}
});
}
我可以找到我的解决方案。 我们必须创建一个新类,如下所示:

public class InnerClass extends AsyncTask {
    @Override
    protected Post doInBackground(Object[] objects) {
        APIServices mAPIServices = ApiUtils.getAPIService();
        Call<Post> ins= mAPIServices.savePost("test title", "test body", 12);
        Post ret=new Post();
        try {
            ret =ins.execute().body();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }
}

错误是什么?你说同步方法不起作用是什么意思?另外,为什么不使用async方法呢?我想从api方法中获取返回值,将其传递给上层(从presenter到view)。我想同步运行它。在“String s=ins.execute().body().toString();”行插入断点时,我的程序关闭了,甚至捕获块不是firedYou可以使用wait或postback从异步方法捕获返回值。把线分开,看清楚发生了什么。字符串s=ins.execute();新行字符串y=s.body();新行字符串z=y.toString();。。。。然后逐行检查每一行,并在对象每次更改时进行评估。我这样做了,但在ins.execute()行中,程序崩溃了,请帮助我创建一个像我这样的项目,如果可以的话,谢谢你,可能会有很多重复的
AsyncTask s=new InnerClass().execute();
        try {
            Post a=(Post)s.get();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }