I am trying to show the Progress Bar component (circular, not horizontal) during a GET api request in Android Studio. I am running the API request on a different thread and I am setting the progress bar to visible before the thread starts and setting its visibility to gone after the thread is over using the runOnUiThread()
method. My code works correctly without the progress bar, I just want a better user experience by showing them that the search is loading. I have already looked at a lot of other solutions, but so far, none have worked (maybe I haven't done it correctly).
The progress bar doesn't show up at all normally, but if I don't set it's visibility to gone, the progress bar shows up after the thread completes. Here is my current code for searching for ingredients:
private List<FoodHint> searchIngredient(String ingredient) {
Gson gson = new Gson();
AtomicReference<FoodSearchResults> searchResults = new AtomicReference<>();
runOnUiThread(new Runnable() {
@Override
public void run() {
progressBar.setVisibility(View.VISIBLE);
}
});
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
StringBuilder result = new StringBuilder();
URL url = new URL("www.exampleurl.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
Scanner scanner = new Scanner(url.openStream());
while (scanner.hasNext()) {
result.append(scanner.nextLine());
}
scanner.close();
} else {
Log.d("debug-error", "Response Code: " + responseCode);
}
searchResults.set(gson.fromJson(result.toString(), FoodSearchResults.class));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
progressBar.setVisibility(View.GONE);
}
});
return searchResults.get().getHints();
}