How to know if a button is being pressed or released? - java

I have a little problem when I try to run my Android application. The problem occurs when I push & release a button on my main View. The application is to behave like a portophone (push the button to talk, release to stop).
To notify that the button is pressed or released, I've tried 2 options:
- Adding an onClickListener,
- Adding an onTouchListener.
The first only looks for the button being pressed, so it's not a viable solution. The second solution is able to differentiate between pushed & released, so it's the one I'm using now. The code looks like this:
// Initialise handler for Push To Talk button
Button button = (Button) findViewById(R.id.buttonPTT);
button.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent me){
switch(me.getAction()){
case MotionEvent.ACTION_DOWN:
Toast.makeText(getApplicationContext(), "PTT pressed", Toast.LENGTH_LONG).show();
// TODO: Activate Push To Talk
break;
case MotionEvent.ACTION_UP:
Toast.makeText(getApplicationContext(), "PTT released", Toast.LENGTH_LONG).show();
// TODO: End Push To Talk
break;
}
return false;
}
});
The problem lies in the ACTION_UP case of the switch. While running, it will only work when you press the button, move the cursor/finger/etc, and then release the button. What I want it to do is press it, and being able to release it without having to move my cursor/finger/etc.
Anybody have any ideas?

Nevermind, I already seem to have found the error. It seemed I still had an onClick handler set in my XML layout file, which I forgot to remove.
Thanks anyway for your time if you read this.

Related

Toggle only works the first time

I am trying to use the Toggle Button to play a sound when the button is "on" and stop the sound when the button is "off".
This seems to only work when I first toggle between the on/off button.
ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton1);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
sound1.start();
} else {
// The toggle is disabled
sound1.stop();
}
}
});
Because you called method stop().
There is the description of the method:
Calling stop() stops playback and causes a MediaPlayer in the Started, Paused, Prepared or PlaybackCompleted state to enter the Stopped state.
Once in the Stopped state, playback cannot be started until prepare() or prepareAsync() are called to set the MediaPlayer object to the Prepared state again.
Calling stop() has no effect on a MediaPlayer object that is already in the Stopped state.
How to play exactly right,you just need to visit this website of google. click me.
So the best thing that you can is to use a class constant to check if the flag is already set. You will need to save this to the savedCacheInstance when onPause/onStop/OnDestroy and then reload it. Something like:
boolean isMusicPlaying = false;
If you save this using savedInstanceCache in both onCreate & onStop/onDestroy, you can control the playback between rotations and start ups/exits. The class property is also inside the class scope of the listener so that any action you take, should update the class property. The best way to identify any issue is to of course, use the debugger. That way you can control the play functions and see which is breaking.

can not click action bar app icon Android

I'm trying to make the action bar app icon (top left image) clickable but it just doesn't work, I've already searched for some answers but nothing works. I've already tried to getSupportActionBar().setHomeButtonEnabled(true); and I can see the icon, but i still can't click on it. I know I can handle the event in the method onOptionsItemSelected(MenuItem item) but the event will never get triggered with my situation. I also don't get why I have to use getSupportActionBar(); instead of getActionBar()...the second one is always null. The minimum sdk is 16 and the maximum is 22. I read this answer -> ActionBarCompat - App icon action (click) not working on 4.0 devices but I don't know how to get in the ActionBarHelperICS.java class or if it apply to my case.
You haven't really posted any code. But there may be 2 problems.
You have to specify which is the parent activity in your manifest file.
Under the activity's tag in manifest, you'll have to specify which activity your home button will point to. Something like this:
android:parentActivityName="com.example.app.MainActivity"
Or Override your onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//add what you want to do here...
return true;
default:
return super.onOptionsItemSelected(item);
}
}

Pause Android app-flow

When a return button is pressed in the app I am working on:
public void clickReturn(View view)
{
// ...
// Call an event handler before finishing the activity
_appData.CustomDetail.hookBeforeFinish(this, new ArrayList<CompSubmission>(_submissions));
// Finish this activity
finish();
}
I am not able to modify clickReturn() - the way the application is structured, all I have access to is the hook hookBeforeFinish().
What I want to do is add a dialog to prompt for some input. I can do this in hookBeforeFinish(), but it only appears for a split second. I assume what is happening is I set up the AlertDialog builder, call builder.show() but finish() is being called directly afterwards - so the dialog only appears momentarily.
Is there anything I can put after builder.show() in the hook function such that it won't continue execution to finish()? If I can pause the application flow until someone presses the OK button on the dialog thatwould work better for me.
Thanks
Please comment finish().
Then read and add a dialog as explained here. In your positive button click (e.g. OK button), add finish();
Edit
Since you cannot override clickReturn() or change the class, you can use your hookBeforeFinish() to create a dialog and comment 'clickReturn();' line.
In your dialog, in the listener for the button which expects to finish the activity add clickReturn();.
This way you will pause the activity closing until user decides to do so.

