I want to define constants which can be used by all activities in an application. What is the best way to do it.
Is extends Application only way of doing it, since I dont want to declare same constant in all the classes.
There are two ways I've used that are effective:
1) Make an interface called Constants or Globals or whatever you want. Define your constant values in that class and make them all public and final. (They have to be public by definition of an interface, but be sure they're final as well). Now simply declare your Activities and any other classes to implement your Constants interface. Now they all have access to the same global values.
2) Make a class Constants instead of an interface. Define all your constants as public static final. Now you can reference all your constant values via Constants.VARIABLE_NAME in any class in your application.
Simple answer declare that Variable as STATIC FINAL and use that constant in all activity's by the name of you activity.constantname eg:activity1.name
it will take same values whenever you use it, also it will change globally.. takes same values no matters from which Activity you are accessing It.
I would use a class holding those values as static and set / get them with static methods.
If you want to assign all Activities to a Constant you declared by Creating Constant Class then,
Enter this Lines to your Constants class:
public static Class_Name Constant_name = null;
and in the Activities, add this line into onCreate() method:
Class_Name Constant_name = this;
Related
Hello everyone :) can you explain why I get this and tell me what how I have to change my code. Waiting for the answers. Have a nice day:)
controller
cannot be used in a static method. You need to make the controller object static to be able to use in a static method.
It appears that you are attempting to use a non-static member field inside a static method. This is not allowed since you need an instance of the class to access the member field. You have two choices:
Make the member field a static class variable by adding the static modifier to its declaration.
Remove the static modifier from the method to make it non-static.
You should definitely prefer the second solution over the first. As a general rule of thumb, all methods and variables should be non-static unless you have a very good, specific reason to make them static. One common use of static variables is for final constants. You also might find a situation where all instances of a class share a single value. Note that these are the exception, not the rule.
I have a service url (http://servicetest.com/api/) getting datas through the restful service.
I want to ask a question that what is the best way holding this constant?. Is it appropriate holding it in strings.xml or applicationcontroller class, or etc. Because according to my needs, I can use service url in every activity. That's why, it should be accessible from anywhere.
Thanks
I think it would be best to create a class constants(urls or whatever you want to name it) and declare all constant variables as static there so you can access them everywhere in your app without creating an object and when you need to change is you have to change only at one place,hope that helped
Just create a class like this:
public class AppConstants {
public static final String URL = "http://servicetest.com/api/";
/* private Constructor to avoid instanciating this class */
private AppConstants() {}
}
Use it that way, e.g.:
MyAsyncTask task = new MyAsyncTask();
task.execute(AppConstants.URL);
create an Interface (i.e ProjectConstants) for declaring all your project constants like generic class manner..So you can easily access these variables everywhere in your application..
//For example
package com.example.myapp;
public interface ProjectConstants
{
String SERVICE_URL = "http://servicetest.com/api/";
}
// you can use this URL in your application where ever you want by simply calling like this
textView.setText(ProjectConstants.SERVICE_URL);
I want to hold all my variables somewhere where every Activity can access them and modify them. I tried storing my variables in xml file but it only works one way, I can access them but not modify them. The other option that I have thought about is creating seperate helper class that holds all my variables and offers getValue(); and setValue(); methods, but problem with this is that I think it will be resetted every time I make object of this class. So Is there any other way to have storage for variables?
Your senod option is nearer.
In your Helper class just add a static variable
See:
Class MyHelper {
..
..
public static int globIntVar;
Where you want to use :
MyHelper.globIntVar = 2; // Setter
public int var = MyHelper.globIntVar; // Getter
You can use android.app.Application for Sharing data between diffrence components of Appliction. see this post:
Android: How to declare global variables?
Your requirement is to create some Global Variables, you can create some Global Variable by Using Application Class.
Check Example:
How to declare global variables in Android?
Make one class in your application which store all variables which are used through out application ex.
public Class Const{
Public static int siteurl="http://www.xyz.com/";
}
Now where ever you want to use that variable write
Const.siteurl
I have 2 BroadcastReceivers in my android application. They are in the same package.
If in the onReceive() method, they both read/write a static class variable (in a separate Util class). Does android create 1 copy of that static class variable or 2 (1 for each receiver)?
And what do I need to do to make sure they are accessing the static class variable not corrupting the data?
There will only be one instance of the static variable. From http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html:
A class variable is any field declared
with the static modifier; this tells
the compiler that there is exactly one
copy of this variable in existence,
regardless of how many times the class
has been instantiated.
To avoid problems, you will have to make sure the static variable is thread safe. Some data structures, like Vector, are already thread safe, so you would not have to do anything further. Otherwise, you may have to use the synchronized keyword or something from the java.util.concurrent.locks package.
Don't use static variables, make the class Singleton.
"And what do I need to do to make sure they are accessing the static class variable not corrupting the data?" - add synchronized to getters/setters
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.