Access functions from anywhere in the program-Android - android

I'm starting to work with the android system and Java in general.
I'm coming from a VB background, and in VB I had a Module, that enabled me to write functions that were accessible from everywhere in my program(different pages for example)
Is there something similar to the Module of VB6 in Java and Android?
Thanks!

In Java you can set the visibilty of a function to public. Then you can access it from everywhere in your code, if you have a object of that class.
public void doSomething() {
}
Then you can also use the keyword static to define methods that do not need to be called from an object of that class but exists during the first loading of the class until the end of the programm:
public static void doSomething() {
}

Related

How to expose objects/properties to JavaScript via AddJavascriptInterface

I know that I can expose a "jsBridge" object to javascript in webview by
Control.AddJavascriptInterface(new JsBridge(), 'jsBridge');
It seems inside the "JsBridge" class, we can only expose methods like
[JavascriptInterface]
[Export("myMethodName")]
public void MyMethod(string message)
{
//some logic
}
But I need some way to expose some objects or properties like bellow:
public ApiModule1 Module1 => _module1;
public ApiModule2 Module2 => _module2;
seems the "ExportAttribute" can only be applied to methods.
I am doing this because I need a way to expose only one single namespace at the JavaScript side, and still keep things organized by not stuffing everything into one object, that is;
jsBridge.Module1.someMethod();
jsBridge.Module2.someMethod();
Did I misunderstood some concepts here or is there are any other way to achieve this kind of feature?
Thank you very much.
You cannot expose properties directly. If you want to export any object create a getter for same in the interface you are exposing.

Android app with weak reference and singleton

I'm in the process of completely redesigning my Android app. Before, EVERYTHING was in the same class.
So I tried to redraw everything so that the code is clearer apart Admob than the doc advice to put in the Main thread, I separate the different part of my code in class. So I used two technique: I created a songleton that contains variables that I want to have access to constantly,and I call my classes via weak reference.
Here is what it looks like:
For example, the UIManager class that needs to update the game's IU have a weak reference looks like this:
private static SoftReference<UIManager> ManageUI;
static{ManageUI= new SoftReference<>(null);}
static UIManager get()
{
if(ManageUI.get()==null)
{
ManageUI= new SoftReference<>(new UIManager());
}
return ManageUI.get();
}
GameManager Manager=GameManager.getInstance();
to be able to use the findviewbyid for example I place in method argument the main class that is the mainthread
the singleton that contains all my variables that I want to have permanent access to looks like this:
private GameManager()
{}
/** Holder */
private static class Manager
{
/** Instance unique non préinitialisée */
private final static GameManager instance = new GameManager();
}
/** Point d'accès pour l'instance unique du singleton */
public static GameManager getInstance()
{
return Manager.instance;
}
To separate all in different class, I pass argument to my method so I can call au stuff belong to Activity like that:
(My main class is called GamePlay)
void OpenGlobalScene(GamePlay activity)
{
Manager.OnTitle=false;
if (!checkLayout(activity,R.id.globalscene)) {
LayoutInflater(activity,9, true);
LinearLayout GamePlan = (LinearLayout) activity.findViewById(R.id.globalscene);
GamePlan.setAlpha(Manager.AlphaBord);
}
}
For now, I have not noticed any problems except a few slownesses on old android phone 4.4.2.
Also compared to my old code were EVERYTHING was in the same class, it's much easier to change pieces of code (going to the inapp billing V3 was simpler since everything was in one class that I call like the others with weak referencre)
My questions are:
-What are the problems that such a structure might pose?
I had also chosen that structure to not load or leave in memory things that are not useful
-How are chance that Android will erase from memory an action in progress called with weak reference?
-As you can see I pass the activity has argument to the method, sometimes I pass it from a method to another. Is that fact can cause some trouble?
Thank you for your help.
Check Dagger2 is better than the clasic singleton https://developer.android.com/training/dependency-injection/dagger-android?hl=es-419
thanks for your answer and your tips. I'am gonna check this out.
Anyone else know something about consequences on memory when using weak references ?

method in android which can be accessed from anywhere?like modules in VB

I am new to android. If my question is wrong please forgive me,
My Question is:
Can I write a method in android which can be accessed from anywhere inside my application?
I've studied VB for all these years and now I am trying to program in android, I couldn't stop comparing them when I write code.
In VB we can create modules and access it from anywhere. Is there anything I can do in Android...??
Answers and advises are needed!
You have to create a class with a static method:
public class MyClass {
public static void myMethod() {
// Your code here...
}
}
And you can call it like this: MyClass.myMethod();
You can try extending Application and put your common functions there.
In all activities you can access this via context.
For reference follow this:
http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/
It is a long topic to discuss , but as you have simply ask whether method is accessible or not , then answer is yes but with some respect of java rules.
Android is again like java coding, You can do same thing what we can do with java.
Same Data type
Method Format
Class structure
Inheritance, Public , private , protected, etc.
So while you write your code you should care for that all things and these all thing you know because you are working in VB.
VB module equivalent is not there in java(android),
but some how you can mock them to some extend by using final classes with static methods.
Anyway you need to import the package containing these type of classes wherever you use it.

