-1

I have been trying to create a weather app that gives the weather of the current location by using an api call. I am relatively new to coding and i am not able to figure out what the problem is in my code that a null pointer error keeps popping up.The error happens on the getTemperature() This is the code for the weatherData Model:

package com.londonappbrewery.climapm;

public class WeatherController extends AppCompatActivity {

    // Constants:
    final String WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather";
    // App ID to use OpenWeather data
    final String APP_ID = "XXXXXXXXXXXXXXXXXXX";
    // Time between location updates (5000 milliseconds or 5 seconds)
    final long MIN_TIME = 5000;
    // Distance between location updates (1000m or 1km)
    final float MIN_DISTANCE = 1000;
    final int REQUEST_CODE = 123;

String LOCATION_PROVIDER = LocationManager.GPS_PROVIDER;


    // Member Variables:
    TextView mCityLabel;
    ImageView mWeatherImage;
    TextView mTemperatureLabel;

    LocationManager mLocationManager;
    LocationListener mLocationListener;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weather_controller_layout);

        // Linking the elements in the layout to Java code
        mCityLabel = (TextView) findViewById(R.id.locationTV);
        mWeatherImage = (ImageView) findViewById(R.id.weatherSymbolIV);
        mTemperatureLabel = (TextView) findViewById(R.id.tempTV);
        ImageButton changeCityButton = (ImageButton) findViewById(R.id.changeCityButton);


        // TODO: Add an OnClickListener to the changeCityButton here:

    }


    // TODO: Add onResume() here:
    @Override
    protected void onResume() {
        super.onResume();
        Log.d("Clima", "onResume() called");
        Log.d("Clima", "Getting weather for location");
        getWeatherForCurrentLocation();
    }


    // TODO: Add getWeatherFor`enter code here`NewCity(String city) here:`enter code here`


    // TODO: Add getWeatherForCurrentLocation() here:
    private void getWeatherForCurrentLocation() {
        Log.d("Clima", "onLocationChanged() callback received");
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        mLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Log.d("Clima","onLocationChanged Called");
                String longtitude = String.valueOf(location.getLongitude());
                String latitude = String.valueOf(location.getLatitude());
                Log.d("Clima", "The long is "+ longtitude);
                Log.d("Clima", "The latitude is "+ latitude);

                RequestParams params = new RequestParams();
                params.put("lat",latitude);
                params.put("lon",longtitude);
                params.put("appid",APP_ID);
                letsDoSomeNetworking(params);

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {
                Log.d("Clima", "onProviderDisabled");
            }
        };
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE);
            return;
        }
        mLocationManager.requestLocationUpdates(LOCATION_PROVIDER, MIN_TIME, MIN_DISTANCE, mLocationListener);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==REQUEST_CODE){
            if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                 Log.d("Clima","Permission granted");
                 getWeatherForCurrentLocation();
            }else {
                Log.d("Clima","Permission denied");
            }
        }

    }


    private void letsDoSomeNetworking(RequestParams params){
        AsyncHttpClient client = new AsyncHttpClient();

        client.get(WEATHER_URL,params,new JsonHttpResponseHandler(){
          @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response){

              Log.d("Clima","Success! JSON: "+response.toString());
              WeatherDataModel weatherData = WeatherDataModel.fromJson(response);
              updateUI(weatherData);
          }
          @Override
            public void onFailure(int statusCode, Header[] headers,Throwable e, JSONObject response){
              Log.e("Clima","Fail"+e.toString());
              Log.d("Clima","Status code"+statusCode);
              Toast.makeText(WeatherController.this,"Req failed",Toast.LENGTH_SHORT);
          }

        });

    }



    // TODO: Add updateUI() here:
    private void updateUI(WeatherDataModel weather){
        mTemperatureLabel.setText(weather.getTemperature());
        mCityLabel.setText(weather.getCity());

        int resID = getResources().getIdentifier(weather.getIconName(),"drawable",getPackageName());
        mWeatherImage.setImageResource(resID);
    }

}

THIS IS THE DATAMODEL CODE:

package com.londonappbrewery.climapm;

