gpt4 book ai didi

java - 改造 Android 从 REST API 获取日期无法正常工作

转载 作者:太空宇宙 更新时间:2023-11-04 09:41:46 24 4
gpt4 key购买 nike

我在 spring 上有一个 REST API。我可以从 url: localhost:8080/all 获取数据我创建了类:

public class DataAPI {
private static final String CLASS_TAG = "DataAPI";
RestAdapter retrofit;
MyWebService myWebService;
private List<Teacher> list;


public DataAPI() {
String url = "http://10.101.12.31:8080/";
retrofit = new RestAdapter.Builder()
.setEndpoint(url)
.build();
myWebService = retrofit.create(MyWebService.class);
}

@RequiresApi(api = Build.VERSION_CODES.N)
public List<Department> getAllDepartments() {
try {
myWebService.getAllTeacher(new Callback<List<Teacher>>() {

@Override
public void success(List<Teacher> data, Response response) {
Log.d(CLASS_TAG, data.toString());
// data.stream().forEach(System.out::println);
list= data;

}

@Override
public void failure(RetrofitError error) {

}
});

} catch (Exception e) {
Log.d(CLASS_TAG, e.toString());
}

return this.departmentList;
}

MyWebService:

public interface MyWebService {
@GET("/all")
void getAllDepartments(Callback<List<Teacher>> pResponse);

主要 Activity :

public class MainActivity extends AppCompatActivity {
private static final String CLASS_TAG = "MainActivity";

TextView textView;
DataAPI dataAPI;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataAPI = new DataAPI();
setContentView(R.layout.activity_main);

textView = findViewById(R.id.textView);


findViewById(R.id.button_get).setOnClickListener(new View.OnClickListener() {


@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onClick(View v) {
textView.setText("");


List<Teacher> list = dataAPI.getAllDepartments();
System.out.println(list == null);
if (list != null){
list.stream().forEach(x -> textView.setText(textView.getText() + "\n" + x.toString()));
}
}
});

我的应用程序上有一个按钮。当我第一次单击它时,没有任何变化,但是当我第二次单击时,数据正在加载。当我将 DataAPI 中的所有代码粘贴到 onClick 方法时,数据将在第一次加载。

最佳答案

使用接口(interface)将数据获取到被调用的 Activity ,如下所示,先写接口(interface),

public class APICallBack {

public interface GetResponseCallback{
void onSuccess(yourresponsetype response);
void onFailed();
}
}

在您的 MainActivity 中实现此接口(interface)。你打电话时 dataAPI.getAllDepartments();

将接口(interface)传递给您的 DataAPI 类。

 public List<Department> getAllDepartments(final APICallback.GetResponseCallback callback){

@Override
public void success(List<Teacher> data, Response response) {
Log.d(CLASS_TAG, data.toString());
// data.stream().forEach(System.out::println);
list= data;
callback.onSuccess(response);
}

}

关于java - 改造 Android 从 REST API 获取日期无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55901927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com