Activity.this reference on Context - java

I have an Activity with a ListView which I've added a listener (setOnItemClickListener).
When I'm inside this method from the listener above mentioned:
public void onItemClick(AdapterView<?> parent, View view, int pos, long id )
In order to have access to the Activity, I've done this:
MyActivity host = (MyActivity) parent.getContext();
From host variable, I have access to all MyActivity methods and attributes (which aren't static), but I can't access to the MyActivity.this reference.
Could someone explain me why? Thanks

MyActivity.this would reference the instance of the "outer" MyActivity class when your code ran in an inner class. -- Does it? If so, why would you need the host variable?
Update: It only just occured to me that you may be missing the fact that everything you would access via MyActivity.this from within an inner class, you can access via host in your specific setup.
Update: You seem to have a wrong understanding of the meaning of this. Originally, it stands for this object, i.e. the class in which your code runs.
With the additional notation Class.this, Java enables you to access the instance of the outer class of your code, but only from an inner class.
In the following example, Class.this works:
class A {
int a;
class B {
void process_a_in_A() {
A.this.a++;
}
}
// however, this does NOT work b/c
// static inner classes do not have references t oouter classes
static class C {
void process_a_in_A() {
// error -- class A.C is detached from its outer class A
A.this.a++;
}
}
}
Also, in the following example, Class.this does not work. The reason is simply that the system cannot know whether there is an Instance of class A and which one of the possibly many instances of class A you want to refer to.
class A {
int a;
}
class B {
void process_a_in_A() {
// A here is a class name, not an object reference;
// so A.this is meaningless in this context
A.this.a++;
}
}
Once again, please be aware that you asked a question without providing the necessary information to answer it specifically, so it can only be answered in general and it looks like you have a wrong understanding about inner classes and the Class.this notation.

Exactly, within any class, you can reference to itself via its Name -> Name.this (especially used for inner-classes)
As you already have your object referenced in the variable host, why not just use it then?!

Related

Java Application return super class when initialized

Nowadays we are on writing some core application that is all other application will be relying on. Without further due let me explain the logic with some codes,
We used to have a single java file that was 1000+ lines long and each application was having it as class inside, so when there was a change, each application had to edit the java file inside of it or simply fix one and copy to all. This is hard to implement as much as it is hard to maintain. Then we end-up with creating this as a separate application that is divided to smaller part, which is easy to maintain and also a core maybe a dependency to other application so we fix in one place and all other code applications are fixed too.
I've been thinking for a some great structure for this for a while want to use a builder patter for this as below
TheCore theCore = new TheCore().Builder()
.setSomething("params")
.setSomethingElse(true)
.build();
The problem arises now. Like so, I initialized the object but now I'm having access to that objects public class only. This application actually will have many small classes that has public functions that I don't want them to be static methods that can be called everytime. Instead I want those methods to be called only if TheCore class is initilized like;
// doSomething() will be from another class
theCore.doSomething()
There are some ideas I produced like
someOtherClass.doSomething(theCore)
which is injecting the main object as a parameter but still someOtherClass needs to be initialized or even a static method which doesn't make me feel comfortable and right way to that.
Actually I do not care if initializing TheCore would bring me a super object that includes all other classes inside initialized and ready to be accessed after I initialized TheCore. All I want in this structure to have a maintainable separate app and methods avaiable if only the main object which is TheCore is this circumstances is initialized.
What is to right way to achive it? I see that Java does not allow extending multiple classes even it if does, I'm not sure it that is right way...
Thanks.
After spending significant amount of time of thought I ended up that
// doSomething() will be from another class
theCore.doSomething()
is not suitable since many java classes could possibly have identical method names. So...
// doSomething() will be from another class
theCore.someOtherClass.doSomething()
would be a better approach.
To make it easier to understand I'll have to follow a complex path to explain it which is starting from the package classes first.
Think that I have a package named Tools and a class inside SomeFancyTool
main
└─java
└─com
└─<domainName>
├─Tools
| └─SomeFancyTool.java
└─TheCore.java
Now this SomeFancyTool.java must have a default access level which is actually package level access, because I don't want this classes to be accessed directly;
SomeFancyTool.java
package com.<domainName>.Tools
class SomeFancyTool{
public String someStringMethod(){
return "Some string!";
}
public int someIntMethod(){
return 123;
}
public boolean someBooleanMethod(){
return true;
}
}
So now we have the SomeFancyTool.java class but TheCore.java cannot access it since it is accesible through its Tools package only. At this point I think of an Initializer class that is gonna be in the same package, initialize these private classes and return them with a function when called. So initiliazer class would look like this;
ToolsInitializer.java
package com.<domainName>.Tools
public class ToolsInitializer{
private SomeFancyTool someFancyTool = new SomeFancyTool();
public SomeFancyTool getSomeFancyTool(){
return someFancyTool;
}
}
Since ToolsInitializer.java can initialize all functional private classes inside in Tools package and also can return them as objects to outside of the package scope, still we are not able to use these methods as we cannot import com.<domainName>.SomeFancyTool from TheCore.java because it is package wide accessible. I think here we can benefit from implementation of the java interface. A class that is not functional alone, so no problem even if it is accessed since it's methods will be nothing but declarations.
At this point I'll rename SomeFancyTool.java to SomeFancyToolImplementation.java which it will be implementing the interface and call SomeFancyTool.java to the interface itself.
SomeFancyTool.java (now as an interface)
package com.<domainName>.Tools
public interface SomeFancyTool{
public String someStringMethod();
public int someIntMethod();
public boolean someBooleanMethod();
}
and lets rename prior SomeFancyTool.java and implement the interface
SomeFancyToolImplementation.java (renamed)
package com.<domainName>.Tools
class SomeFancyToolImplementation implements SomeFancyTool{
#override
public String someStringMethod(){
return "Some string!";
}
#override
public int someIntMethod(){
return 123;
}
#override
public boolean someBooleanMethod(){
return true;
}
}
Now our structure has become like this with the final edits;
main
└─java
└─com
└─<domainName>
├─Tools
| ├─SomeFancyTool.java
| ├─SomeFancyToolImplementation.java
| └─ToolsInitializer.java
└─TheCore.java
Finally we can use our TheCore.java class to call all initializer classes with their methods to receive all these private classes inside as an object. This will allow external apps to call and initialize TheCore first to be able to access other methods.
TheCore.java
public class TheCore{
private SomeFancyToolImplementation someFancyTool;
public static class Builder{
private SomeFancyToolImplementation someFancyTool;
public Builder(){
ToolsInitializer toolsInitializer = new ToolsInitializer();
someFancyTool = toolsInitializer.getSomeFancyTool();
}
public Builder setSomeValues(){
//some values that is needed.
return this;
}
public Builder setSomeMoreValues(){
//some values that is needed.
return this;
}
public TheCore build(){
TheCore theCore = new TheCore();
theCore.someFancyTool = someFancyTool;
return theCore;
}
}
}
All Done and it is ready to use. Now the functional package classes and its methods that it relying on if TheCore is initialized or not, cannot be accessed with out TheCore. And simple usage of this Library from a 3rd Party app would simply be;
3rd Party App
TheCore theCore = new TheCore.Builder()
.setSomeValues("Some Values")
.setMoreSomeValues("Some More Values")
.build();
theCore.someFancyTool.someStringMethod();
Note: Note that a the ToolsInitializer.java is still accessible and could be used the get private method without first calling TheCore but we can always set a checker inside getSomeFancyTool() method to throw error if some prerequisites are not satisfied.
I do not still know if this is a functional structural pattern to use or its just some hard thoughts of mine. And don't know if some pattern is already exist that I just could not see yet but this is the solution I end up with.

How these codes work (Constructor And ListView)

I was following the udemy android app development course, In the course, we were writing code to Create A listview and get some data when the user clicks on the list, to do that the teacher uses a thing called Constructor I know how constructors work theoretically but can't understand the way it works in code. It will be great if someone can explain what these lines of codes do.
edit: Full Code is here https://github.com/atilsamancioglu/A14-LandmarkBook
import android.graphics.Bitmap;
public class Globals {
private static Globals instance;
private Bitmap chosenImage;
private Globals(){
}
public void setData(Bitmap chosenImage){
this.chosenImage=chosenImage;
}
public Bitmap getData(){
return this.chosenImage;
}
public static Globals getInstance() {
if(instance==null){
instance = new Globals();
}
return instance;
}
}
Constructors are special methods invoked when an object is created and are used to initialize them.
A constructor can be used to provide initial values for object attributes.
You can think of constructors as methods that will set up your class by default, so you don’t need to repeat the same code every time.
In your codes, you can define the constructor as below(it may be unrelated, it's just an example):
private Globals(int id){
return chosenImage.setId(id);
}
The constructor is called when you create an object using the new keyword:
Globals objectGlobe = new Globals(000008);
Also a single class can have multiple constructors with different numbers of parameters.
The setter methods inside the constructors can be used to set the attribute values.
It's not bad to be mentioned that; Java automatically provides a default constructor, so all classes have a constructor, whether one is specifically defined or not.

Accessing variables of the wrapper object in OOP

I am creating an application in VBA for my employer (and a similar one in Java for hobby purposes) and its purpose is to 'contain' different tools that will help in our daily work. It's going to be some kind of platform with the main app window and from there a user can access some of the application components like for instance a sub-program when a user can give me feedback on application's functionality, then the info will be stored in a database that I can access later.
I already have a structure: an Application class, that contains the Application Manager and this one class contain an array of fields of the SubApp type. A SubApp type contains view, logic, and business of a sub-application. The Application class also contains members like the name of the app and the information about the user that is currently using the app (previously accessed from the application database).
Whenever a sub-app launch, I would like to put on the title bar the name of the app as well as the name of the sub-app, something like application_name - sub_app_name. The problem is, that I have no idea how can I access it the 'right way'. Recently I've achieved this by creating the app variable as a global object, then accessing it is no problem using some getters. I feel however that storing an application variable as a global variable is a bad practice.
The same problem occurs with the member variable storing info about the current user. I'd like to store the information about the current user while he's giving feedback (tool for giving a feedback is a sub-app in my application)
So here is my question: how can I access the methods/variables of a wrapping object from within one of the member methods/variables?
Any suggestions regarding the overall design of the application would also be welcome.
Object oriented design: use getters and setters for all fields is proper practice. If you want to be lazy, make all your fields public and they will be accessible from the object without getters or setters.
If you wish to access a variable throughout multiple methods in a class.
A) You'll can make a variable global
B) Create a local variable, and pass it as a parameter until you no longer need to use it.
public class Main { //All implementations stated above
private Object globalObject;
public static void main(String[] args) {
Object localObject;
method1(localObject);
method2ThatUsesGlobalObject();
}
}
Accessing variables between classes:
A) Make a variable static
B) Pass it through method parameters, or constructor parameters
C) Use abstract classes or interfaces
Here are examples of the code usage I've stated
public abstract class JavaAbstractClass {
public abstract Object giveMeThisObjectWhenINeedItThanks();
}
public interface JavaInterface {
Object giveMeThisObjectWhenINeedItThanks();
}
public class Main { //All implementations stated above
public static Object object; //Accessible by Main.object everywhere
public static void main(String[] args) {
Object local;
ClassOne class = new ClassOne();
class.method1(local);
new ClassWithInterface() {
#Override
public Object giveMeThisObjectWhenINeedItThanks() {
return local;
}
};
new JavaAbstractClass() {
#Override
public Object giveMeThisObjectWhenINeedItThanks() {
return local;
}
};
}
}

