📜 ⬆️ ⬇️

Making the ProgressBar spin while the http request is coming

It all started with the fact that I suddenly really wanted to do something under the android. And all this despite the fact that java is not my native language.
In the process of creating my application, I encountered several difficulties, the solution of which I want to tell. I think they will be useful, just like me, to beginners, and I will be grateful for advice and more beautiful examples from the guru.
But the main proof of the examples is that the application is working, you can check .

Here are a few problems I encountered:

Consider the first problem so far.

The UI waits for the server to respond, how to win?


Interaction with the server is the key moment of this application. When an application sends a request to the server, it has to wait for a response. During this wait, the user interface stops and it seems that the program is hanging. Nestrachno, if the answer is received within a second, but in reality, waiting for a response from the server sometimes has about 10 seconds. To inform the user that the application is not stuck, you need to show him the ProgressBar. I stopped on a spinning wheel, as in AJAX. Here's what it looks like:


I will describe approximately how it works. I have a certain class HttpClient, he is responsible for interacting with the server. He starts and stops the ProgressBar. This class works asynchronously. That is, the application, running it does not wait until it runs, and may continue its work. This is achieved by the following construction:
//   public class HttpClient extends AsyncTask<Void, Integer, Long>{ ... //   public ProgressDialog dialog; //    Context ctx; ... //  ProgressBar     protected void onPreExecute() { dialog = new ProgressDialog(ctx); dialog.setMessage("..."); dialog.setIndeterminate(true); dialog.setCancelable(true); dialog.show(); } //   , SendHttpPost() -    protected Long doInBackground(Void... params) { try { response = SendHttpPost(); } catch (Exception e) { e.printStackTrace(); response = null; } return null; } //      ,  ProgressBar protected void onPostExecute(Long unused) { dialog.dismiss(); ... //     ,    //     : ((Runnable)ctx).run(); .... super.onPostExecute(unused); } .... } 


The parent class that calls the HttpClient looks like this:
 public class SearchableActivity extends ListActivity implements Runnable { private HttpClient req; ... //   ,       private void showResults(String query) { ... req = new HttpClient(); req.execute((Void)null); } //     HttpClient,        -    public void run() { ... //   req    ,    Activity ... } } 

')
The fact that I followed the Runnable path seems to me very controversial, but at that time there were no other thoughts.

But I learned to download and show asynchronously pictures for this article: habrahabr.ru/blogs/android/78747 I use the moment to say thanks rude !

Source: https://habr.com/ru/post/107188/


All Articles