android how to use string resource in a java class - android

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.

Related

Android Studio context returning null

I have a class that's inputting some data into SharedPreferences.
private static Context context;
context = MainActivity.getContext();
sp = (SharedPreferences) context.getSharedPreferences("currentData", Context.MODE_PRIVATE).edit();
SharedPreferences.Editor editor = sp.edit();
editor.putString("name", placeName);
editor.apply()
I set the context using a method in my MainActivity class:
public static Context getContext(){
return context;
}
However I keep getting a null object reference. Tried multiple solutions from stack overflow and can't overcome the issue.
Why is context returning null?
This is because MainActivity.getContext() is null try passing the context from MainActivity to your class.
public Context context;
public YourClass(Context context) {
this.context= context;
}
In MainActivity init it like this:-
YourClass yours = new YourClass(MainActivity.this);
And also avoid using static contexts it might cause memory leaks !!
Context is an abstract class whose implementation is provided by the
Android system
Context is provided to any Activity by the android system during runtime (Activity indirectly extends Context). You are trying to get Context from MainActivity class via static method, which will not work and will always return null:
context = MainActivity.getContext();
You should always get Context from an instance of Activity, not the class itself. You can do this easily by passing an instance of your current Activity to the constructor of your class. Then, you call getContext() on an INSTANCE of that Activity, not the Activity class itself.
Also, wanted to mention that your code is mostly anti-pattern. You should never store Context in static variables. I'd recommend you read more about Activity lifecycle in android and Context - these are fundamental knowledge.
You can get context statically throughout the application
please try below code:
In the Android Manifest file, declare the following.
<application android:name="com.xyz.MyApplication">
</application>
Use this class
public class MyApplication extends Application {
private static Context context;
public void onCreate() {
super.onCreate();
MyApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return MyApplication.context;
}
}
Now you can call MyApplication.getAppContext() to get your application context statically.
You are getting the context from a static method in the class, that mean that method is called before the class is actually initialized. If there is no actual instance of the activity or if the OS haven't provide with context to the activity, then is null. The Activity has access to the contexto but after the Android underlining management initialized it, the class won't have the context by it self because it is there, if you notice Activities are never instantiated using the constructor because Android does it for you.
If you want to use a static method to having a nice syntax then the static method should be inside the class that use the shared preferences and should be passed from the activity, during any method of the Activity life cycle or when the user interacts with the ui (those listeners are set on the Activity life cycle).
class MyPreferences {
static void save(String toSave, Contex context) {
//TODO your operation here
}
}
And your activity:
public class MainActivity extends AppCompatActivity {
//Below is pseudo code, be careful on doing this precisely in the activity
#Override
onCreate() {
//TODO call super and setContentView
MyPreferences.save("foo", this);
}
}
It seems your problem is you are trying to make the other class to use the Activity, but in Android is the Activity that uses other classes

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

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.

getSharedPreferences() is not recognized in the class extended from BroadcastReceiver

I like to use SharedPreferences in the class extended from BroadcastReceiver. But this method getSharedPreferences(prefName, MODE_PRIVATE); is not recognized. How can I retrieve SharedPreferences in the BroadcastReceiver class?
Thanks
you need a Context to retrieve the SharedPreferences. onReceive gives you the context
getSharedPreferences is a method of Context, your activity extends Context that is why you can use it as is.
If you want to use it somewhere else, you need a context. The easiest way is provided in this answer
Static way to get 'Context' on Android?
Step 1 : You add a class in AndroidManifest.xml
Step 2 : You create your class this way
public class App extends Application{
private static Context _context;
#Override
public void onCreate() {
super.onCreate();
_context = this;
}
public static Context getContext(){
return _context;
}
}
Step 3 : Whenever you need something with a context you do : App.getContext()
in your case App.getContext().getSharedPreferences()

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;

How to obtain AssetManager without reference to Context?

I have a class that needs to obtain a reference to it's application's AssetManager. This class does not extend any sort of android UI class, so it doesn't have a getContext() method, or anything similar. Is there some sort of static Context.getCurrentApplicationContext() type of method?
To clarify: my class is intended to be used like a library, for other applications. It has no associated AndroidManifest.xml or control over the context which is calling it.
Create a subclass of Application, for instance public class App extends Application {
Set the android:name attribute of your <application> tag in the AndroidManifest.xml to point to your new class, e.g. android:name=".App"
In the onCreate() method of your app instance, save your context (e.g. this) to a static field named app and create a static method that returns this field, e.g. getApp():
This is how it should look:
public class App extends Application{
private static Context mContext;
#Override
public void onCreate() {
super.onCreate();
mContext = this;
}
public static Context getContext(){
return mContext;
}
}
Now you can use: App.getContext() whenever you want to get a context, and then getAssetManager() (or App.getContext().getAssetManager()).
I am not sure of the best answer to the OP question. However, I do know that you have to be very careful when using a static context as suggested in Android developer resources:
In the onCreate() method of your app instance, save your context (e.g. this) to a static field named app and create a static method that returns this field, e.g. getApp():
Using static contexts can leak to leaked memory issues, especially if the static context is used for references to views.

Categories

Resources