I have a game quiz, and if a user's answer is wrong a popup screen pops up and stays on screen for 3 seconds. I do this with Handler. Since the game is time limited, they come up with solution to press back button to remove popup from the screen :) and move along. So I disabled the back button for that popup activity. BUT, now I have another problem. It seems that my Handler count time from the last click, so if I click back button on that popup screen Handler count time from that click. If I click it again, it starts from beggining. I've tried to click it 10-12 times and my popup screen was on for half a minute. :) And that's not good. How to make my popup be on for 3 seconds no metter if click back button or not during his time on?
My popup class:
public class WrongAnswer extends Activity{
TextView wrong;
String correctAnswer, correct;
public final int delayTime = 3000;
private Handler myHandler = new Handler();
public void onUserInteraction(){
myHandler.removeCallbacks(closePopup);
myHandler.postDelayed(closePopup, delayTime);
}
private Runnable closePopup = new Runnable(){
public void run(){
finish();
}
};
#Override
public void onBackPressed() {
//do nothing
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.wrong);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
correct = extras.getString("correctAnswer");
}
inicijalizujVarijable();
myHandler.postDelayed(closePopup, delayTime);
}
private void inicijalizujVarijable() {
wrong = (TextView) findViewById(R.id.tvWrong);
Typeface pogresanFont = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
wrong.setTypeface(pogresanFont);
Wrong.setText("Wrong answer!\nCorrect answer is:\n\n" + correct);
}
}
Remove this:
public void onUserInteraction(){
myHandler.removeCallbacks(closePopup);
myHandler.postDelayed(closePopup, delayTime);
}
It's resetting your handler on any interaction, which results in the behaviour you describe.
As a side note, it seems rather heavy to dedicate an Activity to this functionality, I think you'd be better off using a Dialog or similar.
You can show popup as Dialog and setCancelable() to false.
http://developer.android.com/reference/android/app/Dialog.html#setCancelable(boolean)
Related
To show a pop up window i used this way :
Button b = (Button) findViewById(R.id.finish) ;
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,Pop.class));
}
});
code of pop.java
public class Pop extends Activity {
#Override
protected void onCreate(Bundle savedInstanceSate) {
super.onCreate(savedInstanceSate);
setContentView(R.layout.popup);
DisplayMetrics dm = new DisplayMetrics() ;
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels ;
int height = dm.heightPixels ;
getWindow().setLayout( (int)(width*.6),(int)(height*.4) ) ;
I want my button to do some work too as soon as it is pressed so where should i write the method for that and can i use onclick() for that ?
Thank You :)
Your first code snippet must be placed inside the onCreate() callback of the calling activity (in your case it seems MainActivity), after the setContentView() call.
If you need to display a popup I suggest you to use Dialogs https://developer.android.com/guide/topics/ui/dialogs.html
You can write your method after the onClick, before changing the activity or within the new activity in the onCreate method.
I am very new to Andriod Programming and this is probably very basic question.
In my Application, the first page contains just button (for simplicity) login button.
After the user clicks login button it displays the toast and then I need to navigate to new class(page B) where I want to connect to a specific health sensor.
Problem
1. I tried implementing the just the basic part with onClickListener for button and then when clicked, go to next page, where enable Bluetooth,etc. I could not get to next page
MainActivity.java :
public class MainActivity extends AppCompatActivity {
Button button;
PollingTest pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(),"Logged In",Toast.LENGTH_SHORT).show();
pd = new PollingTest();
pd.call();
}
});
}
}
Second Page (Where wanted to Control BT). Never got to this page while testing on the tablet: -
For now just included if I could get a Toast atleast from this page: -
public class PollingTest extends Activity {
BluetoothAdapter btAdapter;
Button btn2;
protected void call() {
//super.onCreate(savedInstanceState);
//setContentView(R.layout.pairinglistactivity);
btn2 = (Button)findViewById(R.id.pollB);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_LONG).show();
}
});
}
}
Here app crashes after clicking on Login button in first page.
I have actually got some different errors with different code, I was not able to make proper Toast or turn BT on in the second page as it was trying them in static method.( very Confusing:( )
Please help me. I know this v v basic Q..
EDIT:
Sorry, this Q is already answered here: -
Moving from one activity to another Activity in Android
You don't start an activity by instantiating it like a normal Java class. So this is wrong
pd = new PollingTest();
pd.call();
you should be using an Intent
and follow the Activity Lifecycle
so you would want something like
Intent i = new Intent(MainActivity.this, PollingTest.class);
startActivity(i);
then override onCreate() in PollingTest.java and put what is in call() in there or call that method from onCreate().
Also, a Toast should use Activity Context
I'm trying to show a "Loading" dialog before the async task starts working. With the following code what happens is that the dialog doesn't show untill all the async task is done his operations, the dialog is being prompted only in the end.
Here's the code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
loadMap();
progressBar = ProgressDialog.show(Map.this, "",
"Loading. Please wait...", true);
//firing the asynctask here
}
The asynctask is doing pretty heavy operation, it takes like 10 seconds till I'm able to see the layout, that's why I want to prompt the user with a "Loading" dialog. but the user is able to see it only in the end of the asynctask operations for some reason.
What should I do?
EDIT: Forgot to mention that in the onProgressUpdate I'm doing some UI operations (Adding the overlays to the mapview). That's why the UI is freezing probably. but I just want to know how to show the loading dialog before, I don't care if the UI freezes after the "loading" dialog shows. Actually I do care, but I don't know if there's any better solution.
EDIT2: The loadmap function:
public void loadMap()
{
mapView = (TapControlledMapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.animateTo(new GeoPoint((int)(47.975 * 1E6), (int)(17.056 * 1E6)));
mapView.setOnSingleTapListener(new OnSingleTapListener() {
#Override
public boolean onSingleTap(MotionEvent e) {
itemizedOverlay.hideAllBalloons();
return true;
}
});
myLocationOverlay = new FixedMyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
mapView.invalidate();
zoomToMyLocation();
editText = (EditText)findViewById(R.id.search);
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus)
onSearchRequested();
EditText editText = (EditText)v;
editText.clearFocus();
}
});
}
Have you tried moving loadMap() in to the asynctask ?
I'm trying to code an onClickevent button on screen 1 that makes
a spinner visible or invisible, depends of the needs, on screen 2 as a result.
Knowing that on screen 1 there are several buttons which uses the same views
or widgets on the second screen, I was thinking about it to use one screen for
all these activities.
It would be nice if someone knows and explain to me how to solve this problem.
I will attach the java code just to look at it.
public class screen1 extends Activity {
private View spinner1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.screen1);
spinner1 = findViewById(R.id.spinner1);
Button A = (Button) findViewById(R.id.b_A);
// error output: Cannot instantiate the type View.OnClickListener
A.setOnClickListener(new View.OnClickListener());
A.setOnClickListener(mVisibleListener);
}
#Override
// error output behind the line 'public void':The method onClick(View) of type screen1 must override or implement a supertype method
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent("com.jack.test.SCREENMENU"));
}
OnClickListener mVisibleListener = new OnClickListener(){
public void onClick(View v){
spinner1.setVisibility(View.VISIBLE);{
};
// the rest is ok from here to down.
You seem to have some major glitches going on with the code in addition to what you are asking. Fortunately, if I understand you correctly, the thing you want is easy to fix:
#Override
public void onClick(DialogInterface dialog, int which)
{
if (need_is_met)
{
if (spinner1.getVisibility() == View.INVISIBLE)
view.setVisibility(View.VISIBLE);
else
view.setVisibility(View.INVISIBLE);
}
}
need_is_met is a boolean ... thats as far as i could get with your statement "depends of the needs"
as far as the rest of your code, it should read like this:
public class screen1 extends Activity
{
private View spinner1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
boolean need_is_met = true; // you can change this or have it set based on something later if you want
spinnerAutomerk = findViewById(R.id.spinnerAutomerk);
button_A = (Button) findViewById(R.id.b_A);
button_A.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (need_is_met)
{
if (spinnerAutomerk.getVisibility() == View.INVISIBLE)
spinnerAutomerk.setVisibility(View.VISIBLE);
else
spinnerAutomerk.setVisibility(View.INVISIBLE);
}
}
}
}
}
something like that. i took out all the requestWindowFeature, windowFlag etc because it is much neater to put this into your manifest:
...
<application
android:icon="#drawable/icon"
android:label="#string/app_name"
>
<activity
android:name=".Screen1"
android:label="#string/app_name"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen"
...
that last line, the theme bit, will set you up with any one of a number of themes (such as dark, light, transparent etc. just got to R.style and ctrl-F for theme and youll see there is a number to choose from. similar to this they can kill the title and notification bar, if you wish.
also i didnt to set net_is_met to something because i dont know what the rest of your code is about.
First off all you need to have screen2 as another activity if you want it to open when clicked and show the spinner (not sure if that is exactly what you meant).
You should use intents to switch to screen2's activity. There a billion examples on how to do that if you google it.
You would use a Boolean to check if certain requirements are met or not:
Boolean Reqs = false;
If(req_met){
Reqs = true;
} else {
Reqs = false;
}
Use that type of format then check if Reqs is true or not when sending the intent to see if the spinner is visible or not (I would use another intent for that)
I'm designing a music player app for Android that will feature pop-up controls. I'm currently trying to get these controls to close after a certain period of inactivity but there doesn't seem to be a clearly documented method of doing this. So far I have managed to cobble the following solution together using a few suggestions both from this site and others.
private Timer originalTimer = new Timer();
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.playcontrols);
View exitButton = findViewById(R.id.controls_exit_pane);
exitButton.setOnClickListener(this);
View volUpButton = findViewById(R.id.controls_vol_up);
volUpButton.setOnClickListener(this);
View playButton = findViewById(R.id.controls_play);
playButton.setOnClickListener(this);
View volDownButton = findViewById(R.id.controls_vol_down);
volDownButton.setOnClickListener(this);
musicPlayback();
originalTimer.schedule(closeWindow, 5*1000); //Closes activity after 10 seconds of inactivity
}
And the code that should close the window
//Closes activity after 10 seconds of inactivity
public void onUserInteraction(){
closeWindow.cancel(); //not sure if this is required?
originalTimer.cancel();
originalTimer.schedule(closeWindow, 5*1000);
}
private TimerTask closeWindow = new TimerTask() {
#Override
public void run() {
finish();
}
};
The above code makes perfect sense to me but it force closes upon any user interaction. It does however close normally if untouched and won't close after interaction if I remove the second schedule, so this seems to be the problem. Also note that I imagine I will be moving this timing task to another thread to help keep the UI snappy. I need to get it working first though :D. If there's any more info I need to supply please ask and thanks for any help...Ye guys are brilliant!
Based on #CommonsWare's suggestion, switched to a Handler. Works perfectly. Thanks very much!
private final int delayTime = 3000;
private Handler myHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.playcontrols);
View exitButton = findViewById(R.id.controls_exit_pane);
exitButton.setOnClickListener(this);
View volUpButton = findViewById(R.id.controls_vol_up);
volUpButton.setOnClickListener(this);
View playButton = findViewById(R.id.controls_play);
playButton.setOnClickListener(this);
View volDownButton = findViewById(R.id.controls_vol_down);
volDownButton.setOnClickListener(this);
musicPlayback();
myHandler.postDelayed(closeControls, delayTime);
}
and the other methods...
//Closes activity after 10 seconds of inactivity
public void onUserInteraction(){
myHandler.removeCallbacks(closeControls);
myHandler.postDelayed(closeControls, delayTime);
}
private Runnable closeControls = new Runnable() {
public void run() {
finish();
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}
};
To complete the answer above, note that the Activity.onUserInteraction() is adequate only if you care about clicks.
The documentation at http://developer.android.com/reference/android/app/Activity.html#onUserInteraction%28%29 states: "Note that this callback will be invoked for the touch down action that begins a touch gesture, but may not be invoked for the touch-moved and touch-up actions that follow."
Actual implementation proved it indeed ignores all movements on the tablet, which means the clock is never reset while, say, drawing without releasing the finger. On the other hand, it also means that the clock is not reset too often, which limits the overhead.