0

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());
stmorray
  • 1
  • 6

2 Answers2

0

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.

Community
  • 1
  • 1
Logain
  • 4,259
  • 1
  • 23
  • 32
  • Thanks for your answer, I don't really know how to do this, the method to get the json is like that : public static JSONObject getJSON(Context context, String city){ try { URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city)); So, I have to add, something after String city, like double latitude ? and if I remove the static I have "Non-static method "getJSON..." cannot be referenced from a static context – stmorray Feb 06 '15 at 10:16
  • I edited my response with a more detailed explanation and links – Logain Feb 06 '15 at 10:24
0

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.

AADProgramming
  • 6,077
  • 11
  • 38
  • 58
  • The only way to make Latitude and Longitude available in RemoteFetch.java is to put GPSTracker gpsTracker = new GPSTracker(this); in the onCreate but as RemoteFetch is not an Activity... – stmorray Feb 09 '15 at 10:54
  • nevermind, I need a way to be able to give these values(now I've got them) to the json api url, because as soon as I'm adding "+ latitude" to my json url I get ""Non static field cannot be referenced from a static context" . " but I can't make the getJSON method non static as I will get this error : "Error:(147, 53) error: non-static method getJSON(Context,String) cannot be referenced from a static context" at the line " final JSONObject json = RemoteFetch.getJSON(MainActivity.this,city); " this come from my MainActivity.java – stmorray Feb 09 '15 at 10:59