Prevent Internet access from delaying toast

Completely new to Android and Java development in general, so please excuse any amateur ignorance and lack of terminology.

I am working on an Android application that includes fetching web pages as strings using a method based on the code available at http://www.spartanjava.com/2009/get-a-web-page-programatically-from- android / .

This takes a small but noticeable amount of time, but works great. It is launched by pressing a button in the user interface. Since the application does not respond to requests while receiving data, I have a toast that is designed to alert users before this happens.

Here, essentially, what is being done is done (and not the actual code, just illustrative):

public void buttonPressed(View view) { Toast.makeText(this, "Getting Data!", Toast.LENGTH_LONG).show(); //See the page linked above for the code in this function! String page = getPage("http://www.google.com/"); Toast.makeText(this, "Data Retrieved!", Toast.LENGTH_LONG).show(); } 

Unfortunately, the “Get Data” toast seems to only appear after the getPage method has completed, appearing very briefly before it closes with the “Data Retrieved” toast.

How can I avoid this by creating a “Data Retrieve” toast, then the getPage method is run, and a “Data Retrieved” toast appears when the method finishes?

Any suggestions would be highly appreciated. I expect the solution to include some kind of threads or synchronization, but I don’t even know where to start looking for the appropriate tutorial ...

Greg

+1
source share
2 answers

proper use of the AsyncTask class that solves your problem:

note the onPreExecute and onPostExecute that are called before / after the page is received.

 public class HomeActivity extends Activity { public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.home); } public void buttonPressed(View view) { new MyAsyncTask(this).execute(new String[] {"http://google.com/"}); } private class MyAsyncTask extends AsyncTask<String, Void, String> { private Context context; public MyAsyncTask(Context context) { this.context = context; } @Override protected String doInBackground(String... params) { String page = getPage(params[0]); //do any more work here that may take some time- like loading remote data from a web server, etc return page; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); Toast.makeText(context, "Data Retrieved: " + result, Toast.LENGTH_LONG).show(); } @Override protected void onPreExecute() { super.onPreExecute(); Toast.makeText(context, "Getting Data!", Toast.LENGTH_LONG).show(); } } } 
+2
source

In the user interface thread, you do not have to perform long (i.e. network or disk I / O) long operations. You should use a combination of AsyncTask or Thread / Handler .

Here are some links:

+1
source

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


All Articles