First, sorry for my low programming skills.
I'm trying to write my first Java application for Android (actually I never studied Java but I get along with that most of all).
Anyway, I'm trying to make this app closing on Back button press. This is the code, with errors [1][2][3].
#Override
[1] public boolean onKeyDown(int keyCode, KeyEvent event)
{
[2] if ((keyCode == KeyEvent.KEYCODE_BACK))
{
[3] finish();
}
return super.onKeyDown(keyCode, event);
}
/**
* [1]KeyEvent cannot be resolved to a type
* [2]KeyEvent cannot be resolved to a variable
* [3]Cannot make a static reference to the non-static method finish() from the type
Activity
*/
Thank you all :)
You need to import KeyEvent package which is android.view.KeyEvent... import android.view.KeyEvent;
Everytime you use a class which comes from a different package of java (java.lang is the default) you should add import to say to the compiler where it should take the class. Eclipse/IntelliJ IDEA/Netbeans help you to import packages by using a simple key combination so use one of them if you can.
For error 3: Your return is out of the method body!
What is a package?
If you want to learn more about android dev, read this.
If you are using an activity, try overriding the method obBackPressed
public void onBackPressed ()
Added in API level 5 Called when the activity has detected the user's
press of the back key. The default implementation simply finishes the
current activity, but you can override this to do whatever you want.
#Override
public void onBackPressed(){
// Do some stuff
finish();
super.onBackPressed();
}
That would save you some trouble.
Related
I am wondering if there is any solution for method dependency of this object and the supper object. I am now working in android, and overriding the onBackPressed method.
I have created a class called ActivityContainer, used to handle universal behaviors. the logic of the onBackPressed of this class is
Close the menu if the menu is currently opening
Prompt if going to close the app, yes to close, no or no action to stay
Then, I have an other class called FragmentActivityContainer extends ActivityContainer, used to handle universal behaviors that used in fragment. the logic of the onBackPressed of this class id
Close the menu if the menu is currently opening
Back the previous fragment if changed fragments in content area
Prompt if going to close the app, yes to close, no or no action to stay
the dependency is messy. Let's take a look for ActivityContainer first
#Override
public void onBackPressed(){
if(this.menu != null && this.menu.isShowing()){
this.menu.close();
} else {
this.promptQuite();
}
}
nice and clear, works fine.
Let's have a look for FragmentActivityContainer
#Override
public void onBackPressed(){
if(this.menu != null && this.menu.isShowing()){
this.menu.close();
} else if(this.fragmentManager.getBackStackEntryCount() > 0){
super.getParent().onBackPressed();
} else{
this.promptQuite();
}
}
it works, but eagerly. I would like to use super.onBackPressed() in FragmentActivityContainer but since back to previous fragment is in the middle between menu close and prompt quite, there is no way for me to do that. What is the best solution to solve this dependency problem?
I have 15 or so activities. Each one of them has a method, and I want to play audio in that method. Now, I have the obvious option to copy and paste the following line of code into each and every one of my activities Now, if I wanted to change something, I would have to go back into each and every one of my activities again. Here is the code:
MediaPlayer pop = MediaPlayer.create(CurrentActivity.this, R.raw.pop);
pop.start();
So, after searching the web for a few hours, I found that most people would just copy and paste it into each activity. So, I put the line of code (above) into a separate java class (which was a service by the way) tried to call that method in the service every time I needed to play the audio. So, I did the following:
public class TwentySeconds extends Service{
public void myPop(View view){
MediaPlayer pop = MediaPlayer.create(TwentySeconds.this, R.raw.pop);
pop.start();
}
}
Now, I got the error non static method cannot be referenced from static context. So, naturally, I tried to make method myPop static. Then, I got the error on TwentySeconds.this about being referenced from static context. So, it seems I am stuck. Changing the methods to static can't work, as I am trying to use an instance of the class as well using this. So, how should I go about calling method myPop where the MediaPlayer can successfully play?
Thanks for the advice,
Rich
Typically, if a utility method needs a Context, it is passed in.
public class Utilities {
public static void myPop(Context context){
MediaPlayer pop = MediaPlayer.create(context, R.raw.pop);
pop.start();
}
}
Utilities.myPop(CurrentActivity.this);
In one of my Android projects (but not necessarily tied to Android) I have quite a few method calls that really do nothing but blow up the code and could be automatically removed. Examples:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public void onDestroy() {
super.onDestroy();
}
I couldn't find any inspections that help me in automatically removing these expressions, so I tried structural search. My attempt so far: I copied the template of 'annotated methods' and made 2 small changes.
$Annotation$ changed to occurs=1, text=Override
Added a $Statement$ variable with occurs=1
The template code:
class $Class$ {
#$Annotation$( )
$MethodType$ $MethodName$($ParameterType$ $ParameterName$) {
$Statement$;
}
}
So far, so good - it's only finding methods with a single line in the body. But now I want to explicitely search for exact statements calling the super method (kind of like a back reference to $MethodName$), but which also return the super value (when not void). Any ideas?
I believe this would be a really useful inspection that could be integrated into the main IntelliJ codebase as well. :-)
So I recently found out that IntelliJ's 'Empty method' inspection actually looks for this. Simply:
Double Shift -> Run Inspection By Name -> Empty method
The synopsis is 'Method only calls its super', but the inspection actually looks for more than just this, for example:
The method and all its derivables are empty
All implementations of this method are empty
The method is empty
Empty method overrides empty method
Depending on your situation it might find more than you want - and the refactoring tried to remove more than I actually wanted. But with a quick manual review you should be good to go. :-)
Using Structural Search you will have to use two separate searches. One for finding methods with void return type:
class $Class$ {
$MethodType$ $MethodName$($ParameterType$ $ParameterName$) {
super.$MethodName$($ParameterName$);
}
}
and a second for methods which return a value:
class $Class$ {
$MethodType$ $MethodName$($ParameterType$ $ParameterName$) {
return super.$MethodName$($ParameterName$);
}
}
Specifying the #Override annotation is unnecessary in this case.
I started learning how to create an app on Android. I have a bit of knowledge on Java already, and now I'm trying some of the activity events.
I know how to use onCreate or onCreateOptionsMenu, and now I'm testing out onStop:
#Override
public void onStop(){
//a function that simply creates and return an AlertDialog.Builder object
displayPopup("Event", "Stopped", "OK").show();
}
I thought this would work since there's no error at compile time. But when I try to exit the app, I expect a popup dialog would show up but instead the app just crashed. It turns out that I need one extra line to make it work:
super.onStop();
It doesn't do anything (at least I can't see anything changed) and it's kind of useless, but without this line the app just keeps crashing.
Any help would be great, thanks.
It calls the onStop() method in the parent Activity class. When you look at the source code, you'll see that it does some internal housekeeping.
protected void onStop() {
if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStop " + this);
if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
getApplication().dispatchActivityStopped(this);
mTranslucentCallback = null;
mCalled = true;
}
Your custom Activity extends the type Activity. The onStop() method is part of the super class activity. If you don't call super.onStop() the implementation on the Activity class is never called, and only your implementation is. This implies crashes since the onStop() method in the Activity classperforms clean ups that must be called.
The android reference on onStop() : http://developer.android.com/reference/android/app/Activity.html#onStop()
Your class is an activity subclass (extends Activity), witch mean that you must call super method of the activity mother class for more information about details of super.onstop() you can check the source code
I've created a few minor apps for Android while learning. Being a PHP developer, it's a challenge to get used to it.
I'm especially wondering how I could define a couple of "general" functions in a separate class. Eg I have a function that checks if network connection is available, and if not, shows a dialog saying that the user should enable it. Currently, that function exists in several of my activities. Of course that seems strange - I suppose it would be more logical to define it once and include it in the activites where needed.
I tried putting it in a new class, and included that class in the original activity. But that failed since eg getBaseContext() is not accepted anymore.
I'm wondering how to go ahead. What should I be Google-ing for ? What is this mechanism called?
You need to create class with static methods. Like this
public class HelperUtils {
public static void checkNetworkConnection(Context ctx) {...}
}
Then you can call it from any place like this:
HelperUtils.checkNetworkConnection(this.getContext());
Assuming current class has Context.
You should read books on general OOP concepts where different type of methods are explained.
You can for example create a class - let's call it NetworkUtils. In this class you can create static method boolean isNetworkConnectionAvailable() and return true if is available and false otherwise. In this class you can create another static method void showNoConnectionDialog(Activity activity) - and in this method you create dialog starting with
public static void showNoConnectionDialog(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//setting message, listener etc. and finally
builder.create().show();
}
In your activity, where you want to check and handle network connection you should call:
if (!NetworkUtils.isConnectionAvailable(getApplicationContext())) {
NetworkUtils.showNoConnectionDialog(YourActivityClassName.this)
}
I guess this should work.