How to use a Retrofit response in another places - android

I am using Retrofit in my application and receiving data from my server.
I receive data from my server in responseBody in Retrofit, but when I want to use these received data, my array is null?!!
Here is my class:
public class ActivityApplicationsList extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_applications_list);
Log.i(TAG , "size of response array: " + populateDataFromServer().size())
//this size is 0 but have to be 4 !
}
private ArrayList<StructApplication> populateDataFromServer() {
final ArrayList<StructApplication> mine = new ArrayList<>();
final APIService service = ServiceGenerator.createService(APIService.class, "2015-03-01 14:26:00", "123456", "123456");
Call<ArrayList<AppModel>> call = service.getApp();
call.enqueue(new Callback<ArrayList<AppModel>>() {
#Override
public void onResponse(Call<ArrayList<AppModel>> call, Response<ArrayList<AppModel>> response) {
ArrayList<AppModel> newAppModel = response.body();
for(int i=0 ; i < newAppModel.size();i++){
StructApplication structApplication = new StructApplication();
structApplication.setName(String.valueOf(newAppModel.get(i).getAppId()));
structApplication.setId(newAppModel.get(i).getAppId());
structApplication.setAppVersionReleaseDate(newAppModel.get(i).getAppVersionReDate());
structApplication.setAppDeleted(newAppModel.get(i).getAppDeleted());
mine.add(structApplication);
}
}
#Override
public void onFailure(Call<ArrayList<AppModel>> call, Throwable t) {
}
});
return mine;
}
}
And I debugged to make sure that all data received in onResponse:
As you can see, I received all data correctly, but when I use this response in onCreate of this class it's null!
I really appreciate your answer about this weird problem.

This is because you are printing your list size before the response comes. As request is being sent asynchronously, and your are trying to get size before onResponse() callback method.
try to add this line
Log.i(TAG , "size of response array: " + populateDataFromServer().size())
in onResponse() method after mine.add(structApplication); you will see the right size.

Its return first and execute later, try this way...
private ArrayList<StructApplication> populateDataFromServer() {
final ArrayList<StructApplication> mine = new ArrayList<>();
final APIService service = ServiceGenerator.createService(APIService.class, "2015-03-01 14:26:00", "123456", "123456");
Call<ArrayList<AppModel>> call = service.getApp();
Response<ArrayList<AppModel>> response = responseCall.execute();
ArrayList<AppModel> newAppModel = response.body();
for(int i=0 ; i < newAppModel.size();i++){
StructApplication structApplication = new StructApplication();
structApplication.setName(String.valueOf(newAppModel.get(i).getAppId()));
structApplication.setId(newAppModel.get(i).getAppId());
structApplication.setAppVersionReleaseDate(newAppModel.get(i).getAppVersionReDate());
structApplication.setAppDeleted(newAppModel.get(i).getAppDeleted());
mine.add(structApplication);
}
return mine;
}

It is happening due to api calling because api taking few seconds to get response and meanwhile you returned your mine array. So please return response once you got value from server.
Do like this
Make a global instance for this class like
public class ActivityApplicationsList extends Activity {
ArrayList<StructApplication> mine = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_applications_list);
populateDataFromServer();
Log.i(TAG , "size of response array: " + mine.size());
}
private void populateDataFromServer() {
final APIService service = ServiceGenerator.createService(APIService.class, "2015-03-01 14:26:00", "123456", "123456");
Call<ArrayList<AppModel>> call = service.getApp();
call.enqueue(new Callback<ArrayList<AppModel>>() {
#Override
public void onResponse(Call<ArrayList<AppModel>> call, Response<ArrayList<AppModel>> response) {
ArrayList<AppModel> newAppModel = response.body();
for(int i=0 ; i < newAppModel.size();i++){
StructApplication structApplication = new StructApplication();
structApplication.setName(String.valueOf(newAppModel.get(i).getAppId()));
structApplication.setId(newAppModel.get(i).getAppId());
structApplication.setAppVersionReleaseDate(newAppModel.get(i).getAppVersionReDate());
structApplication.setAppDeleted(newAppModel.get(i).getAppDeleted());
mine.add(structApplication);
}
}
#Override
public void onFailure(Call<ArrayList<AppModel>> call, Throwable t) {
}
});
}
}

