Hi I am doing one app here. I'm using global class varibles. It's working well, but if I'm using more globalclass variables I'm getting memory exceptions some times.
I tried this:
public class SecondClass extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
TextView tv = (TextView)findViewById(R.id.tv);
tv.setText("Global String : " + GlobalClass.myVal);
}
}
class GlobalClass extends Application {
static String myVal;
}
Is this correct or not?
First thing, you dont need Static Variable to declare global variable in Application Class,
so Change your code to:
class GlobalClass extends Application {
public String myVal;
}
then whereever you need to access this data, get Application object by:
GlobalClass global=(GlobalClass)context.getApplication();
global.myVal="anything";
You can use like this
public class GlobalVar {
public int getMyVar() {
return myVar;
}
public void setMyVar(int myVar) {
this.myVar = myVar;
}
private int myVar = 0;
private static GlobalVar instance;
static {
instance = new GlobalVar();
}
private GlobalVar() {
}
public static GlobalVar getInstance() {
return GlobalVar.instance;
}
}
then you can call like
GlobalVar.getInstance().setMyVar(int);
You can also use Global Variable Activity class wise. As for example
public class SecondClass extends Activity {
String S1,S2,S3;
EditText edt1,Edt2,Edt3;
Button btn1,btn2,btn3;
//like this wat Declare all variable you want to use in your Present Activity Class
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
edt1= (EditText)findViewById(R.id.tv);
}
}
Take a look at the post Singletons vs. Application Context in Android?
There are a lot of discussion about Singletons vs Application objects in the forum.
I'm personally inclined to Application object with properties. If you dont want to keep in memory a lot of objects use a LruCache (there is a pre v11 implementation in the compatibility package) to low your memory requirements.
Take into account you will eat the same amount of memory using Singletons than using the Application object, all objects will be keep in memory until you free them (remove any refrence to them and let the GC purge them from memory).
Related
I have just one class where I need to access SharedPreferences:
public class MyUtils {
public static String packageMe(Object input){
// do stuff here
// need SharedPreferences here
}
public static Object unpackageMe(String input){
// do stuff here
// need SharedPreferences here
}
}
I tried this:
public class MyUtils extends Activity
But, as you know, I cannot access SharedPreferences from a static method.
I thought about passing in the context to the static methods, but that extends the number of classes out to four that I will need to modify, and the classes are already extending AsyncTask:
public class SomeClass01 extends AsyncTask {
#Override
protected Object doInBackground(Object[] params){
MyUtils.packageMe(abc_123_object);
// do stuff here
}
}
So, I thought that maybe I could pass the context into those four classes. However, there are a couple dozen classes that I would need to modify that use those four classes, that in turn use that single class.
public class SomeTopClass extends FragmentActivity implements x, y, z {
new SomeClass01.execute(abc_123_object);
// do stuff here
}
I don't know if I want to be passing a context reference that deep into my code.
I saw here on StackOverflow about putting a reference to the SharedPreferences in my abc_123_object model, but there are quite a few objects I use (other than abc_123_object) and I don't want to have to jerry-rig so many classes.
So, is there a way for me to do this without modifying dozens of classes and passing context references all around my code, or am I stuck?
Thanks
Create static variable in your Application class.
public class MyApp extends Application{
public static Context context;
#Override
public void onCreate() {
context = this;
}
}
Then use it when you need.
public static String packageMe(Object input){
// do stuff here
// need SharedPreferences here
// context = MyApp.context
}
As Dusan mentioned, using an application class is an easy way to do this:
In your application class:
private static MyApplication sInstance = null;
private SharedPreferences mPrefs
public static MyApplication getApp()
{
return sInstance;
}
public SharedPreferences getSharePreferences()
{
return mPrefs;
}
in onCreate():
sInstance = this;
mPrefs = getSharedPreferences(PREF_FILE, MODE_PRIVATE);
Then in your code simply do:
MyApplication.getApp().getSharePreferences();
Your Application's onCreate() is guaranteed to be executed before any activity is created, so unless you are doing something really weird, it should be safe.
I defined a static variable in my custom Application class. Something like this:
public class App extends Application{
...
public static Object var;
...
#Override
public void onCreate() {
var = new Object();
}
}
During my applications's Activities i need to read App.var value, but some times it seems to be null.
Is this possible that static variables of my App class destroyed (because of GC or anything else) during lifetime of my application? If yes, why?
I have been looking for a long time for a simple way to pass data (string type) from class to activity.
I found some tutorials about passing data from activity to class but is it possible to do the opposite, passing data from class to activity ?
if you import the class in your activity (which is also a class by the way) you can easily access the classes attributes.
example: MyClass.java
package edu.user.yourappname;
public class MyClass {
public string infoToPass = "whatever";
}
MyActivity.java
package edu.user.yourappname;
import edu.user.yourappname.MyClass
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
String myString = MyClass.infoToPass;
}
}
i have no IDE to type this in atm it might contain some errors :S but i hope you get the idea.
if you need more specific help you have to provide a code sample.
also, what do you want to achieve exactly? maybie there's a different approach.
cheers!
Create Interface and implement that in your activity. Pass the activity instance in your class and and call that instance with interface method whenever you like.
To be more clear, create an interface and use it as following:
public interface SomeInterface{
public void passValue(String value);
}
public SomeActivity extends Activity implements SomeInterface{
// place any code you want in your activity, onCreate, onResume, etc.
private void someMethod(){
// Wherever in your activity, initialize your class with your activity.
SomeClass someClass = new SomeClass(this);
someClass.someMethod();
}
public void passValue(String value){
// do whatever you want with your value
}
}
public class SomeClass{
private SomeInterface someInterfaceInstance;
public SomeClass(SomeInterface someInterfaceInstance){
this.someInterfaceInstance = someInterfaceInstance;
}
public void someMethod(){
// Some code...
someInterfaceInstance.passValue("Hello World!");
// Some more code...
}
}
Here is a easy way of doing it -
By defining static variables
In your class, make the String whose value you want to pass public static like this -
public static String pass;
And then in you activity, you can directly access it since it's a public variable like this -
String receive = className.pass;
I have two Classes. Class A is an Activity that has integer variables that need to be used in Class B (not an Activity). I have been able to use Bundles to transfer data of variables from one Activity to another Activity before. The problem is that this time, Class B is not an Activity and extends ImageView so that the draw() function can be used. Because of this, I am unable to use normal Activity functions, such as Bundle-Intents or SharedPreferences to transfer data in primitive variables from Class A to my Class B. I receive an error saying that "getIntent() is undefined for type".
So my question is, how can Class B use the variables in Class A if I am unable to bundle? Is there another way?
Someone said they did not understand my question so hopefully the below example will help demonstrate better.
public Class1 extends Activity {
//so Class1 has some primitive data, and is an Activity w/layout
int var1;
int var2;
Bitmap bitmap;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
}
}
A different class needs to draw onto canvas, but also needs to use the
information in var1 and var2 to be able to draw properly. But how to obtain that information?
public Class2 extends ImageView {
/*I am unable to use normal Activity functions, so I
*cannot onCreate, for example. I also cannot bundle,
*getIntent(), or use getSharedPreferences(). So how do I get var1
*and var2 value? */
}
Update: I was able to get this to work using getters. I attempted this before, but it was not returning the correct values. If anyone else ever gets stuck with this similar issue, remember to setup your variables with "static". I'm still learning all the differences, but without static my getter was not working. Once I added static to my variables, everything worked out. So that's one observational tip (even without fully understanding the logic as to why). Thank you to all the responders for your tips.
You can do this in different way.
First of all you can use static variable to do this. Such that you can declare a variable in class A public static String variable; and from class B you can get the value of this variable like this way ClassA.variable.
Another way you can use by passing a context of class A to B and then use SharedPreference.
Or create a new class which extends android Application. From class A you can set different variable value in application class. Now you can retreive those values from Application class. Hope this can help you.
Some code Sample using static variable
public Class1 extends Activity {
public static int var1 =20;
public static int var2 = 30;
}
Now get the variable value from class two
public Class2 extends ImageView {
Class1.var1;
Class.var2;
}
Second way using getter.
public Class1 extends Activity{
int var1 =10;
int var2 =20;
public int getVar1() {
return var1;
}
public int getVar2() {
return var2;
}
}
Now you can get the variable value in Class2
public Class2 extends ImageView {
Class1 class1= new Class1();
class1.getVar1;
class1.getVar2;
}
Also you can use SharedPreference. Hope it can help you. Thanks.
Various options exist:
The Activity can pass the information to Class B:
class B {
public void tellMeInformat(int usefulNumber) {
// Do something
}
}
Or, you can pass the Activity to the ImageView:
class A {
initiation {
B mySpecialImageView = /* Set it upo */;
B.setParentActivity(this);
}
}
class B {
private myA = null;
public void setParentActiviy {
myA = A;
}
private void doSomething {
int usefulNumber = A.getUsefulNumbner();
// Do something
}
}
I need to stock some datas in my application.
I know that i can do it like this:
class:
public class MyApplication extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
}
Implementation:
MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getSomeVariable();
This is working if i'm in an activity.
But if i'm in a class not extended from Activity, how can I access at my datas?
thanks in advance for your help!
You can use a Singleton design pattern. You can then use it anywhere, because it has static access.
public class SingletonClass {
private static SingletonClass _instance = null;
private int _value = 0;
private SingletonClass() {
}
public static SingletonClass getInstance() {
if (_instance == null)
_instance = new SingletonClass();
return _instance;
}
public int getValue() {
return _value;
}
public void setValue(int value) {
_value = value;
}
}
and then access it like this:
SingletonClass.getInstance().getValue();
Note: This is a good and easy workaround for some programming problems, but use it very wisely.. it comes with it's problems
Use SharedPrefrences
http://developer.android.com/guide/topics/data/data-storage.html
Perhaps by injecting all the required for a class data via constructor or special setter, I would suggest former one. (Constructor Injection vs. Setter Injection)
There are more solutions like static fields but personally I do not like this approach since statics sometimes makes unit testing a bit messy.
BTW, what kind of variables you want to share?
I use, it may be gruesome to some, a class with static variables, that you can retrieve from every class in the app.
Just create a class with all the field as static, and you can use them throughout your app. It doesn't get erased, only when stopping the app.
You could also just add static variables to your application class.
You can use static methods (or variables if they are public). It's really a little messy, but if you group them (methods) in the right way you'll earn happinnes and satisfaction )
static public int getSomeInt(){
//something
}
And then anywhere in your app use
int x=MyApplication.getSomeInt();
By the way, using this style, you don't need to extend Application class. It's better to create an abstract class for such purposes.
Pass the context of your activity as a param to the method or class:
// ...
public void doStuff(Context context) {
// for example, to retrieve and EditText
EditText et = context.findViewById(R.id.editText1);
}
then, on your activity, you would do:
// ...
MyClass myClass = new MyClass();
// ...
myClass.doStuff(this);
// ...