Android Back Action Button Result in App Crash

I am building a new application which composed of 3 activities namely:
- Splash Screen
- Activity A
- Activity B, and
- Activity C
From activity A user can go to both activities indicated below:
A -> B -> C (from act A user can go to B then to C).
A -> C (from act A user can go straight to C).
B -> C (from B user can go to C).
i also pass Serializable intent Extra between activities.
The problem that i am having is whenever i pressed the back button on the Action Bar (Top Left Corner) it always makes my app crashes (Error: NULL Pointer Exception).
I have tried to place this code on ALL of my activity.
#Override
public void onBackPressed() {
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
}
I tried to somehow mimic the physical backbutton behaviour since it is working when user press physical backbutton. But somewhat throws error as well.
or
public void onBackPressed(){
super.onBackPressed();
}
or (well this one literally restart the app, which is discourage since it restart the app from splash screen).
public void onBackPressed(){
super.onBackPressed();
finish();
}
Does anyone know the appropriate way to implement back button?
The button on the top left corner is not the "Back" button, it would be the "up" button, and it's just a button in the action bar, onBackPressed refers to the hardware back button being pressed.
Navigation with back and up is not necessarily the same ("back" means go to where I was before, whereas "up" means go to the upper level in the app hierarchy).
Take a look at http://developer.android.com/design/patterns/navigation.html for more information.
(Also, try to avoid a splash screen, they are highly discouraged in android design patterns)
Edit: I forgot to mention how to actually handle the "up" button. You do that on your activity's onOptionsItemSelected:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
// Handle "up" button behavior here.
return true;
} else {
// handle other items here
}
// return true if you handled the button click, otherwise return false.
}
You can do something like this when the back button is called
public void onBackPressed(){
// Add data to your intent
finish();
startActivity(intent);
}
And similar in your onClick method for your action bar button.
I think, the problems is from passing value using intent.
If the value is intended to be use by all of your activity, I think the best way
is to use a sharedpreferences.
If You are using API level 16 or more than , Really No need to do anythinngggg,
i just Find the solution :
in manifest file with every other activity Except MainActivity Add meta-data like this :
android:name="android.support.PARENT_ACTIVITY"
android:value="com.gsetia.ohama.MainActivity"/>
with in Activity like this , For Example
<activity
android:name=".ViewReports"
android:label="#string/title_activity_view_reports"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.gsetia.ohama.MainActivity"/>
</activity>
And In Last , delete public boolean onOptionsItemSelected(MenuItem item) Method. That's it.
You will find your Back Button and will work fine

Prevent back button after logout in android

After logout the user is directed to login screen in android. Now, if user clicks on back button of phone it should stay on login screen itself.
How can I make it possible in android?
I have used following code in my application but it will close my application. It should stay on the login screen only
Intent objsignOut = new Intent(getBaseContext(),Hello.class);
objsignOut.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(objsignOut);
Please guide me the correct way.
override the onBackPressed in your login activity, to do nothing..
public void onBackPressed() {
//do nothing
}
It seems to me that there are simpler and cleaner solutions than overriding onBackPressed method, as mentioned here and here.
You can provide flags when launching a new activity (on login or logout) to simply clear the "back-stack" rather than override the behavior for the back-button:
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
This is a safer solution that can also be used after you log-in and not just after you log-out.
public void onBackPressed(){
if(appCanClose){
finish();
}
}
These functions can exist in both the system framework (used if not in your code), as well as in your code. If you leave it empty, the app will do nothing when the back button gets pressed.
In this example, when the boolean value appCanClse is true, the back button will quit the app, if false, the back button wil do nothing. I would make sure the user still has someway to quit the app. :p
You can do it by just adding this two line of codes
#Override
public void onBackPressed(){
moveTaskToBack(true);
}
It will prevent going back to previous activity as well as take the app to background when anyone hits back button
The actual solution is
#Override
public void onBackPressed() {
super.onBackPressed();
finishAffinity();
}
add this code in Login Activity. App closes when back button clicked in login page.

Categories