You need to get the response after the request. See code comments
public class ActivityApplicationsList extends Activity
implements Callback<ArrayList<AppModel>> { // Implement callback here
// These are final, so make them fields
final ArrayList<StructApplication> mine = new ArrayList<>();
final APIService service = ServiceGenerator.createService(APIService.class, "2015-03-01 14:26:00", "123456", "123456");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_applications_list);
populateDataFromServer();
}
// Callback implementation
#Override
public void onResponse(Call<ArrayList<AppModel>> call, Response<ArrayList<AppModel>> response) {
final ArrayList<AppModel> responseBody = response.body();
for(AppModel model : responseBody){
StructApplication structApplication = new StructApplication();
structApplication.setName(String.valueOf(model.getAppId()));
structApplication.setId(model.getAppId());
structApplication.setAppVersionReleaseDate(model.getAppVersionReDate());
structApplication.setAppDeleted(model.getAppDeleted());
mine.add(structApplication);
}
// adapter.notifyDataSetChanged(); // Need this if using ListView
Log.d("SIZE", ""+mine.size()); // Correct size
}
#Override
public void onFailure(Call<ArrayList<AppModel>> call, Throwable t) {
// error
}
private void populateDataFromServer() { // this is void; it can't return
service.getApp().enqueue(ActivityApplicationsList.this);
}
Suggestion, make this constructor
public class StructApplication {
public StructApplication(AppModel model) {
setName(String.valueOf(model.getAppId());
setId(model.getAppId());
setAppDeleted(model.getAppDeleted());
setAppVersionReleaseDate(model.getAppVersionReDate());
}
}
Then, that loop can simply be
mine.add(new StructApplication(model));

Related

Android Async interface to get data obtained fron json request

i am new to Android,here is class Question bank returns list of json obj received from an api
ArrayAsyncResponse in interface containing only one method process complete ,i readed that http request is asynchronous but unable to relate
Question is model class
case 1) when there is no ArrayAsyncResponse interface exist and i return the list to main activity and print it it shows empty list but when i make call to callback.processComplete() and then return list followed by printing ,it shows data
case2 )if i pass null in this function callback.processComplete() then again returned list is empty
so what basically Interface is helping us
public class QuestionBank {
ArrayList questionArrayList = new ArrayList<>();
private String url = "https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json";
public List<Question> getQuestions(final AnswerListAsyncResponse callBack) {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
url,
(JSONArray) null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
Question question = new Question();
question.setAnswer(response.getJSONArray(i).get(0).toString());
question.setAnswerTrue(response.getJSONArray(i).getBoolean(1));
//Add question objects to list
questionArrayList.add(question);
//Log.d("Hello", "onResponse: " + question.getAnswer());
// Log.d("JSON", "onResponse: " + response.getJSONArray(i).get(0));
//Log.d("JSON2", "onResponse: " + response.getJSONArray(i).getBoolean(1));
} catch (JSONException e) {
e.printStackTrace();
}
}
if (null != callBack) callBack.processFinished(questionArrayList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
return questionArrayList;
}
public class MainActivity extends AppCompatActivity {
private QuestionBank questionBank;
List<Question> questionList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questionBank=new QuestionBank();
questionList=questionBank.getQuestions(new AnswerListAsyncResponse() {
#Override
public void processFinished(ArrayList<Question> questionsArrayList) {//this function triggers when response is received from api
Log.d("inside", "processFinished: "+questionsArrayList);
}
});
Log.d("sync response", "questionLIst: "+questionList);
}
}
Sorry I can't write this in comment, but I think I can help you.
I don't understand well your question. but I think you need to get a Listener of the async in your class activity.
You can do that with EventBus, like this : https://github.com/greenrobot/EventBus

Android Json parsing with retrofit

