IllegalStateException "System services not available to Activities before onCreate()"

13,089

Solution 1

InternetCheck is a Activity class. Activity is started by startActivity. getSystemService requires activity context.

http://developer.android.com/reference/android/content/Context.html#getSystemService(java.lang.String)

You have this

public class JsonData extends Activity

And you do this

JsonData jsonData = new JsonData(); //Activity is started by `startActivity`
// wrong  

What you need is a utility class not an activity class. Also if you are doing network related operation do it in a thread or Asynctask

public class CheckNetwork {


    private static final String TAG = CheckNetwork.class.getSimpleName();



    public static boolean isInternetAvailable(Context context)
    {
        NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
        context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

        if (info == null)
        {
             Log.d(TAG,"no internet connection");
             return false;
        }
        else
        {
            if(info.isConnected())
            {
                Log.d(TAG," internet connection available...");
                return true;
            }
            else
            {
                Log.d(TAG," internet connection");
                return true;
            }

        }
    }
}

To check in any activity

 if(CheckNetwork.isInternetAvailable(ActivityName.this)) 
 // use activity context
 // will return true if network connection is available.

You may be connected to wifi but wifi may not be connect to net. This only checks for network connection availability.

Edit:

    public class MainActivity extends Activity {

        String keys[] = {"Message", "Subject", "MessageType", "SentTime", "ToName", "Id"};
        ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
                if(CheckNetwork.isInternetAvailable(MainActivity.this)) 
                {
            JsonData jsonData = new JsonData();
            jsonData.execute();
                }else
                 {
                  //display toast no network connection available
                 }   

        }

        public void getData()
        {

                // get json data from url and it to dataList   

            }
  class JsonData extends AsyncTask<Void,Void,Void>{
  private String url = "url"; 

    @Override
protected void onPostExecute(Void result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    // dismiss progress dialog
    // update ui
}

@Override
protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
    // display progress dialog
}

    @Override
    protected Void doInBackground(Void... params) {
      getData(); // get data
       // network related operation
       //  do not update ui here.             
    return null;
    }
    }
    }

Solution 2

Your JSONParser extends activity but it's not an activity. Remove the extends Activity and call it as an object.

You'll also need to remove the extends Activity from your InternetCheck class.

Then pass your context to the JSONData class and use your InternetCheck class like this

public class JsonData extends Activity{

     Connect connect = new Connect();
     private String url = "url"; 

     static String keys[];

     public JsonData(Context context){

          InternetCheck netCheck = new InternetCheck(context);

     }

Then in your InternetCheck class accept the context in the constructor and replace all

getBaseContext()

with your context variable

Share:
13,089
Batuhan Coşkun
Author by

Batuhan Coşkun

Lead Android Developer works on Protel.

Updated on July 14, 2022

Comments

  • Batuhan Coşkun
    Batuhan Coşkun almost 2 years

    I investigate that problem but can not find any solution for my code. I have four classes. But i am sure, no problem on class named Connect(You will see its object on class JsonData below.)So i share the other three classes. My MainActivity is;

    public class MainActivity extends Activity {
    
        String keys[] = {"Message", "Subject", "MessageType", "SentTime", "ToName", "Id"};
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            JsonData.keys=keys;
    
