The following code is used in the MainActivity:
StringBuilder stringBuilder = new StringBuilder();
Cache cache;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonDiscard = findViewById(R.id.buttonDiscard);
RequestQueue requestQueue;
cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
Network network = new BasicNetwork(new HurlStack());
requestQueue = new RequestQueue(cache, network);
requestQueue.start();
String url ="https://www.themealdb.com/api/json/v1/1/random.php";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
stringBuilder::append,
error -> System.out.println("Error occurred"));
requestQueue.add(stringRequest);
}
public void handleDiscardClick(View view){
System.out.println(stringBuilder);
}
The issue I am facing is that I am receiving same string response for every click on the button from the url which gives random meal in json format. The only way I can get different string is with every restart of the android app which is definitely not good at all. I tried moving the networking code inside the button function still I am receiving same response. I will highly appreciate if anyone can tell me how to get different response for every click on the button. (Sorry, I am new to android networking)
I ended up modifying the whole code. I wrote the following code in another class and it worked well:
public class NetworkController {
StringBuilder stringBuilder = new StringBuilder();
private final RequestQueue queue;
public StringBuilder getstringBuilder() {
return stringBuilder;
}
public void setModelFromNetwork() {
final String url = "https://www.themealdb.com/api/json/v1/1/random.php";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
response -> {
try {
stringBuilder.append(response.toString());
} catch (JSONException e) {
System.out.println("JSONException occurred. The error is: ");
e.printStackTrace();
}
}, exception -> System.out.println("Error"));
queue.add(stringRequest);
}
public NetworkController(@NonNull final Activity activity) {
queue = Volley.newRequestQueue(activity.getApplicationContext());
}
}