IllegalStateException“在onCreate()之前,活动不可用的系统服务”

时间:2013-08-27 07:59:27

标签: android eclipse illegalstateexception

我调查了这个问题,但无法找到我的代码的任何解决方案。我有四节课。但我相信,名为Connect的类没有问题(你将在下面的类JsonData上看到它的对象。)所以我分享了其他三个类。我的MainActivity是;

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();
    }
}

我为json发送keyvalues,然后从类JsonData上的任何url(它是私有的,我删除它)中获取数据;

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;

    }
}

在这个课程中,我检查来自对象netCheck的互联网连接。我认为我的问题出在那个班级。 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;
    }
}

我怀疑来自注释行** //获取Connectivity Manager对象来检查连接**。 最后我的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)

我再次说,我查看了其他问题,但没有可用的解决方案。提前谢谢。

3 个答案:

答案 0 :(得分:4)

InternetCheck是一个Activity类。活动由startActivity开始。 getSystemService需要活动背景。

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

你有这个

public class JsonData extends Activity

你这样做

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

您需要的是实用工具类而不是活动类。此外,如果您正在进行与网络相关的操作,请在threadAsynctask

中执行此操作
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;
            }

        }
    }
}

签入任何活动

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

您可能已连接到wifi,但wifi可能无法连接到网络。这仅检查网络连接可用性。

编辑:

    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;
    }
    }
    }

答案 1 :(得分:2)

您的JSONParser扩展了活动,但它不是活动。删除extends活动并将其作为对象调用。

您还需要从InternetCheck类中删除extends活动。

然后将您的上下文传递给JSONData类并使用您的InternetCheck类

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);

     }

然后在您的InternetCheck类中接受构造函数中的上下文并替换所有

getBaseContext()

使用context变量

答案 2 :(得分:0)

尝试改变:

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();
    }