How to get a preference value into a static String variable? - java

I am getting the following error message:
"Cannot make a static reference to the non-static method
getPreferences(int) from the type Activity" is the error in my case.
'TimeCardLogin' must be a static variable."
How do I get a preference into a static String variable?
public class MyBaseURLContainer extends Activity {
public static String urlPref = "";
static String BASE_URL =
getPreferences(MODE_PRIVATE).getString("Name of variable",urlPref);
public static final String TimeCardLogin = BASE_URL + "/timecard";
}

I'd recommend making a static getter that takes an Context as an argument. That way a) it will actually compile, and b) if your base-url changes at some point, it will load the most recent value, instead of loading once in the beginning like your program is:
private final static String PREFS = "myUrlPrefs";
public static String getBaseUrl(Context context) {
return context.getSharedPreferences(PREFS, MODE_PRIVATE).getString(
"Name of variable",urlPref);
}
You'd call it from another activity like this:
String baseUrl = MyBaseUrlContainer.getBaseUrl(this);
Or from anywhere you have access to a Context like this (an Activity is a Context):
String baseUrl = MyBaseUrlContainer.getBaseUrl(myContext);
If you absolutely have to use this code from somewhere that doesn't have access to a Context (which really should almost never be the case in an Android app), you could store the value after it's retrieved, but the first time you get the value it has to be from a Context.

Related

getting strings from other classes

hi guys im writing a method that contains a string name from other classes..
i use the String apkName and mcurrentPhotoPath in alot of activites but need to pass the value of them string into my download method.
ive tried this
public static class Stringz{
public String APK() {
return apkNames;
}
public String FILEPATH() {
return mCurrentPhotoPath;
}
}
then in my download method i use
Stringz st = new Stringz();
String apkNames = st.APK();
String mCurrentPhotoPath = st.FILEPATH();
which works fine for a single activity. but because i have multiple activites using the same string names how can i write it so my method know which string to look for in every activity
thanks guys
You need one of these two:
1) An instance of Stringz
2) A static reference to the Strings you want to access
A static reference you define as:
public static String yourString = "Some string";
And instance:
public Stringz reference = new Stringz();
//and access like:
reference.yourString;

The value for annotation attribute AssertTrue.message must be a constant expression

The error message keep disallow me to compile my project in eclipse lula. I found this only happen if my util class reading the message from resources bundle, else it is working fine.
Please advise.
Below is my code:
MessageUtil.java
private static final String MSG_FILE = "com.by.go.booking.ui.messages";
private final static ResourceBundle MESSAGE = ResourceBundle.getBundle(MSG_FILE);
public static final String LOGIN_ID_EXISTS = MESSAGE.getString("ERR1");
LoginBean.java
#AssertTrue(message = MessageUtil.LOGIN_ID_EXISTS)
public boolean isLoginIdUnique() {
boolean result = false;
// validate login ID exists
........
return result;
}
From the code above, eclipse will trigger the error message:"The value for annotation attribute AssertTrue.message must be a constant expression"
Anyway, if I modify the MessageUtil.java as below, that is not error in eclipse.
MessageUtil.java
public static final String LOGIN_ID_EXISTS = "Login is invalid";

get value from other static class to json object