import org.json.JSONException;
import org.json.JSONObject;

public class WeatherDataModel {

    // TODO: Declare the member variables here
    private String mTemperature;
    private int mCondition;
    private String mCity;
    private String mIconName;


    // TODO: Create a WeatherDataModel from a JSON:
    public static WeatherDataModel fromJson(JSONObject jsonObject){

        try {
            WeatherDataModel weatherData = new WeatherDataModel();

            weatherData.mCity = jsonObject.getString("name");
            weatherData.mCondition=jsonObject.getJSONArray("weather").getJSONObject(0).getInt("Id");
            weatherData.mIconName =updateWeatherIcon(weatherData.mCondition);

            double tempResult = jsonObject.getJSONObject("main").getDouble("temp")-273.15;
            int roundedValue = (int) Math.rint(tempResult);

            weatherData.mTemperature = Integer.toString(roundedValue);

            return weatherData;
        }catch (JSONException e){
            e.printStackTrace();
            return null;
        }
    }


    // TODO: Uncomment to this to get the weather image name from the condition:
    private static String updateWeatherIcon(int condition) {

        if (condition >= 0 && condition < 300) {
            return "tstorm1";
        } else if (condition >= 300 && condition < 500) {
            return "light_rain";
        } else if (condition >= 500 && condition < 600) {
            return "shower3";
        } else if (condition >= 600 && condition <= 700) {
            return "snow4";
        } else if (condition >= 701 && condition <= 771) {
            return "fog";
        } else if (condition >= 772 && condition < 800) {
            return "tstorm3";
        } else if (condition == 800) {
            return "sunny";
        } else if (condition >= 801 && condition <= 804) {
            return "cloudy2";
        } else if (condition >= 900 && condition <= 902) {
            return "tstorm3";
        } else if (condition == 903) {
            return "snow5";
        } else if (condition == 904) {
            return "sunny";
        } else if (condition >= 905 && condition <= 1000) {
            return "tstorm3";
        }

        return "dunno";
    }

    // TODO: Create getter methods for temperature, city, and icon name:


    public String getTemperature() {
        return mTemperature;
    }

    public String getCity() {
        return mCity;
    }

    public String getIconName() {
        return mIconName;
    }
}
Ryan M
  • 18,333
  • 31
  • 67
  • 74
Vin
  • 1
  • NEVER expose your API Keys on public websites. You should create a new one now. Did you check that the `fromJson()` method did not return null? – P.J.Meisch May 24 '20 at 11:27
  • I recommend your data model holding the temperature as a `double` internally. There's too much unnecessary conversion. Handle the conversion only in the presentation layer. Check the `double` value on extract from the JSON. – codebod May 24 '20 at 18:32
  • It's very difficult to debug a crash without a stack trace. See [Unfortunately MyApp has stopped. How can I solve this?](/q/23353173) for Android-specific advice, and [What is a stack trace, and how can I use it to debug my application errors?](/q/3988788) for advice on what to do once you have the stack trace. If you still need help, edit your question to include the **complete stack trace**, as well as **which line of your code** the stack trace points to. – Ryan M May 27 '20 at 02:11

1 Answers1

-1

You initialize your object over a json file.

WeatherDataModel weatherData = WeatherDataModel.fromJson(response);

Perhaps your json got no data for temparature, what is the content of response.

adminfd
  • 1,006
  • 7
  • 14
  • Hey Thanks for the response! The response is this JSON: {"coord":{"lon":55.32,"lat":25.24},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"stations","main":{"temp":308.62,"feels_like":310.23,"temp_min":308.15,"temp_max":309.15,"pressure":1008,"humidity":41},"visibility":8000,"wind":{"speed":3.1,"deg":180},"clouds":{"all":60},"dt":1590386922,"sys":{"type":1,"id":7537,"country":"AE","sunrise":1590370207,"sunset":1590418894},"timezone":14400,"id":292223,"name":"Dubai","cod":200} – Vin May 25 '20 at 06:14
  • Essentially I am able to receive a response from the api call but when i access the object using the code i've posted the error occurs – Vin May 25 '20 at 06:18