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) Working with JSON Exploring the Data

Getting fatal exception in main error for Stormy project

When I added the code for isNotworkAvailable to the project I started to get fatal exceptions in main, so I commented the code out and I'm still getting the error. Any I ideas?

HERE ARE THE ERRORS:

06-18 15:50:19.716 1410-1410/com.example.slapdash.stormy E/AndroidRuntime: FATAL EXCEPTION: main java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.slapdash.stormy/com.example.slapdash.stormy.MainActivity}: java.lang.IllegalStateException: System services not available to Activities before onCreate() at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) at android.app.ActivityThread.access$600(ActivityThread.java:141) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5041) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate() at android.app.Activity.getSystemService(Activity.java:4463) at com.example.slapdash.stormy.MainActivity.<init>(MainActivity.java:89) at java.lang.Class.newInstanceImpl(Native Method) at java.lang.Class.newInstance(Class.java:1319) at android.app.Instrumentation.newActivity(Instrumentation.java:1054) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)  at android.app.ActivityThread.access$600(ActivityThread.java:141)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)  at android.os.Handler.dispatchMessage(Handler.java:99)  at android.os.Looper.loop(Looper.java:137)  at android.app.ActivityThread.main(ActivityThread.java:5041)  at java.lang.reflect.Method.invokeNative(Native Method)  at java.lang.reflect.Method.invoke(Method.java:511)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793

HERE IS THE CODE FROM MainActivity.java

package com.example.slapdash.stormy;

import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast;

import java.io.IOException;

import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

public static final String TAG = MainActivity.class.getSimpleName();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    if (fab != null) {
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();


           }
        });
    }

    String apiKey = "8dee9648401ee3996f1f457e02dd2b98";
    double latitude = 37.8267;
    double longitude = -122.423;
    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(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    Log.v(TAG, response.body().string());
                    if (response.isSuccessful()) {

                    } else {
                        alertUserAboutError();
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Exception caought: ", e);
                }

            }
        });

    }
    //else{
       // Toast.makeText(this, R.string.network_unavailable_message, Toast.LENGTH_LONG).show();
        //System.out.println("Network unavailable");
    //}
//}

//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");
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;


}

}

2 Answers

aakarshrestha
aakarshrestha
6,509 Points

Uncomment the following line:

ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

Also, you have one curly bracket uncommented before "else" statement. Comment that out:

} -> COMMENT THIS OUT
    //else{
       // Toast.makeText(this, R.string.network_unavailable_message, Toast.LENGTH_LONG).show();
        //System.out.println("Network unavailable");
    //}

Clean build the project and see it the problem is solved.

Hope it helps!

Happy coding!

Thank you for responding. I found that I had to comment out the if statement that corresponded to the else, in order to get it to run. It will run, but will not test if the network is working.