Android System services not available to Activities before onCreate() [closed]

僤鯓⒐⒋嵵緔 提交于 2019-12-14 03:38:12

问题


....    

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ...

done = true;
}

...


public class addcontacts extends ListActivity {

     protected void onCreate() {

     }
     protected void execute(final Boolean success) {
if (done) {
         adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
         setListAdapter(adapter);
}
     }

 }


public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

@Override
    protected Boolean doInBackground(Void... params) {

...

}
 @Override
    protected void onPostExecute(final Boolean success) {

            setContentView(R.layout.main);


            ac = new addcontacts();
            ac.execute(true);


    }

...

public class getcontacts extends AsyncTask<Void, Void, Boolean> {
    @Override
    protected Boolean doInBackground(Void... params) {


...
listItems.add(json_data.getString("login") + " " + derp);
...
}

...
}

 @Override
    protected void onPostExecute(final Boolean success) {
        getc = null;
        //showProgress(false);
        adapter.notifyDataSetChanged();
}

Runtime error:

 02-12 15:59:35.274: E/AndroidRuntime(1308): FATAL EXCEPTION: main
 02-12 15:59:35.274: E/AndroidRuntime(1308): java.lang.IllegalStateException: System services not available to Activities before onCreate()
 02-12 15:59:35.274: E/AndroidRuntime(1308):    at android.app.Activity.getSystemService(Activity.java:3989)

 02-12 15:59:35.274: E/AndroidRuntime(1308):    at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
 02-12 15:59:35.274: E/AndroidRuntime(1308):    at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:153)

Any ideas how to fix it?


回答1:


The only thing that is broken is your code. Fix would be to avoid access to system services prior onCreate() is completed otherwise there's no setup made yet to the activity object, hence the self-explaining-the-cause exception you facing.



来源:https://stackoverflow.com/questions/14836898/android-system-services-not-available-to-activities-before-oncreate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!