Overridden function working in activity but not working in fragment - android

Which function can be overridden in activity and which one in fragments.
As onKeyDown function overridden in fragment was not working while it was working after overriding it in the activity

Refer to the Fragment and Activity documentation. Methods that are defined as final are not overridable. If they don't have the world final then you can override them no problem.
Just make sure to also run super method, as some of them require that (you'd get exception for those that do if you don't)

Related

Why does this make my app crash and what's the appropriate solution?

I have a button that I want to change its value often, so my Activity has a private variable :
private Button p1_button = (Button)findViewById(R.id.firstbut);
This simple line makes my app crash. If I put inside the onCreate it works and I can interact with the button (change text etc).
EDIT : I think I found the reason. I should initialize AFTER setcontentview ?
EDIT: Thank you for the constructive answers. I have now a different problem I removed the initialization and I did it on onCreate and it works (But I keeped the p1_button declaration as a private field). But when I tried to modify the button in a different method of my activity (just changing the text), it crashes again. So the return value of findViewById is "local" to the method where it is called and I should setcontentview in every method that access UI elements ?
Do not call findViewById() until after you call setContentView(). Otherwise, the widget will not exist.
More generally, do not call inherited methods on Activity until after super.onCreate(), unless specifically advised to do so.
It depends where you are calling this line.
http://i.stack.imgur.com/6EQaU.png
The onCreate() method contains a call to setContentView() and before this is called, Android has no idea what to do with your button as it hasn't been inflated yet!
Therefore as a really easy rule of thumb, always make sure setContentView (or if you're dealing with fragments onCreateView()) have been called and completed. Only then will findViewById() work.
If you would like further guidance, please post some code in which the crash occurs.
edit: I tried to add the image properly but don't have enough rep.
To understand this you need to know the Activity lifecycle. You are trying to look a view which has not yet been created by Android.
As per the android lifecycle explained here "http://developer.android.com/training/basics/activity-lifecycle/starting.html". In onCreate() method the activity is created and you can access different views of the activity. If you will try to look for view before onCreate() the app will crash as it does not know whether that view exists or not.

Would it be wrong to call System.LoadLibrary() from onCreate method of a fragment?

I am trying to use this solution inside my Fragment, however I couldn't be sure where to call System.LoadLibrary(), finally I decided to call from onCreate method of the Fragment, I want to be sure if this would not raise some another weird error on different devices.
General it won't cause weird behaviours, as onCreate is mandatory callback when your fragment created by system. This make sure your native library is prepared before you do further operation in your fragment.
Take a look at fragment life cycle, it might be better if you put your library initialize routine on the first callback onAttach, you can use the attached Activity context to initialize your native library.
It is just a static initialization. You don't even have to have it inside your onCreate() at all. You can simply initialize it as the first part of your class next to your global variables as such:
class YourClass
{
static
{
System.loadLibrary( yourLib );
}
...
}
It is only important that it is done early or you may see UnsatisfiedLinkError followed by application's crash. That way whenever a call referenced later is made, the library itself has already been loaded. A static declaration at the top will do that as soon as an instance of the class has been requested; even before onCreate().

Unimplemented OnCreate() method does not give an error

package com.example.mytests;
import android.app.Activity;
public class MainActivity extends Activity {}
For the code above, even though I do not implement OnCreate() method I get no errors and program works. Should't I get an error that I should override it?
No. You will get error if you override onCreate and forget to call super.onCreate first thing.
In your case just Activity.onCreate() gets called. It can't really give an error, unless they in Google break something severily which they do not. If it gave Android wouldn't work because the same error would come from super.onCreate()
No, you don't need to override it. But if you DO override it, you MUST call super.onCreate().
The idea is that no matter what, the default implementation of onCreate() must be called, which is also the case if you do not override it at all.
onCreate is one of the Life Cycle methods of the Activity
Reason we implement the onCreate because some where we need to set the content view to the activity. For that reason we choose onCreate for setContentView() and it is the first life cycle method to be called. and if you override the onCreate dont forgot to call the super.onCreate()
why super.onCreate
You are extending class which has already defined onCreate method so overriding indicates to use your behavior.otherwise super class behavior will b used.this is same as extend thread class and not override run method.here do nothing run method will b invoked when u call start method on thread . You might be confused in implementing and extending interface or class.

super.onCreate(savedInstanceState);

I have created an Android Application Project and in MainActivity.java > onCreate() it is calling super.onCreate(savedInstanceState).
As a beginner, can anyone explain what is the purpose of the above line?
Every Activity you make is started through a sequence of method calls. onCreate() is the first of these calls.
Each and every one of your Activities extends android.app.Activity either directly or by subclassing another subclass of Activity.
In Java, when you inherit from a class, you can override its methods to run your own code in them. A very common example of this is the overriding of the toString() method when extending java.lang.Object.
When we override a method, we have the option of completely replacing the method in our class, or of extending the existing parent class' method. By calling super.onCreate(savedInstanceState);, you tell the Dalvik VM to run your code in addition to the existing code in the onCreate() of the parent class. If you leave out this line, then only your code is run. The existing code is ignored completely.
However, you must include this super call in your method, because if you don't then the onCreate() code in Activity is never run, and your app will run into all sorts of problem like having no Context assigned to the Activity (though you'll hit a SuperNotCalledException before you have a chance to figure out that you have no context).
In short, Android's own classes can be incredibly complex. The code in the framework classes handles stuff like UI drawing, house cleaning and maintaining the Activity and application lifecycles. super calls allow developers to run this complex code behind the scenes, while still providing a good level of abstraction for our own apps.
*Derived class onCreate(bundle) method must call superclass implementation of this method. It will throw an exception SuperNotCalledException if the "super" keyword is not used.
For inheritance in Java, to override the superclass method and also to execute the above class method, use super.methodname() in the overriding derived class method;
Android class works in the same way. By extending the Activity class which have onCreate(Bundle bundle) method in which meaningful code is written and to execute that code in the defined activity, use the super keyword with the method onCreate() like super.onCreate(bundle).
This is a code written in Activity class onCreate() method and Android Dev team might add some more meaningful code to this method later. So, in order to reflect the additions, you are supposed to call the super.onCreate() in your Activity class.
protected void onCreate(Bundle savedInstanceState) {
mVisibleFromClient = mWindow.getWindowStyle().getBoolean(
com.android.internal.R.styleable.Window_windowNoDisplay, true);
mCalled = true;
}
boolean mVisibleFromClient = true;
/**
* Controls whether this activity main window is visible. This is intended
* only for the special case of an activity that is not going to show a
* UI itself, but can't just finish prior to onResume() because it needs
* to wait for a service binding or such. Setting this to false prevents the UI from being shown during that time.
*
* <p>The default value for this is taken from the
* {#link android.R.attr#windowNoDisplay} attribute of the activity's theme.
*/
It also maintains the variable mCalled which means you have called the super.onCreate(savedBundleInstance) in your Activity.
final void performStart() {
mCalled = false;
mInstrumentation.callActivityOnStart(this);
if (!mCalled) {
throw new SuperNotCalledException(
"Activity " + mComponent.toShortString() +
" did not call through to super.onStart()");
}
}
See source code here.
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/1.5_r4/android/app/Activity.java#Activity.onCreate%28android.os.Bundle%29
Because upon super.onCreate() it will reach the Activity (parent class of any activity) class to load the savedInstanceState,and we normaly don't set any saved instance state, but
android framework made such a way that, we should be calling that.
It is information you want returned to your application, via onCreate(),
if the activity is destroyed and restarted due to some implicit reason
(e.g., not because the user pressed the back button). The most common
use of onSaveInstanceState() is to handle screen rotations, as by
default, activities are destroyed and recreated when the user slides out
the G1 keyboard.
The reason to call super.onCreate(savedInstanceState) is because your
code will not compile otherwise. ;-)

Accessing the Activity from a Fragment

I'm trying to change the activity title from a fragment (in this case, it's an android.support.v4.app.Fragment). To this end, I save the activity in an attribute on the fragment when onAttach() is called on the fragment. According to the docs, onAttach() should be called before onCreateView(), which I'm using to request some data used to fill up the view. When I kick off the thread for the network retrieval, I want to indicate that in the title, so I'm trying to call this.activity.setTitle() from the Fragment. However, that keeps throwing a NullPointerException. What am I missing here?
You can access the Activity in a Fragment using getActivity(). It can be called safely as soon as onActivityCreated() was called on the Fragment. Before that, it might not be there or might not have been fully initialized yet.
If your thread starts before that, just note the fact somewhere in your Fragment and only change the title after onActivityCreated was called.
Nowadays you can call requiredActivity() too that return FragmentActivityobject and if fragment doesn't come from an Activity, method throws a IllegalStateException

Categories

Resources