How to get a Global variable from one class to another? - android

Hi have one database and I've created a Database class that has a private static class DbHelper extends SQLiteOpenHelper to help me manage my database.
This database is access from four different activities.
Now What I need is? I have a GlobalClass like this:
public class Question extends Application{
private String check;
public String getCheck() {
return check;
}
public void setCheck(String check) {
this.check = check;
}
}
In FirstScreen Activity I have a value for String check. If I get in other Activity Class its fine, no problem.
If I get in DBHelper I can't. I have tried like this:
final Question quiz = (Question) getApplicationContext();
final String check = quiz.getCheck();
it shows error in getApplicationContext(). How can I get that value in DBHelper class
Please let me know what is wrong with the syntax.

in DBHelper you will not have ApplicationContext till you don't pass it.
instead of this do one thing make a static String in your Application class and use it.
as Application class is a single ton instance which remains in memory till the end so it will not use much memory.
public class Question extends Application{
public static String check = "";
}
Retrieval of the value
public class DBHelper {
public method() {
String check = Question.check;
}
}

You don't have a Context in your DBHelper class.
You either need to pass in a Context when you instantiate the DBHelper class (preferred but not always practical) or get the Context from your Question by doing something like the following.
((Question)Question.getAppContext())
The Context is then returned via a getAppContext() method in Question.

Related

How do I access Android SharedPreferences from a static method in a class without passing in a context reference?

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.

How to Access Android Custom Application Object in simple Java Class which Also has ApplicationContext object?

I have created a custom application class like this:
class A extends android.app.Application{
public String abc = "xyz";
}
And I have a simple java class
class B {
private appContext;
// This constructor is called from activity.
B(Context ctx){
this.appContext = ctx;
}
private void foo(){
// want to access Class A's abc String vairable Here...HOW TO DO THAT?????
}
}
How to access Class A's abc String vairable in foo method.
You can get the Application class with getApplicationContext from Context with the good casting
((A) this.ctx.getApplicationContext()).abc;
The Application class in Android is a singleton and therefore so is your derived class. Android will create just one instance of your class A when it starts your application. Just change
class A extends android.app.Application {
public String abc = "xyz";
}
to
class A extends android.app.Application {
public static String abc = "xyz";
}
and you can reference it from anywhere like this:
String foo = A.abc;
Instead of passing a Context, try passing an instance of the Application class instead.
Something like:
class B {
private Application app;
// This constructor is called from activity.
B(Application ctx){
this.app = ctx;
}
private void foo(){
app.abc; //Do what you want
}
}
And call B like:
B b = new B(getApplication());
Make sure that this is in onCreate() or later.
Looks like you are already passing the application context as a parameter and initializing it in the constructor. So all you have to now is to use the context variable to access abc of A like the following way: ((A) this.appContext).abc;

Passing a null context to a database helper

I have a static function that gets called whenever my background service gets a new location. In this function I want to take to coordinates passed in and save them in my database. Can I pass 'null' as the context to create an instance of the database helper or is there a better way to do this. Thanks.
public static void locationHasChanged() {
final wd_DatabaseHelper helper = new wd_DatabaseHelper(null, "myDB.db", null, 1);
}
Probably not. Usually your Database helper extends SQLiteOpenHelper and the context will be used to call the openOrCreateDatabase() or the getDatabasePath(). I can't say for sure without seeing the code of wd_DatabaseHelper but having a null context is never a good idea. See for your self ... Source of SQLiteOpenHelper
since an android Service is a context you can pass "this of the service" into your method
public class MyLocationHelper {
public static void locationHasChanged(Context context) {
final wd_DatabaseHelper helper = new wd_DatabaseHelper(context, "myDB.db", null, 1);
....
}
}
public class MyService extends Service {
private void onLocationHasChanged()
{
MyLocationHelper.locationHasChanged(this);
}
}

android how to use string resource in a java class

In my java class I want to use a string resource from strings.xml.
for that I have to use like below,
getString(R.string.address)
if my class is an activity then its taking. But my class is a simple java class , how can I use there?
Is it possible?
Thank you
A class does not have a context and to use a string resource a context is needed. So just call the class from an activity and give a parameter context and within your class constructor just use that context to get the string resource.
In your custom class you need to import the R namespace for the project to get the resource Id.
import com.myrandomapp.R;
Then to get the actual string
context.getString(R.string.COOL_STRING)
You can pass the context of the Activity class to the java class and access the resources.
From your Activity Class
Helper helper = new Helper(this);
Your Java class
public class Helper {
Helper(Context c){
c.getString(R.string.address);
}
}
You can create a static Application Context in your custom Application class
public class App extends Application{
private static Context mContext;
#Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
}
public static Context getContext(){
return mContext;
}
}
Then you just need to call App.getContext().getResources() to get any resource values.
Just remember that this Context is Application type, so there are things that this Context is not good to use. Read this for further info.
You could done if you add this line:
// this is the object itself, and idString is the ID String bound to the literal.
this.getString(R.string.idString)
I hope this comment helps you!
Brs.

Creating an Object accessible by all Activities in Android

I'm trying to create an ArrayList of Data containing Objects (Like a list of Addresses and properties (pretty complex)) and am wondering: How can I make an Object accessible (and editable) by all Activities and not just the one it was instanciated in?
Basically this:
Create Array in Activity 1
Access same Array in Activity 2 and 3
???
Profit.
The easiest way to do this is by creating an Singleton. It's a kind of object that only can be created once, and if you try to access it again it will return the existing instance of the object.
Inside this you can hold your array.
public class Singleton {
private static final Singleton instance = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
Read more about singleton:
http://en.wikipedia.org/wiki/Singleton_pattern
You can extend the application class. And add your arrays there.
You can access the instance of the class by using this command
MyApplication appContext = (MyApplication)getApplicationContext();
Well you can create a Constant class and declare you ArrayList as a static variable.
1.)
Class ConstantCodes{
public static ArrayList<MyClass> list = new ArrayList<MyClass>;
}
This will be accessible from everywhere you want by just ConstantCodes.list
2.) You can extend your class by Application class like this
class Globalclass extends Application {
private String myState;
public String getState(){
return myState;
}
public void setState(String s){
myState = s;
}
}
class TempActivity extends Activity {
#Override
public void onCreate(Bundle b){
...
Globalclass appState = ((Globalclass)getApplicationContext());
String state = appState.getState();
...
}
}
you should make it static and access it from any other activity.....
how about use a static keyword ?
public static SomeClass someObject
in your activity class that initiate your object
1- In your Activity1, déclare your array in public static
public static ArrayList<HashMap<String, String>> myArray = new ArrayList<HashMap<String, String>>();
2- In your Activity2, Activity3, etc. access to your ArrayList
Activity1.myArray
You can create a java file x beside other java files.
x file contains static method which used to access the class method without instantiate it.
Now make a method called createVariable() and declare variable which you want to make it Global.
Now make a method called getVariable() which returns the Global variable.
At which point you want to create global variable, call className.createVariable().
And to get access to that variable call className.getVariable().
Here is my example for Database class.
public class GlobalDatabaseHelper{
static DatabaseHelper mydb;
public static DatabaseHelper createDatabase(Context context)
{
mydb = new DatabaseHelper(context);
return mydb;
}
public static DatabaseHelper returnDatabase()
{
return mydb;
}
}

Categories

Resources