In the docs, it says I should make the new class like this:
class MyView extends GLSurfaceView {
public MyView(Context context) {
super(context);
setRenderer(renderer);
}
}
Now I tried to re-do that in Scala:
class BaseGameActivity extends Activity {
object glview extends GLSurfaceView(this) {
setRenderer(renderer)
setEGLContextClientVersion(2)
}
}
However, the App crashes now with the exception "java.lang.IllegalStateException: setRenderer already called for this instance". I suspect this has to do with the way Scala calls the super-constructor.
I've tried to find out how to override the constructor in the way the docs describe, but couldn't find it. I'd appreciate any hint.
It seems to me that your are propagating the call to a different constructor from the base class. You are passing a reference to this instead of a reference to the Context object. It might be that this other constructor is calling setRenderer.
Could you try to create an inner class MyGLView like this:
class MyGLView(ctx: Context) extends GLSurfaceView(ctx) {
setRenderer(renderer)
}
And see what happens?
The problem is that object does not allow arguments to its constructor. Top-level objects must be initializable without any arguments (nobody calls their ctors). In your case you have an inner object, which can reference the members of the surrounding class instance. If you really need an inner object in your Activity class, you could do:
object glview extends GLSurfaceView(ctx) {
setRenderer(renderer)
}
where ctx is a member of the surrounding class.
In java likewise in scala constructors are not inherited.
So you can not override thing, you didnt inherit. And you should use one of existing constructors for base class. If all of them are calling setRenderer(renderer) it will be called during constructing super object and you obviously should not call it second time in a subtype constructor ( wheither it class, object or mixing-in trait ).
Related
I want to define a class with just one constructor with body . When i set parameter of class i can't define the body of primary constructor.
I want the class have only one constructor.
Foe example
I have a class that extends CursorWrapper. This class have parameter that need to superclass implementation. I need a constructor with one parameter that do it:
class wrapper(cursoe: Cursor): CursoreWrapper {
// i need to call super(cursor). But where?
}
If you want to call cursor, it means your CursorWrapper (clearly typo here) is at least an abstract class, and not an interface.
Judging by your question, it also receives cursor (another typo) as an argument, so we get something like this:
open class CursorWrapper(cursor: Cursor)
Now, to invoke this constructor, you simply call it when you inherit from the class:
class Wrapper(cursor: Cursor): CursorWrapper(cursor) // <- this is your super(cursor)
Now let's assume that you also have another function on CursorWrapper that you need to call during construction.
open class CursorWrapper(cursor: Cursor) {
fun bla() {
// You want to call this for some reason as super.bla()
}
}
You can use init() block for that.
class Wrapper(cursor: Cursor): CursorWrapper(cursor) {
// i need to call super(cursor). But where?
init {
super.bla()
}
}
I have a class called myConstants and in it i list all my constants so when i need them I just reference MyConstants.MYCONSTANT. However, i would like to implement something like this for methods. i am repeating a lot of code, for instance, i have a formatCalendarString(Calendar c) method in 3 activities. seems redundant and unecessary. but i cant make them static because i get static calling non-static errors and the only other way i can think is to make a MyConstant object then call public functions off that object, like this...
MyConstants myConstants = new MyConstants();
myConstants.formatCalendarString(Calendar.getInstance());
is there some way i can just call the formatCalendarString() inside MyConstants class without generating an object?
You can use singleton pattern to cache instances. Keeping methods in something like parent activity does not make any sense (as primary role of activity is user interaction).
Example:
public class MyConstants {
private static MyConstants ourInstance;
private MyConstants() {
//private constructor to limit direct instantiation
}
public synchronized static MyConstants getInstance() {
//if null then only create instance
if (ourInstance ==null) {
ourInstance = new MyConstants();
}
//otherwise return cached instance
return ourInstance;
}
}
You just need a private constructor and public static method that would only generate instance if it is null.
Then, call MyConstants.getInstance().whateverMethod(). It will create only single instance.
However when using singleton, please keep memory leaks in mind. Do not pass activity context directly inside singletons.
If you want to have all methods in activities, you can put then in abstract class BaseActivity, which extends Activity, and then make your activities extends BaseActivity. However, if these methods doesn't correspond to something about activity, I suggest some Singleton or Util class
I agree with Pier Giorgio Misley. It's also good to add a private constructor, because you don't obviously want to instantiate an object.
Can't you just use a parent class? That way you can just inherit the methods and manage in one source. Then you don't have to use static functions then.
Edit: Like Tomasz Czura said, just extend the Class.
public class ParentClass {
public void commonMethod(){
}
}
public class OtherClass extends ParentClass{
}
You can use the Static keyword.
Static methods can be referenced from outside without istantiating the new object.
Just create a class:
public class MyClassContainingMethods{
public static String MyStaticMethod(){
return "I am static!";
}
}
Now call it like
String res = MyClassContainingStaticMethods.MyStaticMethod();
Hope this helps
NOTE
You CAN call non-static from static by doing something like this:
public static void First_function(Context context)
{
SMS sms = new SMS();
sms.Second_function(context);
}
public void Second_function(Context context)
{
Toast.makeText(context,"Hello",1).show(); // This i anable to display and cause crash
}
Example taken from here, you will obiouvsly have to fit it into your needs
Apologize :-
due to my mistake, because last time i didn't asked this Question properly and that's why most of the answers posted below are related to "this" keyword and that's the reason i got that much down votes. So i updated this Question, because i don't want to misguide anyone.
.
EDIT-1 :
Question-1 My question was that why we pass "this" (Object of current class or MainActivity) twice in the GestureDetectorCompact() Constructor
new GestureDetectorCompat(this,this);
Rest of the block of code is given below,
public class MainActivity extends ActionBarActivity implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener {
protected void onCreate(){
private GestureDetectorCompat gestureDetector;
this.gestureDetector = new GestureDetectorCompat(this,this);
gestureDetector.setOnDoubleTapListener(this);
}
}
EDIT-2 : for quite close answer you can click at following link
EpicPandaForce
's answer is very close to my question and it is helpful as well.
The this keyword, which exists in many OOP languages, is a reference to the current instance of the object in which you are contained in memory..
Your example:
this.gestureDetector = new GestureDetectorCompat(this,this);
You are basically saying:
This instance - access gestureDetector is equal to a new instance of GestureDetectorCompat that is constructed with 2 paramaters, in this case, both of them references to this instance of MainActivity.
As people are saying, this is a fundamental principal and it may be more beneficial for you to start with building a strong foundation in Java before moving on to Android.
If you want to understand this, probably you should read this.
Android is a Java based platform and a good Java/OOP knowledge is required in order to make (native) apps.
I strongly suggest you to read at least one Java/OOP book/tutorial. Some good examples are:
Bruce Eckel, Thinking in Java (a great classic)
Oracle Java Tutorial
Object Oriented Programming on Wikibooks (no specific language)
Good learning!
public class MainActivity
extends
ActionBarActivity
implements
GestureDetector.OnGestureListener,
GestureDetector.OnDoubleTapListener {
private Context context;
private GestureDetector.OnGestureListener onGestureListener;
private GestureDetector.OnDoubleTapListener onDoubleTapListener;
private GestureDetector gestureDetector;
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
this.context = this; //mainActvity instance as a context
this.onGestureListener = this; //mainActvity instance as GestureDetector.OnGestureListener
this.onDoubleTapListener = this; //mainActvity instance as GestureDetector.OnDoubleTapListener
//the gesture detector of this activity instance
this.gestureDetector = new GestureDetectorCompat(context, onGestureListener);
//activity as context
//activity as onGestureListener
gestureDetector.setOnDoubleTapListener(onDoubleTapListener);
//activity as double tap listener
}
}
For more information, read about the constructor of GestureDetectorCompat here
Here,
this.gestureDetector = new GestureDetectorCompat(this,this);
the first "this" is referring the 'context' and second "this" is referring to the 'listener'.
You can have a look on this,
public GestureDetectorCompat(Context context, OnGestureListener listener) {
this(context, listener, null);
}
GestureDetectorCompat is the constructor in which we are passing the two "this" keywords, meaning first is context(which refers to the object of current class) and the second one is the listener.
Definition of GestureDetectorCompat constructor is,
GestureDetectorCompat(GestureDetector.OnGestureListener,
GestureDetector.OnDoubleTapListener) { }
So There is need of 2 arguments to call this function. In your case MainActivity is implementing both the Listener interfaces, that's why you need to pass the same reference in both the arguments to handle the callbacks respective to both the interfaces.
In some other implementation, both the interfaces can be handled separately too.
this
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
Over here this refers to current Activity called MainActivity
I'm going to create a Fragment that have an Activity to managing that fragment; Like this:
public class Form extends Fragment {
// TODO some code ...
public class Dialog extends FragmentActivity {
// TODO some code ..
}
}
but it show me error, So I crated it with a static inner Activity but an static inner class don't get me that accesses.
There's no way to make this work. Android requires Activities to have a public no-arg constructor. Non-static inner classes can't be created without an instance of the outer class, and the Android framework doesn't have (and very much shouldn't have) a way to instantiate a Fragment for the purposes of instantiating an Activity.
Just getting started with Android development and Java. So, here's the code I'm working with:
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
public class HelloAndroidActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
What is the purpose of declaring the onCreate() method here:
public void onCreate(Bundle savedInstanceState) {
Then using super to call the onCreate() method here:
super.onCreate(savedInstanceState);
Doesn't this mean that you are calling the onCreate() method from the Activity class rather than the HelloAndroidActivity class? If so, what is the point of declaring a method with the same name in the HelloAndroidActivity class?
Thanks for any clarification.
In your example, HelloAndroidActivity is a class that inherits from Activity. You are then overriding the base class (Activity)'s onCreate method. Overriding occurs when you define a method in a derived class with the same signature as an existing method in the base class. This means that when I call onCreate on an instance of HelloAndroidActivity, I will execute the HelloAndroidActivity version, and not the base class (Activity)'s version.
The instruction super.OnCreate(savedInstanceState) in the overridden version is explicitly calling the base class's version of the method. What this means is you want HelloAndroidActivity.onCreate to first execute the base class's implementation, then run some more code.
Take the following examples to illustrate this behavior (assume the method Output just outputs something to the screen):
1.
class A
{
public void DoSomething()
{
Output("A");
}
}
In this case, calling A.DoSomething() will output "A".
2.
Assume we still have the class A defined as above, and the following:
class B extends A
{
}
In this case, calling B.DoSomething() will also output "A".
3.
Assume we still have the class A defined as above, and the following instead:
class B extends A
{
#Override
public void DoSomething()
{
Output("B");
}
}
Now, calling B.DoSomething() will output "B".
4.
Assume we still have the class A defined as above, and now this instead:
class B extends A
{
#Override
public void DoSomething()
{
super.DoSomething();
Output("B");
}
}
Now, calling B.DoSomething() will output "A" and then "B".
You are creating a class that inherits from Activity; but you have to define its behaviour, so you tell your class, when created, to call base class to complete all the things that must be done (super.onCreate()), then you set your layout to show your screen/app (setContentView()).
One thing more: take a look at #Override defined right before public void onCreate(Bundle savedInstanceState): override means that you're extending base method to let your derived class do all the work of the base one, including (after) your logic.
Question: What is the purpose of declaring the onCreate() method here?
Answer: The oncreate() method is analogous to main(String args[]) in ususal JAVA. The oncreate activity is called when your Activity starts. So all the initialisations should be done in this method.
You write: public class HelloAndroidActivity extends Activity
This means that you are creating a class - "HelloAndroidClass" that inherits from class = "Activity".
You write: super.onCreate(savedInstanceState);
Java uses the keyword "super" to call constructors from parent class. You are using the concept of overriding here. When you run your code, the oncreate method of base class "HelloAndroidActivity" is executed and not that of parent class - "Activity class".
So you code will first run the base class implementation of oncreate() method(super.oncreate(...)) and then the implementation of derived class.
Question: What is the point of declaring a method with the same name in the HelloAndroidActivity class?
Answer: The super keyword is being used to initialize the objects. The point in redeclaring the same method and using overiding is that you are saved from rewriting the code of base class.
onCreate is sort of your main(String[] args) function in normal Java. It is where you setup your code.
From documentation for onCreate method:
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
See more here for activity methods, lifecycle etc.