Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Weather App (2015) Hooking Up the Model to the View Plugging in the Data

Ragesh Kanagaraj
Ragesh Kanagaraj
3,637 Points

Null Pointer Exception while updating Screen with temparature value

I am able to log the Temperature value. But mTextViewOfTemp.setText is not working as expected. Instead it throws a Null Pointer Exception.

My Code :

private final String TAG=MainActivity.class.getSimpleName(); private String apiKey="8022f02a6d3c015aa15a6b1728a1fdf5"; private double latitude = 13.0827; private double longitude = 80.2707; CurrentWheather mCurrentWheather = new CurrentWheather();

private String url="https://api.forecast.io/forecast/"+apiKey+"/"+latitude+","+longitude;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if(isNetworkAvailable()){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call=okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {



            }
  @Override
            public void onResponse(Response response) throws IOException {
                try{
                    if(response.isSuccessful()){
                        String jsonData=response.body().string();
                        Log.v(TAG, jsonData);
                        Log.d(TAG, url);
                        mCurrentWheather=getCurrentDetails(jsonData);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                updateUIScreen();
                            }
                        });

                    }else{
                        alertUserOnFailure();
                    }
                }catch(IOException e){
                    Log.e(TAG,"Caught Exception : "+e);
                }catch(JSONException e){
                    Log.e(TAG,"Caught Exception : "+e);
                }
           }
        });
    }else{
        alertUserOnNetworkFailure();
        Toast.makeText(this,"No Netwrok!",Toast.LENGTH_LONG).show();
    }}
   private CurrentWheather getCurrentDetails(String jsonData) throws JSONException{

    CurrentWheather currentWheather = new CurrentWheather();

    JSONObject forecast=new JSONObject(jsonData);
    String timezone=forecast.getString("timezone");
    currentWheather.setTimeZone(timezone);
    Log.i(TAG, timezone);
    JSONObject currently =forecast.getJSONObject("currently");
    currentWheather.setHumidity(currently.getDouble("humidity"));
    currentWheather.setIcon(currently.getString("icon"));
    currentWheather.setPreciptationChance(currently.getDouble("precipProbability"));
    currentWheather.setTemparature(currently.getDouble("temperature"));
    currentWheather.setSummary(currently.getString("summary"));
    currentWheather.setTime(currently.getLong("time"));
     Log.d(TAG,currentWheather.getFormattedTime());
      return currentWheather;
}

private void updateUIScreen() {
    /*mTemparatureValue.setText(mCurrentWheather.getTemparature()+"");
    mHumidityValue.setText(mCurrentWheather.getHumidity()+"");*/
    Log.i(TAG,mCurrentWheather.getTemparature()+"");
    mTemparatureValue.setText(mCurrentWheather.getTemparature()+"");


}}
private boolean isNetworkAvailable() {

    boolean networkStatus=false;
    ConnectivityManager manager= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = manager.getActiveNetworkInfo();
    assert info != null;
    if(info!=null && info.isAvailable() && info.isConnected()){
        networkStatus=true;
    }

    return networkStatus;
}

My Logs: '''06-02 23:19:34.755 27225-27241/com.example.ragesh.myweather D/MainActivity﹕ https://api.forecast.io/forecast/8022f02a6d3c015aa15a6b1728a1fdf5/13.0827,80.2707 06-02 23:19:34.815 27225-27241/com.example.ragesh.myweather I/MainActivity﹕ Asia/Kolkata 06-02 23:19:34.817 27225-27241/com.example.ragesh.myweather D/MainActivity﹕ 11:20 pm 06-02 23:19:34.818 27225-27225/com.example.ragesh.myweather I/MainActivity﹕ 82.35 06-02 23:19:34.819 27225-27225/com.example.ragesh.myweather D/AndroidRuntime﹕ Shutting down VM 06-02 23:19:34.819 27225-27225/com.example.ragesh.myweather W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41a43d40) 06-02 23:19:34.820 27225-27225/com.example.ragesh.myweather E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.ragesh.myweather, PID: 27225 java.lang.NullPointerException at com.example.ragesh.myweather.MainActivity.updateUIScreen(MainActivity.java:135) at com.example.ragesh.myweather.MainActivity.access$300(MainActivity.java:30) at com.example.ragesh.myweather.MainActivity$1$1.run(MainActivity.java:75) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5086) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) at dalvik.system.NativeStart.main(Native Method) 06-02 23:19:34.823 924-1877/? W/ActivityManager﹕ Force finishing activity com.example.ragesh.myweather/.MainActivity 06-02 23:19:34.835 1796-5289/? W/ContextImpl﹕ Calling a method in the system process without a qualified user: android.app.ContextImpl.sendBroadcast:1252 android.content.ContextWrapper.sendBroadcast:365 com.motorola.motocare.util.TriggerHelper$TriggerBuilder.send:76 com.motorola.motocare.internal.frameworkevents.PauseResumeTrigger.handleFrameworkEvent:53 com.motorola.motocare.internal.frameworkevents.FwEventMonitor$FrameworkListener.processFrameworkEvent:114 06-02 23:19:35.053 924-1000/? D/WifiStateMachine﹕ handleMessage: E msg.what=151572

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

I'm not seeing where you're setting the member variable "mTemparatureValue" to the corresponding TextView (either through findViewById() or ButterKnife). If left uninitialized that would cause the NullPointerException.

Ragesh Kanagaraj
Ragesh Kanagaraj
3,637 Points

I am setting it in the below function, I have mentioned this function above as well. Guess due to the code version the text is not clear above.

private void updateUIScreen() { /mTemparatureValue.setText(mCurrentWheather.getTemparature()+""); mHumidityValue.setText(mCurrentWheather.getHumidity()+"");/ Log.i(TAG,mCurrentWheather.getTemparature()+""); mTemparatureValue.setText(mCurrentWheather.getTemparature()+"");

}}

Seth Kroger
Seth Kroger
56,413 Points

Perhaps I wasn't being clear. mTemparatureValue itself has to be set to a TextView before you can call any methods from it. This is usually done in onCreate() after the setContentView() call. You need to do this for every UI element you want to change dynamically in the Activity. When left uninitialized, it's essentially pointing nowhere, and will throw a null pointer exception when you try to call any methods from it (at least all non-static ones).