what is the difference between "this" and "xxx.this" in android - android

example:
Why can I write like that MainActivity.this.getContentResolve();
but can not write like that this.getContentResolve(); in MainActivity.java

If you need to access instance of enclosing class from inner class you need to make declaration like this - ClassName.this.anyClassMethod();
For more info read this article Nested Classes

This syntax becomes relevant when using inner classes.
public class A {
String str = "A";
public class B {
String str = "B";
public String getStr() {
return A.this.str; //returns A
}
}
}

It's long described but i think your question is related to anonymous class.
When you are inside class and want to refer to the current object of the class you can use this for example:
public class MyActivity extends Activity{
int foo;
public Test(int _foo){
this.foo = _foo;
}
}
but when you want to refer to the current class object from anonymous class inside it you should use class.this for example:
MyActivity.this
Full example for Inner Class:
public class Test {
int foo = 1;
public class InnerTest {
public String getFoo() {
return Test.this.foo;
}
}
}

Why can I write like that MainActivity.this.getContentResolve() but
can not write like that this.getContentResolve()?
Because your trying to access the context of outer class (MainActivity) in the inner class. we use TheActivityClassName.this in the inner class to access the outer TheActivityClassName class’s context.
When we are accessing the activity context in inner class we need a reference to the activity class name so we pass it like MainActivity.this
and when we need it in the class then we can reference it simply like this.something
You should have a look here to get good grasp on what context is actually
Hope it helps

There is no difference if you are calling getContentResolver() from any direct method of the activity. You can write both MainActivity.this.getContentResolver(); and this.getContentResolver(); as well as simply getContentResolver() with the same effect. In this case, the this keyword refers to the current instance of the MainActivity.
However, if you are within an inner class or inside an implementation of an interface/abstract method inside the MainActivity, then this will refer to an instance of the inner class or the interface you are implementing. In that case, you have to call MainActivity.this to get access to the instance of the MainActivity.

Related

Public Methods for all activities

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

Cannot make a static reference to the non-static method myMethod(String) from the type [MyClassWhichIsExtendingActivity]

I am basically creating a base class that will overwrite (extend) classes such as Activity or FragmentActivity and add custom functionality by defining methods that should be available to any other class, that extends this base class.
The structure if the following, basically:
CustomActivity (extends)->BaseActivity (extends)->Activity
or
CustomActivity (extends)->BaseFragmentActivity (extends)->FragmentActivity
The base class in this situation is called hmFragmentActivity and it extends FragmentActivity. I've defined a custom method inside hmFragmentActivity:
public String pref(String key, String defaultVal) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
return prefs.getString(key, defaultVal);
}
Basically it's a helper method, which I want available in all other activities, by making them extend hmFragmentActivity instead of FragmentActivity.
However, when I try to call prefs() from any activity, it gets highlighted as an error in the IDE.
Here's an example:
public class FuelEconomy extends hmFragmentActivity {
// In some method:
if(pref("fuel_usage_liter", "")==""){
Log.d("fuel", "Fuel set");
}
}
When I highlight pref() above, the IDE says:
Cannot make a static reference to the non-static method pref(String)
from the type hmFragmentActivity

android - how to create a reusable function?

In my android project, I have many activities and some of them already extend other stuff like map activity or BroadcastReceiver.
How do I create a function that I can call from any activity, because I don't want to have to repeat any code in multiple activities.
thanks.
If I have useful functions that perform little helpful tasks that I want to invoke from several Activities, I create a class called Util and park them in there. I make them static so that I don't need to allocate any objects.
Here is an example of part of one such class I wrote:
public final class Util {
public final static int KIBI = 1024;
public final static int BYTE = 1;
public final static int KIBIBYTE = KIBI * BYTE;
/**
* Private constructor to prevent instantiation
*/
private Util() {}
public static String getTimeStampNow() {
Time time = new Time();
time.setToNow();
return time.format3339(false);
}
}
To use these constants and methods, I can access them from the class name, rather than any object:
int fileSize = 10 * Util.KIBIBYTE;
String timestamp = Util.getTimeStampNow();
There's more to the class than this, but you get the idea.
You can extend the Application class, then in your activities call the getApplication method and cast it to your application class in order to call the method.
You do this by creating a class that extends android.app.Application:
package your.package.name.here;
import android.app.Application;
public class MyApplication extends Application {
public void doSomething(){
//Do something here
}
}
In your manifest you must then find the tag and add the android:name="MyApplication" attribute.
In your activity class you can then call the function by doing:
((MyApplication)getApplication()).doSomething();
There are other ways of doing something similar, but this is one of the ways. The documentation even states that a static singleton is a better choice in most cases. The Application documentation is available at: http://developer.android.com/reference/android/app/Application.html
You could create a static method or an object that contains this method.
You can create a class extending Activity, and then make sure your real activities are subclasses of that activity, instead of the usual built-in one. Simply define your common code in this parent activity.
Shachar
Create a new Java class BaseActivity with abstract Modifiers and extends it with AppCompatActivity.
Move all your methods under Java class BaseActivity.
package com.example.madbox;
public abstract class BaseActivity extends AppCompatActivity {
protected void YourClass() {
}
}
Extends your Activities with BaseActivity but not AppCompatActivity.

Get Class object from another Class JNI

Java code:
public class ParentClass
{
class ChildClass
{
public String strUrl;
/**
* Standard Constructor.
*/
public ChildClass( )
{
strUrl = "";
{
}
// Some code goes here ....
}
How you can see I have ParentClass and ChildClass in it. Now from my JNI code I want to get ChildClass and call it's constructor. In JNI I have ParentClass object.
What must I do to get ChildClass object from ParentClass and call ChildClass functions or set members?
In oracle java the syntax will be
env->FindClass("ParentClass$ChildClass");
This may works also for android.
Plus constructor of inner class have additional parameter, reference to outer class.

How to access the variables that are in void onCreate class from another class (both are under activity subclass)?

I am trying to access some of the onCreate class variables from another class that is under activity class, for example
..Acivity class(..)
Class onCreate(..){
Final int intItemNo = 0;
}
Class testing(){
//some commands here, will need access to the intItemNo above.
}
};
Place the variable definition outside of the onCreate Class. I am assuming this code is from an activity class so onCreate is really a method not a class. It does not change the answer though. If it is not, onCreate is not a good name for class as it conflicts with an android method.
public class1 extends Activity {
Final int intItemNo;
public void onCreate(..){
intItemNo = 0;
}
Class testing(){
intItemNo = 1;
}
}

Categories

Resources