Android Splash Screen AsyncTask - java

Basically I have a loading splash screen which will be executed when button was clicked:
public void onClick(View v) {
// Load the loading splash screen
Intent loadingIntent = new Intent(context, LoadingScreen.class);
context.startActivity(loadingIntent);
}
});
And in the LoadingScreen class:
public class LoadingScreen extends Activity{
//A ProgressDialog object
private ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Initialize a LoadViewTask object and call the execute() method
new LoadViewTask().execute();
}
//To use the AsyncTask, it must be subclassed
private class LoadViewTask extends AsyncTask<Void, Integer, Void>
{
//Before running code in separate thread
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(LoadingScreen.this,"Getting routes...",
"Loading data, please wait...", false, false);
}
//The code to be executed in a background thread.
#Override
protected Void doInBackground(Void... params)
{
try
{
//Get the current thread's token
synchronized (this)
{
//Initialize an integer (that will act as a counter) to zero
int counter = 0;
//While the counter is smaller than four
while(counter <= 4)
{
//Wait 850 milliseconds
this.wait(750);
//Increment the counter
counter++;
//Set the current progress.
//This value is going to be passed to the onProgressUpdate() method.
publishProgress(counter*25);
}
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
//Update the progress
#Override
protected void onProgressUpdate(Integer... values)
{
//set the current progress of the progress dialog
progressDialog.setProgress(values[0]);
}
//after executing the code in the thread
#Override
protected void onPostExecute(Void result)
{
finish();
//close the progress dialog
progressDialog.dismiss();
}
}
}
With these codes, the loading splash screen did came out. But I wonder is there any other way to show only the pop out dialogue for loading progress bar which on top on my previous screen?
Let's say my previous screen was event details. Then when user selected the button, only the dialogue box with loading progress bar will be shown instead of a new intent with a dialogue box.
Any ideas? Thanks in advance.
EDIT
public void onClick(View v) {
// Load the loading splash screen
new LoadViewTask().execute();
ENeighbourhoodActivity.tvDirection.setText("");
eventModel.setEventX(String.valueOf(eventModel.getEventX()));
eventModel.setEventY(String.valueOf(eventModel.getEventY()));
new GetEventDirectionAsyncTask(new GetEventDirectionAsyncTask.OnRoutineFinished() {
public void onFinish() {
//Hide the callout and plot user location marker
ENeighbourhoodActivity.callout.hide();
EventController.getUserLocation(context);
getActivity().finish();
}
}).execute(eventModel);
}
});
public class GetRegisteredEventAsyncTask extends
AsyncTask<String, Integer, Double> {
static EventController eventCtrl = new EventController();
public static ArrayList<Event> upcomingModel = new ArrayList<Event>();
public static ArrayList<Event> pastModel = new ArrayList<Event>();
public interface OnRoutineFinished { // interface
void onFinish();
}
private OnRoutineFinished mCallbacks;
public GetRegisteredEventAsyncTask(OnRoutineFinished callback) {
mCallbacks = callback;
}
public GetRegisteredEventAsyncTask() {
} // empty constructor to maintain compatibility
#Override
protected Double doInBackground(String... params) {
try {
upcomingModel = eventCtrl.getRegisteredUpcomingEvent(params[0]);
pastModel = eventCtrl.getRegisteredPastEvent(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Double result) {
if (mCallbacks != null)
mCallbacks.onFinish(); // call interface on finish
}
protected void onProgressUpdate(Integer... progress) {
}
}

In your onClick() method you could write something like:
new LoadViewTask().execute();
and the progress dialog will be shown in that page itself.

what are you doing man, just call your AsyncTask not the intent
public void onClick(View v)
{
new LoadViewTask().execute();
}
});
do your intent in postExecute
#Override
protected void onPostExecute(Void result)
{
finish();
//close the progress dialog
progressDialog.dismiss();
//START YOUR ACTIVITY HERE
Intent loadingIntent = new Intent(context, LoadingScreen.class);
context.startActivity(loadingIntent);
}
Must read the documentation of AsynTask

Related

Android dialog dismiss after certain computation

I'm encountering the following problem:
I created a waiting spinner using Dialog like this
final Dialog progDialog = new Dialog(context);
progDialog.setContentView(R.layout.progress_dialog);
progDialog.setTitle("Calculating...");
progDialog.setCancelable(false);
progDialog.setCanceledOnTouchOutside(false);
WindowManager.LayoutParams lp = progDialog.getWindow().getAttributes();
lp.dimAmount = 0.7f;
progDialog.show();
Afterwards, I'm calculating something in the background
for()...
for()...
After the calculation is finished, I want to dismiss my dialog with
progDialog.dismiss();
However, this results in my dialog never being shown at all. When I remove the last line, the dialog is shown but is never dismissed. Is there a fix to it?
You better try with AsyncTask
private class YourAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progDialog;
public YourAsyncTask(MyMainActivity activity) {
progDialog = new ProgressDialog(activity);
}
#Override
protected void onPreExecute() {
progDialog.setContentView(R.layout.progress_dialog);
progDialog.setTitle("Calculating...");
progDialog.setCancelable(false);
progDialog.setCanceledOnTouchOutside(false);
progDialog.show();
}
#Override
protected Void doInBackground(Void... args) {
// do background work here
return null;
}
#Override
protected void onPostExecute(Void result) {
// do UI work here
if (progDialog.isShowing()) {
progDialog.dismiss();
}
}
}
Use the above code in your Main Activity. And, do your calculation part in doInBackground.
To set timer for your computation try below code:
Runnable progressRunnable = new Runnable() {
#Override
public void run() {
progDialog.cancel();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);
Adding show/hide:
progDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
theLayout.setVisibility(View.GONE);
}
});
Update:
ProgressDialog class was deprecated as of API 26