I'm using retrofit for the first time and I'm looking to parse some json data but I may have made a mistake initiating the network request on MainActivity. The App doesn't crush but it's not returning any values. it's a Gridlayout with an OnclickListener on each item and I'm only looking to return 2 values (name and Id ). The object currently has 3 items (name, id, and a List<>) this is the Full API end point "https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json"
public class MainActivity extends AppCompatActivity implements
CakeAdapter.CakeClickedListener {
RecyclerView mRecyclerView;
TextView mCakeName;
ImageView mCakeImage;
TextView mCakeId;
private List<CakesItem> mCakeList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.cake_list_recycler_view);
mRecyclerView.setHasFixedSize(true);
GridLayoutManager mGridLayoutManager = new GridLayoutManager(MainActivity.this, 2);
final CakeAdapter mCakeAdapter = new CakeAdapter(this);
mRecyclerView.setLayoutManager(mGridLayoutManager);
mRecyclerView.setAdapter(mCakeAdapter);
mCakeAdapter.getCakeData(mCakeList);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
BakingJsonApi bakingJsonApi = retrofit.create(BakingJsonApi.class);
Call<List<CakesItem>> call = bakingJsonApi.getCakes(Constants.JSON_PATH);
call.enqueue(new Callback<List<CakesItem>>() {
#Override
public void onResponse(Call<List<CakesItem>> call, Response<List<CakesItem>> response) {
if (!response.isSuccessful()) {
Toast.makeText(MainActivity.this, "Code: " + response.code(), Toast.LENGTH_SHORT).show();
return;
}
List<CakesItem> cakeItem = response.body();
mCakeAdapter.getCakeData(cakeItem);
}
#Override
public void onFailure(Call<List<CakesItem>> call, Throwable t) {
Toast.makeText(MainActivity.this, "Unable to load data" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public interface BakingJsonApi {
#GET("/topher/2017/May/59121517_baking/{json}")
Call<List<CakesItem>> getCakes(#Path("json") String path);
}
class Constants {
static final String BAKING_API = "https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json";
static final String BASE_URL = "https://d17h27t6h515a5.cloudfront.net/";
static final String JSON_PATH = "baking.json";
}
Maybe update Recycler-Adapter can work. I also modified your condition.
call.enqueue(new Callback<List<CakesItem>>() {
#Override
public void onResponse(Call<List<CakesItem>> call, Response<List<CakesItem>> response) {
if (response.isSuccessful()) {
mCakeList = new ArrayList();
mCakeList.addAll(response.body());
mCakeAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Call<List<CakesItem>> call, Throwable t) {
Toast.makeText(MainActivity.this, "Unable to load data" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Try change this condition :
if (!response.isSuccessful()) {
To something like t:
if(response.isSuccessful()){
Modelcake respuesta = response.body();
listcake.addAll(respuesta.getcake()); //in getcake() you get what are you want in your model
adapter.notifyDataSetChanged();
}else{
Log.e("API","onResponse"+response.errorBody());
}
With that should be work.

Problems in understating execution flow in android studio

The following code is using retrofit and youtubedata api to get subscriber count of two youtube channels.
public class NavigationActivity extends AppCompatActivity {
private static String GOOGLE_YOUTUBE_API_KEY = "AIzaSyBV4XQEZ9l1HZeBQFL6ZZvHYfMhtnqUkmw";
private static String CHANNEL_ID_TS = "UCq-Fj5jknLsUf-MWSy4_brA";
private static String CHANNEL_ID_PDP = "UC-lHJZR3Gqxm24_Vd_AJ5Yw";
public static int SUBS_TS = 0;
public static int SUBS_PDP = 0;
//?part=snippet%2CcontentDetails%2Cstatistics&id=UC_x5XG1OV2P6uZZ5FSM9Ttw&key=AIzaSyBV4XQEZ9l1HZeBQFL6ZZvHYfMhtnqUkmw
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
Map<String, String> qMap = new HashMap<>();
qMap.put("part", "snippet,contentDetails,statistics");
qMap.put("id", CHANNEL_ID_TS);
qMap.put("key", GOOGLE_YOUTUBE_API_KEY);
Map<String, String> qMap2 = new HashMap<>();
qMap2.put("part", "snippet,contentDetails,statistics");
qMap2.put("id", CHANNEL_ID_PDP);
qMap2.put("key", GOOGLE_YOUTUBE_API_KEY);
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ChannelResponse> call = apiService.getSubs(qMap);
call.enqueue(new Callback<ChannelResponse>() {
#Override
public void onResponse(Call<ChannelResponse> call, Response<ChannelResponse> response) {
List<Channel> channels = response.body().getChannels();
SUBS_TS = channels.get(0).getStatistics().getSubscriberCount();
Log.d("GEEK", SUBS_TS + "");
}
#Override
public void onFailure(Call<ChannelResponse> call, Throwable t) {
Log.d("GEEK", t.toString());
}
});
Call<ChannelResponse> call2 = apiService.getSubs(qMap2);
call2.enqueue(new Callback<ChannelResponse>() {
#Override
public void onResponse(Call<ChannelResponse> call, Response<ChannelResponse> response) {
List<Channel> channels = response.body().getChannels();
SUBS_PDP = channels.get(0).getStatistics().getSubscriberCount();
Log.d("GEEK", SUBS_PDP + "");
}
#Override
public void onFailure(Call<ChannelResponse> call, Throwable t) {
Log.d("GEEK", t.toString());
}
});
//This statement seems to be executed before the SUSB_TS and SUSB_PDP variables are updated using the response.
Log.d("GEEK", SUBS_PDP + "AFTER");
}
}
Why is the
Log.d("GEEK", SUBS_PDP + "AFTER");
statement executed before the onResponse method?
Log
2018-12-12 14:30:26.993 17518-17518/com.geek.wartube D/GEEK: 0AFTER
2018-12-12 14:30:27.863 17518-17518/com.geek.wartube D/GEEK: 76222082
2018-12-12 14:30:27.885 17518-17518/com.geek.wartube D/GEEK: 75161493
I have also checked using the debugger that statements inside onResponse were not executed before the log statement in last line.
What should I do to achieve the desired result?
The calls to apiService.getSubs(qMap) and apiService.getSubs(qMap2) methods are done in background thread. That's why the next statement is executed before response finishes. Hence statement Log.d("GEEK", SUBS_PDP + "AFTER"); executes before onResponse() method
You can execute second call in onResponse() of first call and in onResponse() of second call do whatever you want to do next or if possible use Rxjava. But first way is simple to understand

How to handle onResponse method by using Retrofit library?

I am using retrofit library.I have created a class in which i am getting the value of particular id from other class, and i want to fetch particular list of that id but in the onResponse() method am getting an error. i checked in the postman in json format the list is fetching......but not here!
public class Main2Activity extends AppCompatActivity implements Callback<MailChimpEmailResponse> {
public String idReceived;
List<MailChimpEmailResponseSecond> emailList = new ArrayList<>();
private RecyclerView recyclerViewSecond;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Call<MailChimpEmailResponse> call = MailChimpAPIClient.getClient().fetchMembers(idReceived,"efb918ee88a3a8a77-us15" );
call.enqueue(this);
}
#Override
public void onResponse(Call<MailChimpEmailResponse> call, Response<MailChimpEmailResponse> response) {
Log.d("ashu", "null response");
Intent intent = getIntent();
idReceived = intent.getStringExtra("id_value");
Log.d("ashu", "id received is: " + idReceived);
MailChimpEmailResponse listResponse = response.body();
for (MailChimpEmailResponseSecond list : listResponse.emailLists) {
Log.d("ashu", list.getEmailListName());
this.emailList = listResponse.emailLists;
}
recyclerViewSecond = (RecyclerView) findViewById(R.id.my_recycler_view_second);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerViewSecond.setLayoutManager(linearLayoutManager);
EmailAdapter adapter = new EmailAdapter(this.emailList);
recyclerViewSecond.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<MailChimpEmailResponse> call, Throwable t) {
}
}
my api class:
public interface MailChimpApi {
#GET("lists")
public Call<MailChimpListResponse> fetchLists(#Query("apikey") String apikey, #Query("offset") int offset, #Query("count") int count);
#GET("lists/{list_id}/members")
public Call<MailChimpEmailResponse> fetchMembers(#Path("list_id") String listId,#Query("apikey") String apikey);
}
my json:
{
"members": [
{
"id": "04d80020e78edd86a79eda",
"email_address": "ashuingh.02046547#gmail.com",
"unique_email_id": "784c772918",
"email_type": "html",
"status": "subscribed",
"merge_fields": {
"FNAME": "Ashsdjssh",
"LNAME": "kudjskjar"
},
I believe the following line should be in onCreate method instead of onResponse,
idReceived = intent.getStringExtra("id_value");

JSON Download # onCreateView leaves recyclerView empty

if (isConnected()) {
Event eInstance = new Event();
theEvents = eInstance.downloadEvents(eventsNightlife, getActivity());
rAdapter = new RecyclerAdapter(theEvents);
recyclerView.setAdapter(rAdapter);
progrsBar.setVisibility(View.GONE);
....
This is part of the code that runs at "onCreateView". The method downloadEvents uses Volley to download JSON data, extract it and return a list of items (theEvents). Now when my app starts, the recycler view is empty. If I go to my home screen out of the app and then run my app again, this time the data sometimes gets downloaded.
I debugged step by step, and at first launch (i mean when the app is not just resuming), theEvents is empty, so the download didn't return or manage to return anything...
Suggestions on how to execute things before the UI has been shown to the user or what actually needs to be done to approach this task better?
Also, I use a swipeRefreshLayout and at its onRefresh method I do:
public void onRefresh() {
Event eInstance = new Event();
theEvents = eInstance.downloadEvents(eventsNightlife, getActivity());
rAdapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
but it doesn't work. I also tried to
rAdapter = new RecyclerAdapter(theEvents);
rAdapter.notifyDataSetChanged();
recyclerView.swapAdapter(rAdapter, false);
still not working.
EDIT: My downloadEvents method implementing Volley:
public List<Event> downloadEvents(String urlService, Context context) {
eventsList = new ArrayList<>();
RequestQueue requestQueue = Volley.newRequestQueue(context);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
(Request.Method.GET, urlService, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
String durationStr = null;
for (int i = 0; i < response.length(); i++) {
JSONObject eventJson = response.getJSONObject(i);
String title = eventJson.getString("EventTitle");
String body = eventJson.getString("EventBody");
String date = eventJson.getString("EventDate");
String time = eventJson.getString("EventTime");
int duration = Integer.parseInt(eventJson.getString("EventDuration"));
if (duration > 60) {
durationStr = "Duration: " + duration / 60 + " h";
} else if (duration < 60) {
durationStr = "Duration: " + duration + " m";
}
String place = eventJson.getString("EventPlace");
String organ = eventJson.getString("Organization");
Event event = new Event(title, body, date, time, durationStr, place, organ);
eventsList.add(event);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY ERROR", "" + error);
}
}
);
requestQueue.add(jsonArrayRequest);
return eventsList;
}
You can use EventBus for your purpose that is a simple and truth way.
Here, i write an example for how to use EventBus with volley.
Consider that i want to download some data.
This is the class that my download methods is inside it (you can add more methods to it in the future):
Im used volley to download my data:
// Download methods is inside volley
public class MyDownloader{
public static void downloadData(){
DownloadDataEvent dlDataEvent=new DownloadDataEvent();
List<String> myResult=new ArrayList<>();
...
#Override
public void onResponse(JSONArray response) {
super.onResponse(response);
if(respone!=null){
// Do what i want with my received data
dlDataEvent.setData(response);
}
// Post my event by EventBus
EventBus.getDefault().post(dlDataEvent);
...
}
}
}
This is my event:
public class DownloadDataEvent{
private JSONArray mData;
public void setData(JSONArray data){
mData=data;
}
public JSONArray setData(){
return mData;
}
}
Now i want to use my downloadData() method inside my MainActivity:
(I called my downloadData method inside onCreate.)
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// I have to register this class for EventBus subscriber:
if(!EventBus.getDefault().isRegister(this)){
EventBus.getDefault().registerSticky(this);
}
// Call my downloadData method
if(isConnected()){
MyDownloader.downloadData();
}
}
// And for receive the data through EventBus, i have to create a
// method (subscriber) in this template:
public void onEventMainThread(DownloadDataEvent downloadDataEvent){
JSONArray result=downloadDataEvent.getData();
// Do what i want with my received data
}
}
you can create more than one subscriber every where you want to use received data.
I passed JSONArray to my DownloadDataEvent that it is not good. you can deserialize your received data and pass it to your DownloadDataEvent.
I used Volley to download data
Maybe my descriptions were confusing, but EventBus is a well-known library and is very easy to use.

Categories

Resources