Skip to content Skip to sidebar Skip to footer

How Do I Return A Value From Onresponse

Basically this it the code structure, I would like to know how i can modify my codes so that I can get the value inside onResponse and returning it. As of now, my mainReply variabl

Solution 1:

If you wanted to modify your existing code, you would add an interface like the one I added up top (RevealDetailsCallbacks), pass it into the asynctask constructor, and run it. The code would look like this:

publicclassMainActivityextendsAppCompatActivity {

    //Interface callback hereinterfaceRevealDetailsCallbacks {
        publicvoidgetDataFromResult(List<String> details);
    }

    EditText et_message;
    FloatingActionButton fab_send;
    API api;
    ListView list_view_conversation;
    List<ChatModel> list_chat = newArrayList<>();
    RevealDetailsCallbacks callback;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et_message = (EditText) findViewById(R.id.et_message);
        fab_send = (FloatingActionButton) findViewById(R.id.fab_send);
        list_view_conversation = (ListView) findViewById(R.id.list_view_conversation);

        Retrofit retrofit = newRetrofit.Builder()
                .baseUrl(API.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        this.callback = newRevealDetailsCallbacks() {
            @OverridepublicvoidgetDataFromResult(List<String> details) {
                //Do stuff here with the returned list of Strings
            }
        };

        api = retrofit.create(API.class);

        fab_send.setOnClickListener(newView.OnClickListener() {
            @OverridepublicvoidonClick(View view) {
                //this method ultimately is to get response and send back to userString s = et_message.getText().toString();
                ChatModel model = newChatModel(s, true);
                list_chat.add(model);
                newretrieveDetails(callback).execute(list_chat);

                et_message.setText("'");
            }
        });

    }

    publicclassretrieveDetailsextendsAsyncTask<List<ChatModel>, Void, String> {
        String text = et_message.getText().toString();
        String mainReply = "";
        List<ChatModel> models;
        List<String> details = newArrayList<String>();
        privateRevealDetailsCallbacks listener;

        retrieveDetails(RevealDetailsCallbacks listener){
            this.listener = listener;
        }

        @OverridepublicStringdoInBackground(final List<ChatModel>[] lists) {
            Call<List<Patient>> call = api.getPatients();
            models = lists[0];
            call.enqueue(newCallback<List<Patient>>() {
                publicString reply;

                @OverridepublicvoidonResponse(Call<List<Patient>> call, Response<List<Patient>> response) {
                    List<Patient> patients = response.body();

                    for (int i = 0; i < patients.size(); i++) {
                        if (patients.get(i).getNric().equals(text)) {
                            details.add("Name: " + patients.get(i).getName() + "\nNRIC: " + patients.get(i).getNric()
                                    + "\nDOB: " + patients.get(i).getDob() + "\nContact No: " + patients.get(i).getContactno());
                        }
                    }
                    this.mainReply = details.get(0);
                    Log.i("Here Log i", reply);
                    if(listener != null) {
                        listener.getDataFromResult(details);
                    }
                }

                @OverridepublicvoidonFailure(Call<List<Patient>> call, Throwable t) {
                    //Don't make a toast here, it will throw an exception due to it being in doInBackground//Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
            return mainReply;//I want to reply with the data added into the details arraylist in the onResponse segment
        }


        @OverridepublicvoidonPostExecute(String s) {
            ChatModel chatModel = newChatModel(s, false);
            models.add(chatModel);
            CustomAdapter adapter = newCustomAdapter(models, getApplicationContext());
            list_view_conversation.setAdapter(adapter);
        }
    }
}

However, there is no need for asynctask here since you are running Retrofit and calling .enqueue, which runs on a background thread. A simpler version would look like this:

publicclassMainActivityextendsAppCompatActivity {

    //Interface callback hereinterfaceRevealDetailsCallbacks {
        publicvoidgetDataFromResult(List<String> details);
    }

    //Keep your same variables here@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Same setup herethis.callback = newRevealDetailsCallbacks() {
            @OverridepublicvoidgetDataFromResult(List<String> details) {
                //Do stuff here with the returned list of Strings
            }
        };


        fab_send.setOnClickListener(newView.OnClickListener() {
            @OverridepublicvoidonClick(View view) {
                //Same setup here, then call the methodmakeWebCalls();
            }
        });

    }

    privatevoidmakeWebCalls(){
        Call<List<Patient>> call = api.getPatients();
        models = lists[0];
        call.enqueue(newCallback<List<Patient>>() {
            @OverridepublicvoidonResponse(Call<List<Patient>> call, Response<List<Patient>> response) {
                //Run your response code here. When done, pass to the callback
            }

            @OverridepublicvoidonFailure(Call<List<Patient>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Solution 2:

You can just enqueue the Retrofit call immediately in the OnClick and handle its response there

fab_send.setOnClickListener(newView.OnClickListener() {
        @OverridepublicvoidonClick(View view) {
            finalStringtext= et_message.getText().toString();
            // if you're trying to filter data, add a parameter to getPatients() 
            api.getPatients().enqueue(newCallback<List<Patient>>() {
                 @OverridepublicvoidonResponse(Call<List<Patient>> call, Response<List<Patient>> response) {
                     // Here you have a full list of patients final List<Patient> patients = response.body();

                     // adapter = new PatientAdapter(MainActivity.this, patients);// mListView.setAdapter(adapter);
        }

Post a Comment for "How Do I Return A Value From Onresponse"