Answer the question
In order to leave comments, you need to log in
How to pass data to main thread from CallBack okhttp Android?
Good afternoon!
I'm working on an Android application to learn how to work with JSON.
As an API, I use this one - jsonplaceholder.typicode.com .
So, I need the body of the post and the number of comments to be displayed in the RecyclerView list item, in fact, here is the code:
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
//Модель данных для постов
private PlaceHolderPost placeHolderPost;
//Список экземпляров постов
List<PlaceHolderPost> posts = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppTheme);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Получаем RecyclerView
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv);
//Получаем данные о постах
String apiKeyPosts = "posts";
int idPost = 1;
String placeholderPostsURL = "https://jsonplaceholder.typicode.com/" + apiKeyPosts + "/";
//Получаем данные о комментах
String apiKeyComments = "comments";
String placeholderCommentsURL = "https://jsonplaceholder.typicode.com/" + apiKeyComments;
/*Проверка на наличие подключения к интернету*/
if (isNetworkAvailable()) {
OkHttpClient client = new OkHttpClient();
Request requestPost = new Request.Builder()
.url(placeholderPostsURL)
.build();
Request requestComments = new Request.Builder()
.url(placeholderCommentsURL)
.build();
Call call = client.newCall(requestPost);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
final String jsonData = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
if (response.isSuccessful()) {
Log.v(TAG, jsonData);
posts = getCurrendDetails(jsonData);
Log.e("placeholderPost", posts.size() + " - размер");
PostDataAdapter adapter = new PostDataAdapter(MainActivity.this, posts);
// устанавливаем для списка адаптер
recyclerView.setAdapter(adapter);
} else {
alertUserAboutError();
}
} catch (JSONException e) {
Log.e(TAG, "JSON Exception caught: ", e);
}
}
});
}
});
//Log.e("placeholderPost", posts.size() + " - размер");
//PostDataAdapter adapter = new PostDataAdapter(MainActivity.this, posts);
// устанавливаем для списка адаптер
//recyclerView.setAdapter(adapter);
}
}
private ArrayList<PlaceHolderPost> getCurrendDetails(String jsonData) throws JSONException {
JSONArray postJsonArray = new JSONArray(jsonData);
ArrayList<PlaceHolderPost> postsList = new ArrayList<>();
for (int i = 0; i < postJsonArray.length(); i++) {
JSONObject entry = postJsonArray.getJSONObject(i);
postsList.add(new PlaceHolderPost(
entry.getInt("userId"),
entry.getInt("id"),
entry.getString("title"),
entry.getString("body")
));
}
return postsList;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
} else {
Toast.makeText(this, getString(R.string.network_unavailable_message),
Toast.LENGTH_LONG).show();
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
}
package com.example.slave.firstappjson;
public class PlaceHolderPost {
private int userId;
private int id;
private String title;
private String body;
PlaceHolderPost(int userId, int id, String title, String body)
{
this.userId = userId;
this.id = id;
this.title = title;
this.body = body;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = 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;
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question