Asynctask doesn't stop after cancelling it in doInBackground

I'm trying to code a progress bar, that increases depending on a timer (starts at 0 and goes up to a certain time I choose).
When I click on a button, the progress bar decreases (decreases from values[0] - 5).
When the progress bar value is 30, I want to stop the progressbar, so stop asynctask, and restart it so the progress bar value is now 0.
My code doesn't have any error, the problem is that the progressbar doesn't stop and doesn't restart. (I know that because I made a TOAST to print the value of the progress bar, and it never stops)
This is my code in MainActivity
public class MainActivity extends Activity {
ProgressBar progressBar_eau;
TextView txt;
int compteur = 0;
Button btn_arrosoir;
MyTask task_eau;
Boolean restart = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_arrosoir = (Button) findViewById(R.id.btn_arrosoir);//my button when you click the progress bar decreases
progressBar_eau = (ProgressBar) findViewById(R.id.barre_eau);
progressBar_eau.setMax(30);
Drawable draw3=getResources().getDrawable(R.drawable.custom_eau);
progressBar_eau.setProgressDrawable(draw3);
progressBar_eau.setProgress(0);
task_eau = new MyTask(progressBar_eau);
task_eau.execute(300);
btn_arrosoir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//OnCLick Stuff
compteur = compteur - 5;
}
});
}
public void cancelAsynctask(){
if (restart == false){
task_eau.cancel(true);
restartAsynctask();
Toast.makeText(MainActivity.this,
"cancel", Toast.LENGTH_LONG).show();
restart = true;
}
}
public void restartAsynctask(){
task_eau = new MyTask(progressBar_lumiere);
task_eau.execute(300);
Toast.makeText(MainActivity.this,
"restart", Toast.LENGTH_LONG).show();//my emulator shows both message start and restart even though the progress bar doesn't stop
}
public class MyTask extends AsyncTask<Integer, Integer, String> {
ProgressBar progressBar_actuelle;
public MyTask(ProgressBar target) {
progressBar_actuelle = target;
}
#Override
protected String doInBackground(Integer... params) {
while (task_eau.isCancelled() == false){
for (; count <= params[0]; count++) {
try {
Thread.sleep(1000);
publishProgress(count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onProgressUpdate(Integer... values) {
progressBar_actuelle.setProgress(values[0]+compteur);
if (progressBar_actuelle.getProgress() >= 30){
restart = false;
cancelAsynctask();
}
}
}
}
I think the problem is with the Progressbar declared in AsyncTask.Remove that and directly use the progressbar object created in onCreate method.I also observed that you are not dismissing progressbar at any point in the code. Look into it as well.

Progress Bar loading according to timer

Am using a timer to record video in my App and it is based on JavaCvRecorder app.
When I press the screen the recording starts and we are able to see the time in leftside of screen.
Now instead of showing the timer I have to show a progress bar to load according to the time can any one help me on this as i don't know where to show the progress bar. The below is code for showing time while recording video. Please help me friends
private void initiateRecording(boolean isActionDown) {
isRecordingStarted = true;
firstTime = System.currentTimeMillis();
recording = true;
totalPauseTime = 0;
pausedTime = 0;
txtTimer.setVisibility(View.VISIBLE);
// Handler to show recoding duration after recording starts
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
btnRecorderControl.setVisibility(View.VISIBLE);
btnRecorderControl.setText(getResources().getString(R.string.stop));
}
Use AsynkcTask method
private void call_timerprogressbar() { //......call this method first
try {
callprogressbar sessionrunner = new callprogressbar(getActivityTaskHandler);
sessionrunner.execute();
} catch (Exception ex) {
}
}
public class callprogressbar extends AsyncTask<String, String, String> {
Handler statushandler;
public callprogressbar(Handler getActivityTaskHandler) {
statushandler = getActivityTaskHandler;
}
#Override
protected String doInBackground(String... params) {
//........call your timer function
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setMessage("Please wait... ");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setIndeterminate(true);
progressBar.setCanceledOnTouchOutside(false);
progressBar.setTitle(" ");
progressBar.setCancelable(false);
progressBar.show();
}
#Override
protected void onPostExecute(String result) {
try
{
super.onPostExecute(result);
Message msg = new Message();
msg.obj = result;
statushandler.sendMessage(msg);
progressBar.dismiss();
}catch(Exception ex){
}
}
}
public Handler getActivityTaskHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
progressBar.dismiss();
}
};

Java AsyncTask not showing progress on UI though publishProgress(progress)

In my android app, i am doing time consuming task extending AsyncTask, and want to display the progress in Toast messages. Toast messages are also displayed onPre() and onPost().
I am able to display Toast messages onPre() & onPost() but not able to show onProgressUpdate(Integer... progress).
Following is my code...
public class MainClass extends Activity {
public void Start(View view) {
DemoTasks runner = new DemoTasks(this);
runner.execute("Start");
}
private class DemoTasks extends AsyncTask<String, Integer, Integer> {
private Context context;
public DemoTasks(Context context){
this.context = context;
}
#Override
protected Integer doInBackground(String... params) {
try {
publishProgress(0);
doWork();
Thread.sleep(5000L);
publishProgress(100);
} catch (Exception localException) {
Log.d("POST", localException.getMessage());
}
return 100;
}
#Override
protected void onPostExecute(Integer result) {
Toast.makeText(context, "post", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPreExecute() {
Toast.makeText(context, "pre", Toast.LENGTH_SHORT).show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
Toast.makeText(context, "progress-" + progress, Toast.LENGTH_SHORT).show();
}
}
}
Also in my doInBackgroud(String...params) ...Thread.sleep is also not working.
As soon as onPre() gets executed, onPost() also executes after that!!!!
You can try this,
showProgress ();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
dialog.cancel();
Intent i=new Intent(getApplicationContext(),Main.class);
startActivity(i);
finish();
}
}, 3000); //number of seconds
private ProgressDialog dialog;
public void showProgress () {
dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setMessage("Please wait");
dialog.show();}
Bascially,you can access the UI on any method, even In doinBackground you can access the UI using runOnUIthread.
here is one AsyncTask Example. This will show a peogress dialog while executing the task.
private class LoginProcessing extends AsyncTask<Object, Void, Void> {
private LoginCredentials myLoginCredentials;
private ProgressDialog progressDialog;
public LoginProcessing(LoginCredentials Credentials) {
super();
myLoginCredentials=Credentials;
progressDialog.setMax(100);
progressDialog.setMessage("Please Wait..");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgress(0);
progressDialog.show();
}
protected void onPreExecute (){
}
#Override
protected Void doInBackground(Object... arg0) {
// TODO Auto-generated method stub
//Code to do the process in background
return null;
}
#Override
protected void onProgressUpdate(Long... progress) {
// int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5);
progressDialog.setProgress(progress);
}
protected void onPostExecute(Void result){
progressDialog.dismiss();
//Your code after the process
}
}
You can call this Task as,
new LoginProcessing(loginCredentials).execute();
In this Example loginCredentials is the parameter I am passing to the AsyncTask. You can change it to your own parameter.

How to show "Loading" status in Android?

I'm making an Android application and it has to load some data though Internet (only some data-- not all). So when the data is loading, and the Internet connection is slow, I want to show a "Loading..." icon to the user.
So how can I do this? Show a "Loading..." icon while the data is being loaded in the background, and when its completely loaded, hide the icon?
Thanks in advance!
use Async Task for your status.
new SomeTask(0).execute();
/** Inner class for implementing progress bar before fetching data **/
private class SomeTask extends AsyncTask<Void, Void, Integer>
{
private ProgressDialog Dialog = new ProgressDialog(yourActivityClass.this);
#Override
protected void onPreExecute()
{
Dialog.setMessage("Doing something...");
Dialog.show();
}
#Override
protected Integer doInBackground(Void... params)
{
//Task for doing something
return 0;
}
#Override
protected void onPostExecute(Integer result)
{
if(result==0)
{
//do some thing
}
// after completed finished the progressbar
Dialog.dismiss();
}
}
Use AsyncTask along with progress dialog on task completion..That will do..
Use asynctask for Background operations, then display progress dialog like below
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
List<Message> titles;
private ListActivity activity;
//private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
List<Message> titles = new ArrayList<Message>(messages.size());
for (Message msg : messages){
titles.add(msg);
}
MessageListAdapter adapter = new MessageListAdapter(activity, titles);
activity.setListAdapter(adapter);
adapter.notifyDataSetChanged();
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
}
}
protected Boolean doInBackground(final String... args) {
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
return true;
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
}
}
}
In the onCreate method:
WebView mWebView;
ProgressDialog pgDiagWebView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
pgDiagWebView = ProgressDialog.show(CreateAccountWebView.this, "Loading", "Wait", true);
mWebView = (WebView) findViewById(R.id.registerWebView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new ResgisterWebViewClient());
mWebView.loadUrl("http://www.google.com/");
}
class ResgisterWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
pgDiagWebView.dismiss();
}
}

Categories

Resources