Я использую rxjava и модификацию для получения данных с сервера (localhost для тестирования), а затем показываю их в представлении переработчика. У меня есть PHP-скрипт, который я тестировал почтальон, и он работает нормально, но я не смог получить этот ответ, используя rxjava. Код, который я написал, следующий:
php script getPosts.php
<?php
require_once "DbOperations.php";
$response = array();
$response["login"] = array();
$db = new DbOperations();
$user = $db->getPosts();
$response["success"] = "0";
array_push($response["login"],$user);
echo json_encode($response);
Вывод это дает как
{"login":[[{"q_contents":"abc","username":"abc"}]],"success":"0"}
ApiClient.class
public class ApiClient {
public static final String BASE_URL = "http://192.168.43.133:8080/ProblemSolver/includes/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
return retrofit;
}
}
In APiService Интерфейс
@GET("getPosts.php")
Observable<Post> getPost();
Модель класса Post.class
public class Post {
private String q_contents;
private String username;
public Post() {
}
public Post(String q_contents, String username) {
this.q_contents = q_contents;
this.username = username;
}
public String getQ_contents() {
return q_contents;
}
public void setQ_contents(String q_contents) {
this.q_contents = q_contents;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
RxJava
private void loadRecentPosts() {
Retrofit retrofit = ApiClient.getClient();
mService = retrofit.create(APIService.class);
mService.getPost()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Post>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Post post) {
Toast.makeText(getContext(),""+post.getUsername(),Toast.LENGTH_LONG).show();
}
@Override
public void onError(Throwable e) {
Log.d("", "onError: "+e.getMessage());
}
@Override
public void onComplete() {
Toast.makeText(getContext(),"complete",Toast.LENGTH_LONG).show();
}
});
}
Я получаю пустое сообщение в тосте, которое я написал в onNext ().