I have a requirement of having a activity as dialog (Not an Alert dialog, instead a progress dialog). There are no ui components in this activity since this activity does server interaction, based on server response next activities are started. Only a progress dialog with cancel button needs to be shown in this activity. Now the problem is when ever this activity is launched just before progress dialog is displayed a small black rectanagle is visible for a second or more, also when this activity is finished this is visible. How to get rid of this ? or is there any better way of haveing a progress dialog as activity ?
-Thanks & regards,
Manju
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityAsDialogActivity.this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
String str ="Hellow World";
txtView = (TextView)findViewById(R.id.txtview);
this.setFinishOnTouchOutside(false);
txtView.setText(R.string.select_dialog);
ActivityAsDialogActivity.this.setTitle(R.string.app_name);
mProgressHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (mProgress >= MAX_PROGRESS) {
mProgressDialog.dismiss();
Intent intent = new Intent(ActivityAsDialogActivity.this, ActivityOne.class);
startActivity(intent);
finish();
} else {
mProgress++;
mProgressDialog.incrementProgressBy(1);
mProgressHandler.sendEmptyMessageDelayed(0, 100);
}
}
};//end of handler
showDialog(DIALOG_PROGRESS);
mProgressDialog.setProgress(0);
mProgressHandler.sendEmptyMessage(0);
}//end of onCreate()
#Override
public void onBackPressed(){
Log.d("Manju ==>"," back key pressed");
finish();
}
#Override
public void finish(){
Log.d("Manju ==>", " inside finish()");
super.finish();
}
In Creating Global Dialog, I used a transparent activity with a dialog inside. I think you can do the same thing. I do not recall facing the problem you are facing, and it worked perfectly.
Check it out
Related
I have 5 buttons in my activity inside a linear layout.
I have written a code to display a toast message when I click one of those buttons.
It is displaying the toast message after 6 seconds of Click action.
I couldn't think what the problem could be..
Here is the code I have written in android studio
public class HomePage extends AppCompatActivity implements View.OnClickListener {
private Button loginButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
makeNotificationBarTransparent();
loginButton = (Button)findViewById(R.id.login_btn);
loginButton.setOnClickListener(this);
Intent i = getIntent();
Toast.makeText(getApplicationContext(),i.getStringExtra("UserName"),Toast.LENGTH_LONG).show();
}
private void makeNotificationBarTransparent() {
//Making notification bar transparent
if(Build.VERSION.SDK_INT >= 21){
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.login_btn:
Toast.makeText(getApplicationContext(),"CLicked",Toast.LENGTH_LONG).show();
break;
}
}
}
Can anyone tell me What could be the problem?
It might be the fact that you show another toast message that you set to show up, as two toast messages cannot display at once.
I am referring to this toast message:
Toast.makeText(getApplicationContext(),i.getStringExtra("UserName"),Toast.LENGTH_LONG).show();
You mean the Toast message will be show after clicking the button for 6 seconds?
Try to use this:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// show toast here...
}
}, 6000); // 6 seconds
Or you can use CountDownTimer:
new CountDownTimer(6000, 1000) {
public void onTick(long millisUntilFinished) {
// do every 1 second
}
public void onFinish() {
// show your toast after 6 seconds.
}
}.start();
Is this what you need? If not, tell me more about your problems :)
I have added a popup activity inside my app which is popping after 15 seconds of my app start. But when I am opening another activity and coming back to my main activity the popup showing again. I want it to appear only the first time when user is opening the app. What changes I should make? Appreciate the help.
Here is the popup code:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (context != null) {
AlertDialog.Builder alert = new AlertDialog.Builder(context, R.style.MyAlertDialogStyle)
.setTitle("Title")
.setMessage("Message")
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
Intent intent = new Intent(MainActivity.this, WebActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int which) {
dialogInterface.dismiss();
// do nothing
}
});
mDialog = alert.create();
mDialog.getWindow().getAttributes().windowAnimations = R.style.MyAlertDialogStyle;
if (!((Activity) context).isFinishing())
mDialog.show();
// .setIcon(R.drawable.inr1)
// .show();
}
}
}, 15000);
You can do this if it needs to pop up only on application start
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
//Set some flag on global constant
}
}
save a tag(counter) in sharedPrefrances for that When the application starts up interpretation is the first time app start
You can use a global variable in the application class like this.
public class global extends Application
// some Boolean variable to hold status
And make sure you put this class inside android manifests application tag
android:name
Add this code in your MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
if(sharedPreferences.getBoolean("IS_FIRST_TIME", true)) {
//show your dialog here
//...
//change the value of your sharedPreferences
sharedPreferences.edit().putBoolean("IS_FIRST_TIME", false).apply();
}
}
please check the activity lifecycle.
Note:Remove Handler.
Note 2:Create method and call the dialog
Note 3:check the below method in lifecycle.
onPause ():
Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here.
save a boolean inside sharedpreferences read its value and determine weather running for the first time or not.
here is the code that will help you.
public void firstimeRun(boolean value) {
SharedPreferences sharedPreferences = getPrefrenceManager();
sharedPreferences.edit().putBoolean("key", value).apply();
}
public boolean isRunningForthefirstTime() {
SharedPreferences sharedPreferences = getPrefrenceManager();
return sharedPreferences.getBoolean("key", false);
}
private SharedPreferences getPrefrenceManager() {
return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
}
Type finish(); after your startActivity(intent);
Before referring me to other threads on this forum and marking my question as duplicate kindly read my question. I have to create a global application timeout. No matter which activity is user on, after specific amount of time the user will be displayed AlertDialog that his session has expired and he can exit or renew his session. I have read different solutions and used service as my solution.
public class InActivityTimer extends Service {
MyCounter timer;
#Override
public void onCreate() {
timer = new MyCounter(20 * 1000,1000);
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
timer.start();
return super.onStartCommand(intent, flags, startId);
}
private class MyCounter extends CountDownTimer{
public MyCounter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
Intent intent = new Intent("timeout_action");
sendBroadcast(intent);
stopSelf();
}
#Override
public void onTick(long millisUntilFinished) {
// Need AlertDialog code here
Toast.makeText(getApplicationContext(), ("Time Remaining: " + millisUntilFinished/1000)+"", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDestroy() {
timer.cancel();
super.onDestroy();
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
The problem is that I can display the Toast without any problem but the AlertDialog is not displayed when called inside onFinish().
The first problem is to display the AlertDialog for whole application bearing in mind that the AlertDialog is displayed for some context. Also if somehow the AlertDialog is displayed then how to close the Application. On Activity I just close the activity by calling finish() so should I clear the Activities stack in this case?
The second complex part that I am facing is to display a popup when user click "Time remaining" link in the application which will show how much time is remaining for the Session to be timed out. This time should be exactly same as the time remaining in the service.
I can also use BroadcastReceiver and send update to the activity once the time is finished but wouldn't that be Activity specific because I want the timeout to act same regardless of which activity is user on. I want to avoid writing the same code on each activity.
Kindly guide me through with some solution.
If you use a fragment based design for your app, you can keep a root FragmentActivity in which all other elements of the app are displayed. This way you can use the context of the root FragmentActivity every time, to display your Dialog.
Additional: "Could you kindly refer to me some article.."
What you are doing is not common, and I would have to google search just like you to find any existing example similar to your case. I can however fill in a bit more detail on what I have proposed above.
If you are unfamiliar with using Fragments, read the Developer Documentation.
public class MainActivity extends FragmentActivity {
private static final int SPLASH_SCREEN_FRAGMENT = 0;
private static final int HOME_SCREEN_FRAGMENT = 1;
...
#Override
protected void onCreate(Bundle. savedInstanceState) {
super.onCreate(savedInstanceState);
// show your first fragment
Fragment splashFragment = new SplashFragment();
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, splashFragment).commit();
// Start your service using the context of your FragmentActivity
// Your FragmentActivity will always be the current activity, and you will display
// all other elements of your app inside it as fragments
Intent intent = new Intent(this, InActivityTimer.class);
startService(intent);
}
// method for switching the displayed fragment
private void fragmentSwitcher(int fragmentType) {
Fragment currentFragment = new Fragment();
switch (currentFragmentType) {
case SPLASH_SCREEN_FRAGMENT:
currentFragment = new SplashScreenFragment();
break;
case HOME_SCREEN_FRAGMENT:
currentFragment = new HomeScreenFragment();
break;
...
}
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, currentFragment).commit();
}
}
I have solved my issue with rather very simple approach.
#Override
public void onFinish() {
Intent intent = new Intent(getBaseContext(), TimeoutActivity.class);
startActivity(intent);
stopSelf();
}
and below is the onCreate method for my TimeoutActivity.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContextThemeWrapper ctw = new ContextThemeWrapper(TimeoutDialogActivity.this, R.style.Theme_Base_AppCompat_Dialog_FixedSize);
final AlertDialog alertDialog = new AlertDialog.Builder(ctw).create();
alertDialog.setCancelable(false);
alertDialog.setTitle("Session Timeout !");
alertDialog.setTitle("Your session has expired.");
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Logout", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
finish();
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
finish();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Renew Session", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
finish();
});
alertDialog.show();
}
I want to show another alert message(alert box/alert dialog) after the progress bar reaches 100%. How do I do that?
And Also is there any way to style that box (or both of them)?
Below is my code for an ProgressBar:
public class MainActivity extends Activity {
Button progress_button;
ProgressDialog pro_dialog;
Handler pro_handler;
int progress;
private static final int MAX_PROGRESS = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// intiliazing the buttons
progress_button = (Button) findViewById(R.id.button1);
progress_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Creating progress dialog interface setting
// title,progressstyle,max_progress
pro_dialog = new ProgressDialog(MainActivity.this);
pro_dialog.setTitle("Making everything OK is in progress! Please be patient.");
pro_dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pro_dialog.setMax(MAX_PROGRESS);
progress = 0;
pro_dialog.show();
pro_dialog.setProgress(0);
pro_handler.sendEmptyMessage(0);
}
});
// set onclick listener for buttons
pro_handler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (progress >= MAX_PROGRESS) {
pro_dialog.dismiss();
} else {
progress++;
pro_dialog.incrementProgressBy(2);
pro_handler.sendEmptyMessageDelayed(0, 100);
}
}
};
}
First of all, it would make more sense if you could replace:
pro_dialog.incrementProgressBy(2);
with this:
pro_dialog.setProgress(progress);
Current code dismisses dialog after progress variable reaches MAX_PROGRESS, but current value of this variable isn't presented by the progress dialog.
If you would like to show AlertDialog, you can do it for example after "pro_dialog.dismiss()".
Case of Progress Dialog styling has been discused here.
I have the following:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
populate();
handler = new Handler();
t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
doReload1();
populate();
}
});
}
}, 300, 30000);
}
private void populate() {
if (playlists.length != 0) {
MyListView = (ListView) findViewById(R.id.MyListView);
for (String item : playlists) {
Log.d("DEBUG", "item=" + item);
}
String[] adapterPlaylists = new String[playlists.length];
for (int i = 0; i < playlists.length; i++) {
adapterPlaylists[i] = playlists[i];
}
adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, adapterPlaylists);
MyListView.setAdapter(adapter1);
adapter1.notifyDataSetChanged();
MyListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v,
int position, long id) {
dialogwait = ProgressDialog.show(Playlist.this,
"Loading...", "Please wait..", true);
Intent i = new Intent(getBaseContext(), ViewPlaylist.class);
i.putExtra("id", idPlaylist[position]);
i.putExtra("timer", timerPlaylist[position]);
startActivity(i);
finish();
}
});
} else
System.out.println("playlist null");
}
#Override
protected void onPause() {
super.onPause();
System.out.println("onPause Playlist!!!!!!");
dialogwait.dismiss();
t.cancel();
}
The thing is that here:
dialogwait = ProgressDialog.show(Playlist.this,
"Loading...", "Please wait..", true);
I create a ProgressDialog and I dissmis it in onPause().
But onPause gets called right after onCreate() before I even the ProgressDialog is created.
Any idea why?ANy solution?Thanks
This is because a Dialog in Android, does not block - meaning that the thread running behind it (in this case your Activity and in particular your onItemClickListener) will continue to execute.
It looks like you want to display a loading dialog, to let the user know that the item he clicked is being loaded. I suggest you move that dialog to the next activity (the one started from onClick), and then display and dismiss the dialog from there.
I think that the problem could be that you are calling finish() in your OnItemClickListener. This will cause the current Activity to end as soon as you click on an item which, because of your onPause() implementation will immediately close the dialog.
Maybe you need to display the dialog when your ViewPlaylist Activity is created rather than in this Activity.
anything on top of your current activity (a dialog or any other activity) makes it a background activity, thus onPause is called. if anything, dialog.dismiss() should be called in activities' onResume. in your implementation, you're showing a dialog when a button is clicked, thus pausing your activity and calling dismiss. you should call dismiss only when the process associated with your dialog is finished, thus telling your user that you're ready to do something else - in your case launch another activity.
launch your activity inside your dialog's onDismiss.
for example:
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// start the other activity
}
});