This is my activity oncreate() method. I set a positive button ok with a dialogue window.
when I click on it, it navigates UI activity staticDisplay.class. I want to set a progress bar after clicking ok in the dialogue window until it loads the next activity.
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "ACTIVITY ONCREATE");
super.onCreate(savedInstanceState);
// setContentView(R.layout.dialog);
setContentView(R.layout.main);
if (Registration.isRunning == false) {
TextView title = new TextView(this);
title.setText("DM2");
title.setBackgroundColor(Color.DKGRAY);
title.setPadding(10, 10, 10, 10);
title.setGravity(Gravity.CENTER);
title.setTextColor(Color.WHITE);
title.setTextSize(20);
/* alert message */
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCustomTitle(title);
builder.setMessage(R.string.app_description).setPositiveButton(
"Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (Registration.isRunning == false) {
startService(new Intent(
getApplicationContext(),
Registration.class));
}
staticInfo();
if (Registration.ruid == null)
Registration.ruid = uId;
startActivity(new Intent(getApplicationContext(),
StatisticDisplay.class));
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
startActivity(new Intent(getApplicationContext(),
StatisticDisplay.class));
}
}
StaticDisplay.class on create method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.statdisplay);
usage_btn = (Button) findViewById(R.id.appstat);
usage_btn.setOnClickListener(this);
setting_btn = (Button) findViewById(R.id.setting);
setting_btn.setOnClickListener(this);
}
you can use AysncTask for background process to be done and showing progressdialog as follows,
call the class
new Task().execute(CurrentActivity.this);
In Task Class:
private class Task extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialog;
Context context;
public Task(Context context)
{
this.context=context;
//constructor for this class
}
protected void onPreExecute() {
//create the progress dialog as
dialog=new ProgressDialog(context);
}
protected Void doInBackground(Void... JSONArray) {
//Place your background process code
}
protected void onPostExecute(Void unused) {
//dismiss the progressdialog
dialog.dismiss();
}
}
This Code , Working For me
private ProgressDialog progress;
Button CallButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
progress = new ProgressDialog(Page.this);
CallButton=(Button)findViewById(R.id.button1);
CallButton.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
switch (v.getId()) {
case R.id.button1:
progress.setMessage("Please Wait Loading...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.show();
new Thread()
{
public void run()
{
Intent i = new Intent(Page.this,Update.class);
startActivity(i);
progress.dismiss();
}
}.start();
break;
}
}
Please look at to following code snippet,
progDailog = ProgressDialog.show(loginAct,"Process ", "please wait....",true,true);
new Thread ( new Runnable()
{
public void run()
{
// your loading code goes here
}
}).start();
Handler progressHandler = new Handler()
{
public void handleMessage(Message msg1)
{
progDailog.dismiss();
}
}
In the run() method, you can put your loading code.
Related
I want to show a ProgressDialog while jumping from my LoginActivity to my HomeActivity, basically while HomeActivity is loading.
I am using a separate thread to call the intent of the HomeActivity while I am showing the ProgressDialog from the main thread in LoginActivity.
Everything seems to be working fine, it is just that the ProgressDialog is displayed but there is no animated spinner.
I am wondering if i am doing this correctly.
Here the relevant code from LoginActivity:
public class LoginActivity extends AppCompatActivity {
private EditText userID, userPass;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userID = (EditText) findViewById(R.id.edtX_srcLogin_userID);
userPass = (EditText) findViewById(R.id.edtX_srcLogin_userpass);
final Button bt_submit = (Button) findViewById(R.id.bT_scrLogin_submit);
bt_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
parseUserCredentials(userID.getText().toString(), userID.getText().toString());
}
});
}
private void parseUserCredentials(String userId, String userPassword) {
if ( userId.equals("userid") && userPassword.equals("1234") ) {
dialog = ProgressDialog.show(LoginActivity.this, "Checking credentials",
"Please wait...", true, false);
newThreadLoadActivity();
}else {
userID.setText("");
userPass.setText("");
userID.requestFocus();
dialog.cancel();
}
}
private void newThreadLoadActivity(){
new Thread() {
public void run() {
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
}
}.start();
}
#Override
protected void onStop() {
super.onStop();
dialog.cancel();
}
}
EDIT
The main idea is to show the ProgressDialog whileHomeActivity loads, and cancel the ProgressDialog when HomeActivity is ready to be displayed.
Use the below code.It will make the delay for 10sec while moving to the next activity so your progress bar make be visible.
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
dialog.cancel();
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
}
}, 10000);
I currently trying to show a progress dialog on OnclickListener of a Dialogbox since my items are taking too long to fetch from Server.
I use Async task as suggested here (Android progress dialog) and this post (android problem with progress dialog) to show progress dialog The progress dialog is shown , however the code returns exception when it goes to do background that " Looper is not set". And when I set looper nothing happens.
I am not sure at this stage what is it that I am doing wrong.
public void firstMethod()
{
final CustomObj obj = getCustomObj();//not imp
Messages.getInstance().showAlert(MainActivity.this, "message", false, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
}, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
gotoAnotherPge(obj);
}
});
}
public void gotoAnotherPge(final CustomObject obj)
{
final ProgressDialog pd = new ProgressDialog(MainActivity.this);
new AsyncTask<Object, Object, Boolean>()
{
protected void onPreExecute()
{
pd.setMessage(String.format(Statics.getText(MainActivity.this, R.raw.dictionary, "subscriptions_loading_unsubscribing")));
pd.show();
}
protected Boolean doInBackground(Object... params)
{
try{
Looper.prepare();
final LocalPopulator lp = new LocalPopulator(MainActivity.this, 0)
{
#Override
public void populate()
{
List<Serializable> items = Arrays.asList(getItemHere(obj));
List<Serializable> listItems = new ArrayList<Serializable>();
listItems.addAll(items);
Serializable[] sItems = listItems.toArray(new Serializable[menuItems.size()]);
result = sItems;
}
};
showNextPage(true, 1, 0, lp);
Looper.loop();
}catch (Exception e){
Log.e("tag", e.getMessage());
/*
* The task failed
*/
return false;
}
return true;
}
protected void onPostExecute(Boolean result)
{
pd.dismiss();
}
};
MainActivity.this.runOnUiThread (new Runnable()
{
#Override
public void run()
{
// dismiss the progressdialog
pd.dismiss();
}
});
}
How to show the ProgressDialog button after n seconds (fixed) delay that the ProgressDialog is shown?
To be more clear, the ProgressDialog starts normally. How can I show a button within it after n seconds?
L.F.
EDIT
Using the answers of Segi and android_beginner (thank you very much) I'm posting the solution of my problem:
pDialog = new ProgressDialog(mContext);
pDialog.setTitle(Reso.getString(mContext, R.string.waiting));
pDialog.setMessage(Reso.getString(mContext, R.string.waiting));
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
Reso.getString(mContext, R.string.annulla),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Stuff
}
});
pDialog.show();
pDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setVisibility(View.INVISIBLE);
int progressDialogCancelButtonDelay = 2500;
new CountDownTimer(progressDialogCancelButtonDelay, progressDialogCancelButtonDelay + 1) {
#Override public void onTick(long millisUntilFinished) { }
#Override public void onFinish() {
pDialog.getButton(ProgressDialog.BUTTON_NEGATIVE).setVisibility(View.VISIBLE);
}
}.start();
Try Something Like Below Code:
ProgressDialog loadingDialog = ProgressDialog.show(activity.this, "", "Loading...",
true, false);
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(2500);
runOnUiThread(new Runnable() {
public void run() {
loadingDialog.dismiss();
loadingDialog.setButton(ProgressDialog.BUTTON_NEUTRAL,
"Close",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//button click stuff here
}
});
loadingDialog.show();
loadingDialog.getButton(ProgressDialog.BUTTON_NEUTRAL).setVisibility(View.INVISIBLE);
}
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Just extend this class instead of AsyncTask and be sure to call super() when appropriate:
public abstract class AsyncTaskWithDelayedIndeterminateProgress
<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
private static final int MIN_DELAY = 250;
private final ProgressDialog progressDialog;
private final CountDownTimer countDownTimer;
protected AsyncTaskWithDelayedIndeterminateProgress(Activity activity) {
progressDialog = createProgressDialog(activity);
countDownTimer = createCountDownTimer();
}
#Override protected void onPreExecute() {
countDownTimer.start();
}
#Override protected void onPostExecute(Result children) {
countDownTimer.cancel();
if(progressDialog.isShowing())
progressDialog.dismiss();
}
private ProgressDialog createProgressDialog(Activity activity) {
final ProgressDialog progressDialog = new ProgressDialog(activity);
progressDialog.setIndeterminate(true);
return progressDialog;
}
private CountDownTimer createCountDownTimer() {
return new CountDownTimer(MIN_DELAY, MIN_DELAY + 1) {
#Override public void onTick(long millisUntilFinished) { }
#Override public void onFinish() {
progressDialog.show();
}
};
}
make a layout with your ProgressDialog and an invisible button on it.
When you show the dialog activate a timer, that set the button visible after n seconds.
I dont know if i understand your question right, but i hope so. =)
progress dialog doesnt work while listing data with listAdapter
i think its all about sending activity to myAdapter
final myAdapter adapter = new myAdapter(rss_list_activity.this, liste);
final ProgressDialog dialog = ProgressDialog.show(this, "Title",
"Message", true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
dialog.dismiss();
}
};
Thread checkUpdate = new Thread() {
public void run() {
getListFromXml();
lv.setAdapter(adapter);
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
here's some information on threading, i would use an AsyncTask if I were you:
http://developer.android.com/resources/articles/painless-threading.html
Something similar to this should work:
LoadListTask tsk = new LoadListTask();
tsk.execute((Void) null);
with this somewhere
private class LoadListTask extends AsyncTask<Void, Void, List<theType>>
{
final ProgressDialog dialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
dialog = ProgressDialog.show(MainClass.this, "Title", "Message", true);
}
#Override
protected void onPostExecute(List<theType> result)
{
super.onPostExecute(result);
final myAdapter adapter = new myAdapter(rss_list_activity.this, result);
lv.setAdapter(adapter);
dialog.dismiss();
}
#Override
protected List<theType> doInBackground(Void... params)
{
return getListFromXml();
}
}
use dialog.show(); to show dialog. you are directly dismissing the dialog using dialog.dismiss();
For the past few days, I haven't been able to solve an issue with my dialog box. I am running a thread to show the dialog box for 5000ms and removing it. and I am trying to show a toast("SUCCESS"). The problem is I am getting the dialog box for the second time also. I am new to android development and I need to solve this with Async Task so that I can delay the second thread and show a alert dialog.builder with a positive button instead of toast. I goggled a lot but I confused to to implement this
Here I am sending my credentials to server and while sending I am showing a progress dialog box for 5000ms and I want to have a separate thread in order to show the dialog.builder with a positive button.( When the user get a response in the logcat for that I should check the responsecode==1 or not from the logcat to show the builder)
plz someone help me to solve this with some code snippet if possible.
Thanks in advance.
this is the code where I need to implement Async task
Button signin = (Button) findViewById(R.id.regsubmitbtn);
signin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// showDialog(0);
t = new Thread() {
public void run() {
register();
try {
while (counter < 2) {
showmsg(0);
Thread.sleep(5000);
removeDialog(0);
// Toast.makeText(Register.this, "Registerd", Toast.LENGTH_LONG).show();
showmsg(1);
// toast.show();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 0: {
++counter;
dialog = new ProgressDialog(this);
if (counter == 1) {
dialog.setMessage("Registering...");
}
else {
String resultsRequestSOAP = "";
if (Log.v("TAG", String.valueOf(resultsRequestSOAP)) == 1)
;
{
Context context = getApplicationContext();
CharSequence text = "Registerd";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
dialog.setIndeterminate(true);
dialog.setCancelable(true);
return dialog;
}
}
return null;
}
public void showmsg(int actionsToBePerformedOnScreen) {
Message msg = new Message();
msg.what = actionsToBePerformedOnScreen;
handler.sendMessage(msg);
}
public Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
showDialog(0);
break;
case 1:
// clear all images in the list
removeDialog(0);
break;
}
};
};
Easy: show dialog onPreExecute, register() in doInBackground and hide dialog in onPostExecute. Finally, do new RegisterTask().execute() in your onclick.
private class RegisterTask extends AsyncTask<Void, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(YourClass.this);
protected void onPreExecute() {
this.dialog.setMessage("Signing in...");
this.dialog.show();
}
protected Boolean doInBackground(final Void unused) {
return Main.this.register(); //don't interact with the ui!
}
protected void onPostExecute(final Boolean result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if (result.booleanValue()) {
//also show register success dialog
}
}
}
Why you don't use Android AsyncTask?
For example:
public class MyPreloader extends AsyncTask<InputObject, Void, OutputObject>{
private Context context;
private ProgressDialog dialog;
public MyPreloader(Context context){
this.context = context;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(context);
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.show();
super.onPreExecute();
}
#Override
protected ResponseBase doInBackground(InputObject... params) {
InputObject input = params[0];
//some code for background work
}
#Override
protected void onPostExecute(OutputObject result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
super.onPostExecute(result);
}