0

I have an app which checks if website is working by pinging website via volley
If request is made I can log whether request is successful or not
I am facing trouble in showing it in cardview I have a onBindViewHolder which populates all elements in cardview
There is a 'ischeck' function inside onBindViewHolder which checks if request is made
But since I am using volley I can't return a value from onResponse

 public void onResponse(JSONObject response) {
                         Log.d("istrue","yes");
                        Toast.makeText(context1, "Success: ", Toast.LENGTH_LONG).show();
                    }

So how do I populate cardview from onResponse function ?

2 Answers2

0

Since Volley requests are made asynchronously (in a background thread), you cannot simply return the result. What you need is a listener.

  1. Declare an interface as a listener.
  2. Implement it in your Activity/ Fragment.
  3. Pass the interface reference to the class that's making Volley request.
  4. From onResponse, call the listener callback method with the response value.
  5. Now you got the response to your Activity/ Fragment, where you can update your RecyclerView.

For an example code, check this.

Bob
  • 13,447
  • 7
  • 35
  • 45
0

you need an interface to get callback from web service:

public interface ServerCallback {
    void onSuccess(String s);
    void onError(Exception e);
}

then after that use interface in Web Service class:

import android.content.Context;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

public class WebService {

    private static WebService ourInstance;

    public static WebService getInstance() {
        if (ourInstance == null) {
            ourInstance = new WebService();
        }
        return ourInstance;
    }

    public void sample(Context context, ServerCallback serverCallback) {
        Volley.newRequestQueue(context).add(new StringRequest(Request.Method.GET, "Your URL", new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                serverCallback.onSuccess(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                serverCallback.onError(error);
            }
        }));
    }

}

finally get callback and do whatever you want from your class using this code:

    WebService.getInstance().sample(this, new ServerCallback() {
        @Override
        public void onSuccess(String s) {
            // do every thing you want
        }

        @Override
        public void onError(Exception e) {
            // handle error response
        }
    });
}