Doing an API, constructor for system private use only and another official, javadoc'ed and public to use. Advise on fix / pattern approach

I guess this is a bad pattern, whats the best approach to fix it?
I mean I would like everybody using a constructor with 2 arguments,but I need to leave default constructor because its implementing a listener which classloads it without args. I would like to hide default constructor to anyone else but the listener handler which uses it, and make the other the unique point to instantiate.
Is there any kind of annotation? any privacy modifier for certain classes (system caller one is not in the same package)?
This seems fine to me. You would do the same thing if you want to instantiate a class differently during unit testing.
Oh, I see you need a constructor that has more access than protected but less than public. Unfortunately that's not possible.
You could put both your class MyClass and the listener MyListener that needs to use the empty constructor in the same package. Then, set the access of the empty constructor to package-level:
package com.stackoverflow.foo;
public class MyClass {
MyClass () { // package-private (no explicit access modifier)
}
public MyClass(int a, int b) { // public
}
}
package com.stackoverflow.foo;
public class MyListener {
private MyClass ref = new MyClass(); // MyListener is on the same package as MyClass, so this is valid
}
This way, you ensure that only classes that are on the same package as MyClass can use the default constructor.

When is a static class initialized? Need to be called from the Application object when the app starts

I have extended the Application class like this:
public class MyApplication extends Application
{
private static MyApplication instance;
public MyApplication()
{
instance = this;
}
#Override
public void onCreate()
{
MyStaticClass.Start() // Here it crashes
super.onCreate();
}
}
The problem that I'm having is I need to call a method from an static class as soon as the application starts. However it seems that static classes have not been initialized at this point so it crashes. Is there a way of doing that inside the application class? I don't want to do this from an activity.
Thanks
First, let's see what your static class looks like. Secondly, you can do whatever you want in your application class, but just move that static method call to AFTER the call to super.onCreate(). Thirdly, post the log!!
You might need to redesign your app architecture. For instance, what do you mean under "as soon as the application starts"?
On Android the concept of "application start" is different from other platforms.
E.g. Application.onCreate() will not be called if your app's Java process was still alive by the time you pressed the app icon on the home screen. And vise versa - if your app process was killed by OS because your app was in background (e.g. due to an incoming call), then Application.onCreate() will be called while OS restores the app when call is finished. But from the user perspective this will not be an "application start".
Here is the documentation on this - Processes and lifecycles.
Static classes aren't initialized. They aren't objects. Static methods should use no state-dependent information, and static variables should not change. They exist to provide functions and parameters to people using the class who don't need an instance of it. They also allow you to do things which access private members of the class.
Realistically, classes aren't even static - they just have static members (methods and variables).
I would guess that the method start() isn't defined as static in MyStaticClass, meaning you have to instantiate a MyStatic Class instance first.
Static Classes essentially give you the opportunity to create SubClasses without creating sub Packages. They work exactly like normal classes, but you have to call them via their MasterClass.
public class MyClass{
public static class MyStaticClass{
public MyStaticClass(){
//Construct
}
public void MyMethod(){
//Do stuff
}
public static void MyStaticMethod(){
//Do Static Stuff
}
}
}
Will result in the following properties:
MyClass C1 = new MyClass(); //Totally Legal
MyClass.MyStaticClass C2 = new MyClass.MyStaticClass() //Also legal
MyClass.MyStaticClass.MyStaticMethod() //Legal
C1.MyStaticClass.MyStaticMethod() //Legal, but odd
C2.MyStaticMethod() //Also legal, also odd
C2.MyMethod() //Legal, intended use.
C1.MyStaticClass.MyMethod() //Unconditionally Illegal
MyClass.MyStaticClass.MyMethod() //Unconditionally Illegal
MyStaticClass.MyMethod() //Unconditionally Illegal

Categories

Resources