I'm doing a login, I would like when the user put the credentials, the app show a toast or a image saying loading. But this image should be a few seconds in the screen before change the activity. Thanks.
Basically the image is shown during the time when the app is doing authentication task or other works in background. I dont know why you want few seconds. And you can use progress dialog for the loading view.
Do authentication in an AsyncTask and update interface when data finishes loading.
You can start a new activity in your AsyncTask's onPostExecute() method.
You need a new class that extends AsyncTask:
public class MyTask extends AsyncTask<Void, Void, Void> {
public MyTask(ProgressDialog progress) {
this.progress = progress;
}
public void onPreExecute() {
progress.show();
}
public void doInBackground(Void... unused) {
//do your login here
}
public void onPostExecute(Void unused) {
progress.dismiss();
}
}
In activity do:
ProgressDialog progress = new ProgressDialog(this);
progress.setMessage("Loading...");
new MyTask(progress).execute();
In onPostExecute() start activity by Intent
Intent go=new Intent(this.class,target_activity.class);
startActivity(go);
Related
I'm having trouble avoiding a "Unable to add window — token android.os.BinderProxy is not valid; is your activity running?" exception when using a progress dialog box with an async task.
final ProgressDialog nDialog = new ProgressDialog(MainActivity.this);
nDialog.setMessage("Loading...");
nDialog.setIndeterminate(false);
nDialog.setCancelable(false);
if(!isFinishing()){nDialog.show();}
I then continue with:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Run code while showing progress dialog
ndialog.dismiss
}
}, 1000);
I've come to understand that I'll occasionally get an exception because the activity will have finished, while the ndialog is being accessed. So a solution seems to be change the ndialog.
The initial issue of showing a dialog once the activity finishes (which only happens rarely) is solved by
if(!isFinishing()){nDialog.show();}
I was considering putting this same code for the nDialog.dismiss. But the problem is that if I do:
if(!isFinishing()){nDialog.dismiss();}
and the activity finishes before this can run, the user will get stuck with a dialog screen that will never get dismissed.
Am I missing something? How can I prevent this error, but at the same time make sure that the dialog will start and be dismissed?
Thanks!
Careful while handling views, activities and other related UI objects from another thread. Threads like AsyncTask are not aware of the activity lifecycle, and you may end up posting things to dead windows. I believe this is what is happening to you.
A safer way to do this:
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.lang.ref.WeakReference;
public class MyTask extends AsyncTask<Void, Void, Void> {
private final WeakReference<MyActivity> weakReferenceActivity;
public MyTask(#NonNull MyActivity activity) {
this.weakReferenceActivity = new WeakReference<>(activity);
}
#Nullable
public MyActivity getActivity() {
MyActivity activity = weakReferenceActivity.get();
if (activity.isDestroyed()) {
return null;
}
return activity;
}
#Override
protected void onPreExecute() {
MyActivity activity = getActivity();
if (activity != null) {
activity.showProgressDialog();
}
}
#Override
protected Void doInBackground(Void... voids) {
[do something]
return null;
}
#Override
protected void onPostExecute(Void nothing) {
MyActivity activity = getActivity();
if (activity != null) {
activity.hide();
}
}
}
I'am trying to implement an AsyncTask in Android that will load all my data from the database. Therefore I used the onPreExecute method to start a ProgressDialog
public class DataLoader extends AsyncTask<Void, Void, Void> {
private LoginActivity activity;
private ProgressDialog nDialog;
public DataLoader (LoginActivity act){
this.activity = act;
nDialog = new ProgressDialog(activity);
}
protected void onPreExecute() {
System.out.print("Start AsyncTask");
nDialog.setMessage("Loading data..");
nDialog.setTitle("Starting the application");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected Void doInBackground(Void ... params) {
System.out.println("Starting doInBackground");
loadDashboardData();
return null;
}
protected void onPostExecute() {
nDialog.dismiss();
Intent i = new Intent();
i.setClass(activity.getApplicationContext(), DashboardActivity.class);
activity.startActivity(i);
}
The I use the doInBackground method to load call a function to load the data. This method is called from an visible activity. The task is called with:
public class LoginActivity extends Activity {
public void onClick(View v) {
DataLoader dl = new DataLoader(this);
dl.execute();
}
}
And the code for the doInBackground is:
protected Void doInBackground(Void ... params) {
System.out.println("Starting doInBackground");
loadDashboardData();
return null;
}
Now the problem is that my doInBackground method will not finish. I tried to implement the loadDashboardData() call in the onPreExecute method. This will not show my dialog box but it will load the data correctly. In this case the UI Thread is not responding and will response after all the data has been loaded.
What can hinder the doInBackground method to execute correctly and load the data properly? The called method works (because I can call it and get the correct data). Also I'am not seeing the println in my run console.
In the frontend I can see the progressbar spinning, but in the backend I can see that no data is loaded.
Your problem is that you are overriding the wrong method name : )
It should be
#Override
protected void onPostExecute(Void result) {
// your code
}
as in your case the variable which doInBackground return is Void.
You can check the documentation about AsyncTask .
So I'm just trying to create an Alert Dialog that is just a message (no buttons or titles). I want to display an alert dialog when a background task is running. The alert dialog will run on the UI thread.
Here's what I have done so far:
protected void onPreExecute() {
super.onPreExecute();
AlertDialog altDlg;
altDlg = new AlertDialog.Builder(AlertDialogActivity.this).create();
altDlg.setMessage("Retrieving Information. Please Wait");
altDlg.show();
}
I also tried doing this:
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setMessage("Retrieve Info. Please Wait").show();
The error I am getting with the first one is:
cannot find symbol 'AlertDialogActivity'
symbol: class AlertDialogActivity
location: class com.example.Device.Activity
The second attempt error says:
incompatible types: com.example.Device.Activity cannot be converted to android.content.Context
I'm not sure what I am doing wrong in either scenario. I just want to display a basic message when a background task is running and I was hoping the closest thing I can use is AlertDialog.
EDIT for how to set up AsyncTask properly:
Small background of what I want to do. I just want to read in a file, deserialize it and save it's contents to a db.
Right now I'm assuming I only need two activities.
One is my main activity:
public class MainActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setup);
final Button setup_button = (Button) findViewById(R.id.setup_button);
setup_button.setOnClickListener (new View.OnClickListener() {
public void onClick(View view){
setContentView(R.layout.retrieve_info);
}
});
}
}
Now the onClick event just moves to the new view that is supposed to display the message or alert dialog that says retrieving information. Please Wait. It displays the message while reading a file and saving to db. Once the file is read and saved, The message should disappear and say something like setup complete.
My second activity so far is:
public class RetrieveInfoActivity extends AsyncTask<Void,Void,Void> {
private ProgressDialog progressBar;
private void retrieveInfo(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
//Read all the lines until there are no more lines
while (scanner.hasNextLine()) {
scanner.nextLine();
//TODO: deserialize and save to db
}
scanner.close();
}
catch (FileNotFoundException e) { e.printStackTrace(); }
}
#Override
protected Void doInBackground(Void... params) {
retrieveInfo("test.txt");
return null;
}
protected void onPreExecute() {
super.onPreExecute();
progressBar.setIndeterminate(true);
progressBar.setCancelable(false);
progressBar.setMessage("Retrieve Information.Please wait");
progressBar.show();
}
#Override
protected void onPostExecute() {
progressBar.dismiss();
}
}
That's all I really have so far. I just need to understand how to set up this in Android conceptually.
Hope this makes sense.
Try this:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
Instead of using an AlertDialog use a ProgressBar, it will do the trick for you.
private ProgressDialog progressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setIndeterminate(true);
progressBar.setCancelable(false);
progressBar.setMessage("Your message");
progressBar.show();
}
#Override
protected void onPostExecute(final String error_code) {
progressBar.dismiss();
}
Looks like you are extending AsyncTask and trying to use it as a context. That won't work as AsyncTask itself is nothing but an abstract class.
You need to create a custom constructor for your AsyncTask to fetch the Context:
public class MyTask extends AsyncTask<Void, Void, Void> {
private Context mCtx;
public MyTask(Context context) {
mCtx = context;
}
...
Then when starting your AsyncTask, pass the context:
new MyTask(this).execute();
Another way would be to make the AsyncTask an inner class and use YourActivity.this when creating the dialog. Example:
public class YourActivity extends Activity {
...
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
AlertDialog dialog = new AlertDialog.Builder(YourActivity.this).create();
}
#Override
protected Void doInBackground(Void... params) {
...
}
}
}
I have an activity with a listview. When I call this activity the activity takes about 3-5 seconds to appear and display the listview. It looks as if the button has not been pressed to load the activity, i would like to display a progressdialog while this loads but can't figure it out.
ProgressDialog progress;
progress = ProgressDialog.show(this, "Loading maps!",
"Please wait...", true);
// sort out track array
getTracks();
progress.dismiss();
I did the above on the oncreate() of the activity with the listview but the dialog never shows?
What I would like is to show the progress dialog on Activity A when the button is pressed and then dismiss once Activity B is loaded and displayed?
Thanks
You need to implement AsyncTask or simple JAVA threading. Go with AsyncTask right now.
onPreExecute() - display dialog here
doInBackground() - call getTracks()
onPostExecute() - display tracks in ListView and dismiss dialog
For example:
private static class LoadTracksTask extends AsyncTask<Void, Void, Void> {
ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = new ProgressDialog(yourActivity.this);
progress .setMessage("loading");
progress .show();
}
#Override
protected Void doInBackground(Void... params) {
// do tracks loading process here, don't update UI directly here because there is different mechanism for it
return null;
}
#Override
protected void onPostExecute(Void result) {
// write display tracks logic here
progress.dismiss(); // dismiss dialog
}
}
Once you are done with defining your AsyncTask class, just execute the task inside onCreate() by calling execute() method of your AsyncTask.
For example:
new LoadTracksTask().execute();
You can make progress Dialog like this :
onPreExecute(){
progressdialog = new ProgressDialog(MainActivity.this);
progressdialog.setMessage("Please wait while downloading application from the web.....");
progressdialog.setIndeterminate(false);
progressdialog.setMax(100);
progressdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressdialog.setCancelable(false);
progressdialog.show();
}
doInBackground(String... strings){
// here you code for downloading
}
onProgressUpdate(String... progress)
{
// here set progress update
progressdialog.setProgress(Integer.parseInt(progress[0]));
}
onPostExecute(String result)
{
progressdialog.dismiss();
}
Use something like this:
private static class MapLoader extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
progress.setVisibility(View.VISIBLE);
// make your element GONE
}
#Override
protected Void doInBackground(Void... params) {
// Load map processing
return null;
}
#Override
protected void onPostExecute(List<Document> result) {
progress.setVisibility(View.GONE);
adapter.setNewData(new_data);
adapter.notifyDataSetChanged();
}
}
In your onCreate() use:
listView.setAdapter(adapter);
new MapLoader.execute();
I have developed an Android App that communicates via HTTP-Request with a server.
Some times it takes more time for a request so the app shows just a black screen and passes some seconds later. Sometimes the black screen appears some seconds later and you can send the request again and again.
Is there any possibility to disable the onTouch-Events or show a layer while the screen is loading?
Thank you.
use an asyncTask and launch your httprequest in the doInBackground() method, and for blocking the user , just display a ProgressDialog :
class YourRequestTask extends AsyncTask<Void, Void, JSONObject> {
ProgressDialog progress;
Context context;
public YourRequestTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(context, null,"Please wait...");
}
#Override
protected JSONObject doInBackground(Void... params) {
//do your work here for your http request
}
#Override
protected void onPostExecute(JSONObject result) {
progress.dismiss();
Log.i(TAG, "result is "+result.toString());
}
}