IllegalStateException “System services not availab

2019-07-08 18:59发布

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.

3条回答
Summer. ? 凉城
2楼-- · 2019-07-08 19:10

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

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-07-08 19:24

Try to change:

public class MainActivity extends Activity {

  @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();
    }
查看更多
一夜七次
4楼-- · 2019-07-08 19:28

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;
    }
    }
    }
查看更多
登录 后发表回答