为什么要跳过我的班级创建

时间:2017-05-27 21:50:02

标签: java android class oncreate

好的,对于我的生活中的这个错误,我无法弄明白,甚至不知道该怎么去google了。 这是我初级课程的一个片段。 (You can view the whole thing here

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("Avariel", "I am running");

        RealmManager realmManager = new RealmManager();

        Log.i("Avariel", "I have passed RM");

在其中,我正在尝试创建一个Realm Manager(You can view the whole class here)类。此时我甚至可以显示"I am running Realm Manager's on Create"。当我调试时它只是冻结。

public class RealmManager extends Activity {

    public static final String TAG = MainFragmentActivity.class.getName();
    private Realm realm;

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

        Log.i("Avariel REALM", "I am running Realm Manager's on Create");
        /**
         * https://realm.io/docs/java/latest/#getting-started
         * http://facebook.github.io/stetho/
         * https://github.com/uPhyca/stetho-realm
         * chrome://inspect/#devices
         */
       /* Stetho.initializeWithDefaults(this);
        Realm.init(this);
        Stetho.initialize(
                Stetho.newInitializerBuilder(this)
                        .enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
                        .enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build())
                        .build());

        realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        Player player = realm.createObject(Player.class);
        player = player.create(01, "Gideon", "Barlock", "Orc", "Lawful Evil", "Fighter", "A wandering Warrior", 0, 30, 0, null, null, null, null, null, null, null, null, null, 0);
        realm.commitTransaction();
        Realm.init(this);

        RealmConfiguration config = new RealmConfiguration.Builder().build();
        Realm.setDefaultConfiguration(config);*/
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realm.close();
    }

表示我看到的日志

05-27 22:38:13.477 32158-32158/com.example.gideonsassoon.avariel I/Avariel: I am running
05-27 22:38:13.559 32158-32158/com.example.gideonsassoon.avariel I/Avariel: I have passed RM

我在这里做错了什么。 You can view the full project here

非常感谢你的帮助,

2 个答案:

答案 0 :(得分:1)

从不通过构造函数自己创建Activity的实例。

由于RealmManager似乎不是实际活动(使用用户界面等),请从您的extends Activity声明中删除RealmManager。然后,您需要安排自己调用RealmManager上的方法,就像任何其他Java对象一样。

答案 1 :(得分:0)

  

“我在创建时运行Realm Manager”

不,你不是。您调用了new,它调用了默认构造函数,它从不调用onCreate

尝试以下操作来创建管理某些Realm对象的常规Java对象

public class RealmManager  {

    private final Context context;
    private final Realm realm;

    public RealmManager(Context context) {
        Log.i("Avariel REALM", "I am running Realm Manager"); 
        context = context;
        realm = Realm.getDefaultInstance();
    }

另外,

RealmManager realmManager = new RealmManager(this);

我相信所有其他代码都属于 Application 类,而不是任何活动

例如