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
Farouk Charkas
1,957 PointsWhat does logcat mean by this?
To whomever this may concern,
I keep on getting this message in the logcat. I was long expecting this due to my app crashing upon running. I do understand that the prefix "Caused by: " means that this error is crashing the app. So, after told, this is my question, "What does logcat mean by the error I am getting below?". Any help is appreciated. :-)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int everingapplications.rain_gig.CurrentWeather.getTemperature()' on a null object reference
3 Answers
Gloria Dwomoh
13,116 PointsHi again,
you should remove this:
updateDisplay();
from here in your code:
ButterKnife.inject(this);
updateDisplay();
and see if that helps.
You can get hints of it from the logcat by looking at these lines:
at everingapplications.rain_gig.MainActivity.updateDisplay(MainActivity.java:138)
at everingapplications.rain_gig.MainActivity.onCreate(MainActivity.java:75)
I believe that right after the onCreate method you can't call "UpdateDisplay" because there is no data to update the display with. You use the Forecast API to fetch the data and that happens way after that, so because it has no data to update your display with, it gives you the null exception.
Gloria Dwomoh
13,116 PointsIt says "method 'int everingapplications.rain_gig.CurrentWeather.getTemperature()' on a null object reference" so check wherever you have used getTemperature() method to see if you are referencing it correctly. You can post it here as well if you're still stuck.
Farouk Charkas
1,957 PointsHow do I search in Android Studio?, to find where I am referencing getTemperature(). And this is what I found so far:
public int getTemperature() {
return (int) Math.round(mTemperature);
Gloria Dwomoh
13,116 PointsDo ctrl + F and type the function you are looking for.
Farouk Charkas
1,957 PointsOk, thank you Gloria Dwomoh,
This is what I found:
mTemperatureLabel.setText(mCurrentWeather.getTemperature() + "°");
What did I do wrong?
Gloria Dwomoh
13,116 PointsDo you return current weather anywhere? Can you paste that part of the code too? Thanks
Farouk Charkas
1,957 Pointspublic int getTemperature() {
return (int) Math.round(mTemperature);
}
public void setTemperature(double mTemperature) {
this.mTemperature = mTemperature;
}
This is the getter and setter
Gloria Dwomoh
13,116 PointsNo I mean, do you do something like return currentWeather(); or something like that anywhere?
Farouk Charkas
1,957 PointsYes I do, here it is:
private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
android.util.Log.i(TAG, "From JSON: " + timezone);
JSONObject currently = forecast.getJSONObject("currently");
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getDouble("humidity"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setPrecipChance(currently.getDouble("precipProbabiltiy"));
currentWeather.setSummary(currently.getString("summary"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setmTimeZone(timezone);
return currentWeather;
Farouk Charkas
1,957 PointsDo you have any idea what might be the cause? Gloria Dwomoh, thank you for keeping up! :-)
Farouk Charkas
1,957 PointsSo I added the parenthesis at the end, but it is giving me an error
Gloria Dwomoh
13,116 PointsCorrection. I will need to see your full code. Can you paste it in pastebin? CurrentWeather.java (or however you called it) and the MainActivity.
Gloria Dwomoh
13,116 PointsI tried to spot the error but couldn't really find it. The code is long so it can be hard to spot. Can you paste the full logcat too? Maybe that will help.
Farouk Charkas
1,957 PointsOk, that sounds good to me. And I really appreciate your help.
This is my Main Activity
//This is my MainActivity.java
//This is the package name 'everingapplications.rain_gig'
package everingapplications.rain_gig;
//Importing the necessary
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.nfc.Tag;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
//Importing the Wi-Fi files
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
//Importing the JSON files
import org.apache.commons.logging.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
//Importing ButterKnife
import butterknife.ButterKnife;
import butterknife.InjectView;
//Importing the Toast Widget
import static android.widget.Toast.LENGTH_LONG;
//Declaring the class
public class MainActivity extends AppCompatActivity {
//Declaring the TAG String
public static final String TAG = MainActivity.class.getSimpleName();
//Declaring CurrentWeather
private CurrentWeather mCurrentWeather;
//Inject views using ButterKnife
@InjectView(R.id.timeLabel)
TextView mTimeLabel;
@InjectView(R.id.temperatureLabel)
TextView mTemperatureLabel;
@InjectView(R.id.humidityValue)
TextView mHumidityValue;
@InjectView(R.id.precipValue)
TextView mPrecipValue;
@InjectView(R.id.summaryLabel)
TextView mSummaryLabel;
//What will happen
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
updateDisplay();
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
getForecast(latitude, longitude);
android.util.Log.d(TAG, "The Main UI code is running!");
}
private void getForecast(double latitude, double longitude) {
String apiKEY = "1fc52007d735d76038460b34d37fbe16";
String forecastURL = "https://api.forecast.io/forecast/" + apiKEY +
"/" + latitude + "," + longitude;
if (isNetworkAvailable()) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastURL)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
android.util.Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(jsonData);
runOnUiThread(new Runnable() {
@Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException e) {
android.util.Log.e(TAG, "Exception caught: ", e);
} catch (JSONException e) {
}
}
});
} else {
Toast.makeText(this, "No Network Connection.", LENGTH_LONG).show();
}
}
private void updateDisplay() {
mTemperatureLabel.setText(mCurrentWeather.getTemperature() + "°");
mTimeLabel.setText("At" + mCurrentWeather.getFormattedTime() + "it will be: ");
mHumidityValue.setText("Humidity: " + mCurrentWeather.getHumidity() + "");
mPrecipValue.setText("Precip. Chances: " + mCurrentWeather.getPrecipChance() + "");
mSummaryLabel.setText(mCurrentWeather.getSummary() + "");
}
private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
android.util.Log.i(TAG, "From JSON: " + timezone);
JSONObject currently = forecast.getJSONObject("currently");
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getDouble("humidity"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setPrecipChance(currently.getDouble("precipProbabiltiy"));
currentWeather.setSummary(currently.getString("summary"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setmTimeZone(timezone);
return currentWeather;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
}
And this is my CurrentWeather
package everingapplications.rain_gig;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/**
* Created by Doctors on 8/11/2015.
*/
public class CurrentWeather {
private String mIcon;
private long mTime;
private double mTemperature;
private double mHumidity;
private double mPrecipChance;
private String mSummary;
private String mTimeZone;
public String getmTimeZone() {
return mTimeZone;
}
public void setmTimeZone(String mTimeZone) {
this.mTimeZone = mTimeZone;
}
public String getIcon() {
return mIcon;
}
public void setIcon(String mIcon) {
this.mIcon = mIcon;
}
public long getTime() {
return mTime;
}
public String getFormattedTime() {
SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
formatter.setTimeZone(TimeZone.getTimeZone(getmTimeZone()));
Date dateTime = new Date(getTime() * 1000);
String timeString = formatter.format(dateTime);
return timeString;
}
public void setTime(long mTime) {
this.mTime = mTime;
}
public int getTemperature() {
return (int) Math.round(mTemperature);
}
public void setTemperature(double mTemperature) {
this.mTemperature = mTemperature;
}
public double getHumidity() {
return mHumidity;
}
public void setHumidity(double mHumidity) {
this.mHumidity = mHumidity;
}
public int getPrecipChance() {
double precipPercentage = mPrecipChance * 100;
return (int) Math.round(mPrecipChance);
}
public void setPrecipChance(double mPrecipChance) {
this.mPrecipChance = mPrecipChance;
}
public String getSummary() {
return mSummary;
}
public void setSummary(String mSummary) {
this.mSummary = mSummary;
}
}
Farouk Charkas
1,957 PointsLogcat:
08-17 20:24:05.533 2711-2711/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
08-17 20:24:05.746 2711-2711/everingapplications.rain_gig D/AndroidRuntime﹕ Shutting down VM
08-17 20:24:05.747 2711-2711/everingapplications.rain_gig E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: everingapplications.rain_gig, PID: 2711
java.lang.RuntimeException: Unable to start activity ComponentInfo{everingapplications.rain_gig/everingapplications.rain_gig.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int everingapplications.rain_gig.CurrentWeather.getTemperature()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int everingapplications.rain_gig.CurrentWeather.getTemperature()' on a null object reference
at everingapplications.rain_gig.MainActivity.updateDisplay(MainActivity.java:138)
at everingapplications.rain_gig.MainActivity.onCreate(MainActivity.java:75)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
08-17 20:24:10.855 2711-2711/everingapplications.rain_gig I/Process﹕ Sending signal. PID: 2711 SIG: 9
Farouk Charkas
1,957 PointsFarouk Charkas
1,957 PointsOk, I have fixed the other crash, but It doesnt update the display
Gloria Dwomoh
13,116 PointsGloria Dwomoh
13,116 PointsYou might like to make a new question with your updated code and post any possible logcat error messages.