Hi My android project is
A GPSTracker.java class which gives Latitude and longitude
A RemoteFetch.java class which get the JSON from an adress API is in static state
A MainActivity.java
but the url to get the json is like that :
private static final String OPEN_WEATHER_MAP_API =
"http://api.openweathermap.org/data/2.5/weather?" + "q=%s&" +"lat="+"&lon=" + "&units=metric";
My latitude and longitude are in the GPSTracker, but when I'm getting them, the it don't let me get these values as they're not in static format...
So as soon as I'm adding them in my openweatherapi url I have the error :
"Non static field cannot be referenced from a static context" .
Is there a way to "cast" a string/int format to a static format ??
If you need more info just say it to me please.
here some code
private void updateWeatherData(final String city){
new Thread(){
public void run(){
final JSONObject json = RemoteFetch.getJSON(MainActivity.this,city);
if(json == null){
handler.post(new Runnable(){
public void run(){
Toast.makeText(MainActivity.this.getApplicationContext(),R.string.place_not_found,Toast.LENGTH_LONG).show();
}
});
} else {
handler.post(new Runnable(){
public void run(){
renderWeather(json);
}
});
}
}
}.start();
}
in RemoteFetch.java
private static final String OPEN_WEATHER_MAP_API =
"http://api.openweathermap.org/data/2.5/weather?" + "q=%s&" +"lat="+"&lon=" + "&units=metric";
public static JSONObject getJSON(Context context, String city){
try {
// gps.getLatitude();
URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city));
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.addRequestProperty("x-api-key",
context.getString(R.string.open_weather_maps_app_id));
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp="";
while((tmp=reader.readLine())!=null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
You must understand the difference between a class and an instance of that class. Static fields and methods are connected to the class itself and not to it's instances.
Since as per your code, latitude and longitude are in the GPSTracker are not static,(those are instance variables) you are getting the error.
To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance and allow you an access to instance variables (in your case,latitude and longitude are in the GPSTracker ).
Try below code where you want to access latitude and longitude in the GPSTracker (in onCreate() of MainActivity for example)
GPSTracker obj = new GPSTracker();
To access the instance variable latitude and longitude use obj as below
obj.latitude or obj.longitude.
2 other points to consider for above to work:
1. Make sure you import GPSTracker class in your file where you want to use it (MainActicity.java for example), if it is outside your file's package.
2. If GPSTracker class has some other constructor defined, that you want to use, you need to call that constructor while creating an object.
You are trying to access something that is not on your scope (aka context, but in terms of language, do not confuse it with the class Context). So you either need to pass your variable as a parameter to the static method, or making the method and instance method (removing the static).
Editing for further explanation:
On some part of your code (which I suppose is not on the part you pasted), you are using an attribute. Inside your static method you cannot see that attribute.
'static' means whatever it is, it lives on the Class, while non-static things belong to instances of that class. While the code seems to be on the same place when you write it, it won't be in the same place on runtime. That's why you cannot see attributes from the instance when you are doing something on a static context (that is, inside the static method).
So you either:
pass it as a parameter, like you did with the other two (context and city),
or you remove the 'static' keyword from your toJSON method. Beware if it was being use on other places on static context, since it might throw a compilation error saying that now those other context cannot see the method!
Also, you might want to check out Gson https://sites.google.com/site/gson/gson-user-guide
A SO response on your error, read it and try to understand how it works: "Non-static method cannot be referenced from a static context" error
And some docs on class members http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
I would advice you to review basic OOP concepts, since this error you are having is a very basic one.

Implementing a class of "constants" initialized at application start not at compile time

I'm working on a Java project that uses a big class of constants like:
public final class Settings {
public static final int PORT_1 = 8888;
public static final int PORT_2 = 8889;
...
}
Now, some of the value of those constants are not available at compile time anymore so I need a way to "initialize" them at application starts (e.g. from the args[]). Once initialized there should be no way to change them. I'm not very skilled in java, how do I do this in an acceptable way?
I thought of using a singleton with something like a "one shot" set method that throws an exception if called more than one time but it seams too hacky...
You can use a static initializer like this:
public final class Settings {
public static final int PORT_1;
public static final int PORT_2;
...
static {
// create the value for PORT_1:
PORT_1 = ...;
// create the value for PORT_2:
PORT_2 = ...;
}
}
The static initializer is executed during class loading. The final keywords on PORT_1 and PORT_2 protects them to be changed afterwards.
Well, using system properties is a way of doing it unless there is a huge amount of constants.
private static final String CONSTANT1 = System.getProperty("my.system.property");
private static final int CONSTANT2 = Integer.valueOf(System.getProperty("my.system.property"));
System properties are passed on the command line when starting the application using the -D flag.
If there are too many variables a static initializer can be used where a property file or similar can be read that holds the properties:
public class Constants {
private static final String CONSTANT1 = System.getProperty("my.system.property");
private static final int CONSTANT2 = Integer.valueOf(System.getProperty("my.system.property"));
private static final String CONSTANT3;
private static final String CONSTANT4;
static {
try {
final Properties props = new Properties();
props.load(
new FileInputStream(
System.getProperty("app.properties.url", "app.properties")));
CONSTANT3 = props.getProperty("my.constant.3");
CONSTANT4 = props.getProperty("my.constant.3");
} catch (IOException e) {
throw new IllegalStateException("Unable to initialize constants", e);
}
}
}
Note that if you are using some external framework such as Spring Framework or similar there is usually a built-in mechanism for this. E.g. - Spring Framework can inject properties from a property file via the #Value annotation.
There is no simple way to do this in Java. One way to simulate this is to use a builder which returns an internal type (so it can write the private fields) but the internal type only has getters.
See this answer: https://stackoverflow.com/a/1953567/34088

Error class message creation way

I need to create message class that can retrieve the data for message and print it out the problem is that I must provide in the message class to the static filed value like (public static String exc01 ="testErr";) if I remove the equal "testErr"; Im getting an error;
Exception in thread "main" java.lang.NullPointerException
at java.util.PropertyResourceBundle.handleGetObject(Unknown Source)
at java.util.ResourceBundle.getObject(Unknown Source)
at java.util.ResourceBundle.getString(Unknown Source)
at test1.Messages.getString(Messages.java:19)
at test1.TestMessageClass.main(TestMessageClass.java:8)
1.why should I provide value to the static string exc01 in class message if the message properties file already contain the error value?
2.there is better/nicer to do this all logic of messages ?
for that I have created message class as follows
package msg;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
private static final String BUNDLE_NAME = "test1.messages";
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
public static String exc01 ="testErr";
public static String exc02;
private Messages() {
}
public static String getString(String key) {
try {
return RESOURCE_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
}
I have file for message under the same package which is called messages.properties and contain the following message
exc01=Failed to create the extension for {0}
exc02=Failed to create the extension
I have created simple test program
public class TestMessageClass {
public static void main(String[] args) {
System.out.println(Messages.getString("exc01"));
System.out.println(Messages.getString(Messages.exc01));
}
}
print
Failed to create the extension for {0}
!testErr!
Your code calls
Messages.getString(Messages.exc01)
Messages.exc01 is a variable or type String. Its default value is null. It's not "exc01" as you seem to believe. You're confusing the name of a variable with its value.
So, if you don't initialize the variable, the code above tries to get the message from the properties file having a null key, which doesn't make sense: you must provide a non-null key, and that's why you get a NullPointerException.
If you want to get the message for the key "exc01", then you can use
Messages.getString("exc01")
or you can initialize any String variable to "exc01", and pass this variable:
public static String exc01 = "exc01";
...
Messages.getString(Messages.exc01);
Note that exc01 should be defined as a constant, and not as a variable. It should thus be final, and respect the Java naming conventions for constants:
public static final String EXC01 = "exc01";
...
Messages.getString(Messages.EXC01);
Note that if you initialize the variable with "testErr", as you did, the code will look for the message associated with the key "testErr" in the properties file. And since such a message doesn't exist, you'll get a MissingResourceException, and the ctach block will thus return !testErr!. That's why you have !testErr! in your test output.

Categories