What does 'this' mean as a parameter in Android SDK? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the meaning of “this” in Java?
I'm still very new to learning Android programming, and I noticed that "this" was used often in parameters for method calls in the language. I'm following The New Boston tutorials through YouTube, but he never really explains quite detailed enough what the 'this' statement means. Can somebody please explain it to me? Maybe dumb it down a bit?
this refers to the instance of the class you are currently coding within.
You cannot use it in a static context because in this situation you are not within any object context. Therefore this doesn't exist.
public class MyClass {
public void myMethod(){
this.otherMethod(); // Here you don't need to use 'this' but it shows the concept
}
private void otherMethod(){
}
public static void myStaticMethod(){
// here you cant use 'this' as static methods don't have an instance of a class to refer to
}
}
In android class.this is used to pass context around.
Formal definition of context: It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities.
That means if you need to access resources (including R and user interface) you will have to use context.
In java this means the instance of the class that you are in. For example MainActivity.this points to the current instance of the MainActivity. So by using MainActivity.this.foo you are accessing the foo field of MainActivity class.
public class YourClass {
private int YourInt;
public setTheInt(int YourInt) {
this.YourInt = YourInt;
}
}
"this" is used to see whether an attribute or function belongs to the class we're working on, clearer.
Also, you see that setTheInt operation gets an integer named as the same as your attribute. In that function's namespace, YourInt is not this class's YourInt, but a reflection of the integer coming from setTheInt's calls. "this" helps here to divide the outer and the inner "YourInt"s.

Where should I put global methods and variables in an Android app?

When I'm writing a method or using a member variable, I often find I need to share them across an app. But where should they go?
I can subclass Activity, but that falls over as soon as I use a MapView and am forced to use MapActivity, so not all my activities inherit from my subclass. Is there I way around this?
Where inheritance isn't applicable, I am tending to put generic methods and member variables into a subclass of the Application object, but I'm finding it's creating a mess of code as every class needs to either grab access to the application object through via context, or I have to pass it down.
I suspect I would be better off creating MyApplication.getInstance() and keeping everything in a singleton, instead of passing the application object down through the app classes. but before I wanted to see what you guys had to say.
If you want to access the "Global Singleton" outside of an activity and you don't want to pass the Context through all the involved objects to obtain the singleton, you can just define, as you described, a static attribute in your application class, which holds the reference to itself. Just initialize the attribute in the onCreate() method.
For example:
public class ApplicationController extends Application {
private static ApplicationController _appCtrl;
public static ApplicationController getAppCtrl()
{
return _appCtrl;
}
}
One example with resources: Because subclasses of Application also can obtain the Resources, you could access them simply when you define a static method, which returns them, like:
public static Resources getAppResources()
{
return _appCtrl.getResources();
}
For global methods, use a static Util class with static methods. If you can't use static methods, then the methods shouldn't be global in the first place, and put them in the class that makes sense.
First read this:
How to declare global variables in Android?
Now why you shouldn't use a static singleton. Using a singleton is a the same thing as a global variable. Global variables reduce your maintainability because everywhere you use the global variable you break modularity or introduce global details and assumptions about your overall design. Your program can't have two of these variables because it only looks in one place for it. This means your program can't adapt easily when you have two instances instead of one.
For example, say I have a method called playTurn() and I implement it like so:
public void playTurn() {
globalPlayer.incrementClock();
globalPlayer.doSomething();
globalPlayer.doSomethingElse();
}
Now let's say I want to add a second player to the mix. Uh oh my playTurn() method assumes one player only when it used globalPlayer. If I want to add a second player to the program I have to change that method. Do this a lot and your program is very rigid and inflexible to change. Instead what if I did this:
public void playTurn(Player player) {
player.incrementClock();
player.doSomething();
player.doSomethingElse();
}
Now can do this:
playTurn( player1 );
playTurn( player2 );
I can reuse playTurn() for both player1 and player2 and I didn't have to change it. I just had to change the client of that method.
Most of the time you're being lazy and you want to get a reference to some object, and global variables are fast ways to get references to well known objects. Instead it's better to have one class that resolves the dependencies across your application at start up or the time when it makes sense. Then only that one place understands how your code is put together. For example,
public class Game {
Player player1;
Player player2;
Board board;
public void startGame() {
BlueTooth blueTooth = BlueTooth.getChannel();
player1 = new LocalPlayer();
player2 = new NetworkedPlayer( blueTooth );
board = new Board();
player1.setOpponent( player2 );
player1.setBoard( board );
player2.setOpponent( player1 );
player2.setBoard( board );
}
}
Now everyone has their dependencies, and they don't need to use static variables to find references to things. Also player1 doesn't have to know about details like that player2 is over the network, or that it's apart of a Game. What's important to note is that these objects we're connecting have a long life, possibly the entire program, but if they need to create other things at runtime that's ok for them to do.
Say for example, we need to create multiple players at runtime based on who joins the game. Well we might create a PlayerManager that we can instantiate at startup then create Player objects on the fly. PlayerManager is just a plain old object that we create in Game when we start a new game.
I hope you can start seeing this is a much better way to develop software. You might not understand it right off, but if you think about it will make more sense. It's very subtle change, but very powerful.

Categories

Resources