            JsonData jsonData = new JsonData();
            ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
            dataList= jsonData.GetData();
        }
    }
    

    I send keyvalues for json and then take data from any url(it is private, i delete it) on class JsonData;

    public class JsonData extends Activity{
    
        Connect connect = new Connect();
        private String url = "url"; 
    
        static String keys[];
    
        public ArrayList<HashMap<String, String>> GetData() {
    
            JSONArray json = null;
            ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
            InternetCheck netCheck = new InternetCheck();
            if(netCheck.isInternetOn()){
                try {
                    JSONObject result = connect
                        .connect(url);
                    json = result.getJSONArray("d");
    
                    for (int i = 0; i < json.length(); i++) {
                        HashMap<String, String> hashmap = new HashMap<String, String>();
                        JSONObject json2 = json.getJSONObject(i);
                        for (int j = 0; j < keys.length; j++){
                            hashmap.put(keys[j], json2.getString(keys[j]));
                        }
                        mylist.add(hashmap);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }   
            } 
            else
                Toast.makeText(this, " Check Internet Options. ", Toast.LENGTH_LONG).show();
            return mylist;
    
        }
    }
    

    In this class, i check internet connection from object netCheck. I think my problem is on that class. InternetCheck.java ;

    public class InternetCheck extends Activity {
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
        }
    
        public final boolean isInternetOn() {
    
            // get Connectivity Manager object to check connection
            ConnectivityManager connec =  (ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE);
    
            // Check for network connections
            if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
                 connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
                 connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
                 connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {
                return true;
    
            } else if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||  connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED  ) {
                return false;
            }
            return false;
        }
    }
    

    I am suspecting from the commented line **//get Connectivity Manager object to check connection ** . Finally my Logcat;

    08-27 10:13:45.449: E/AndroidRuntime(24925): FATAL EXCEPTION: main
    08-27 10:13:45.449: E/AndroidRuntime(24925): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsonparser/com.example.jsonparser.MainActivity}: java.lang.IllegalStateException: System services not available to Activities before onCreate()
    08-27 10:13:45.449: E/AndroidRuntime(24925):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1659)
    08-27 10:13:45.449: E/AndroidRuntime(24925):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
    08-27 10:13:45.449: E/AndroidRuntime(24925):    at android.app.ActivityThread.access$1500(ActivityThread.java:121)
    08-27 10:13:45.449: E/AndroidRuntime(24925):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
    08-27 10:13:45.449: E/AndroidRuntime(24925):    at android.os.Handler.dispatchMessage(Handler.java:99)
    08-27 10:13:45.449: E/AndroidRuntime(24925):    at android.os.Looper.loop(Looper.java:130)
    08-27 10:13:45.449: E/AndroidRuntime(24925):    at android.app.ActivityThread.main(ActivityThread.java:3768)
    08-27 10:13:45.449: E/AndroidRuntime(24925):    at java.lang.reflect.Method.invokeNative(Native Method)
    08-27 10:13:45.449: E/AndroidRuntime(24925):    at java.lang.reflect.Method.invoke(Method.java:507)
    08-27 10:13:45.449: E/AndroidRuntime(24925):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
    08-27 10:13:45.449: E/AndroidRuntime(24925):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
    08-27 10:13:45.449: E/AndroidRuntime(24925):    at dalvik.system.NativeStart.main(Native Method)
    08-27 10:13:45.449: E/AndroidRuntime(24925): Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate()
    08-27 10:13:45.449: E/AndroidRuntime(24925):    at android.app.Activity.getSystemService(Activity.java:3536)
    08-27 10:13:45.449: E/AndroidRuntime(24925):    at com.example.jsonparser.InternetCheck.isInternetOn(InternetCheck.java:19)
    08-27 10:13:45.449: E/AndroidRuntime(24925):    at com.example.jsonparser.JsonData.GetData(JsonData.java:25)
    08-27 10:13:45.449: E/AndroidRuntime(24925):    at com.example.jsonparser.MainActivity.onCreate(MainActivity.java:21)
    08-27 10:13:45.449: E/AndroidRuntime(24925):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    08-27 10:13:45.449: E/AndroidRuntime(24925):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
    

    I'm saying again, i looked over other questions but no solution available for me. Thanks in advance.

  • Batuhan Coşkun
    Batuhan Coşkun almost 11 years
    But i must send the keys values to JsonData class.
  • Batuhan Coşkun
    Batuhan Coşkun almost 11 years
    I change my codes with your suggestions. I think this is the right way, but the same error is continues.
  • Raghunandan
    Raghunandan almost 11 years
    @Droid you also do this JsonData jsonData = new JsonData(). JsonData is a activity class activities are started by startActivity with intent. also` connect .connect(url)` all network related operation should be done on a thread. use thread or asynctask
  • Batuhan Coşkun
    Batuhan Coşkun almost 11 years
    i used debugging and the problem is on InternetCheck class and the point 'context.getSystemService(Context.CONNECTIVITY_SERVICE)).get‌​ActiveNetworkInfo();‌​'. I'm sure with that.
  • Raghunandan
    Raghunandan almost 11 years
    @Droid that is one problem if you do network related operation post honeycomb you get NetworkOnMainThreadException. check the docs developer.android.com/reference/android/os/…. and do check the edited answer. i am sure if you make the changes it will work
  • Batuhan Coşkun
    Batuhan Coşkun almost 11 years
    I can not solve the problem, i changed InternetCheck class codes with your codes. I used startActivity for JsonData class. But the same problem is continues :(
  • Raghunandan
    Raghunandan almost 11 years
    @Droid check the edit. i made JsonData extend asynctask. ALso i made it an inner class. Declared dataList as a class member so you can add the data to the list in getData. Check network availability before invoking asynctask. modify the above accordingly. it will work. If this does not help i don't know in what way i can help further.
  • Raghunandan
    Raghunandan almost 11 years
    @Droid glad to help. always remember to do network related operation on the thread.
  • Batuhan Coşkun
    Batuhan Coşkun almost 11 years
    Thank you for that, i never forget this from now on :)
  • Chris Stratton
    Chris Stratton almost 10 years
    Untrue, this is the solution.
  • Chris Stratton
    Chris Stratton almost 10 years
    This is not the answer, because the problem is with JsonData trying to behave as an activity, when it is not really one, and not being created as one.