greendao:插入时出现NullPointerException

时间:2014-05-06 14:30:32

标签: java android greendao

我有一个问题。我正在学习Greendao,但在第一步我有错误..当我想使用插入时,我得到一个nullPointerException。我不知道为什么......我对id有自动增量,我不需要输入密码。我不知道如何使用它..

logcat的:

05-06 14:27:14.410: D/dalvikvm(2599): GC_FOR_ALLOC freed 93K, 6% free 3221K/3424K, paused 7ms, total 8ms
05-06 14:27:14.410: I/user(2599): dodano
05-06 14:27:14.474: D/libEGL(2599): loaded /system/lib/egl/libEGL_genymotion.so
05-06 14:27:14.478: D/(2599): HostConnection::get() New Host Connection established 0xb81a6b50, tid 2599
05-06 14:27:14.486: D/libEGL(2599): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
05-06 14:27:14.486: D/libEGL(2599): loaded /system/lib/egl/libGLESv2_genymotion.so
05-06 14:27:14.530: W/EGL_genymotion(2599): eglSurfaceAttrib not implemented
05-06 14:27:14.534: E/OpenGLRenderer(2599): Getting MAX_TEXTURE_SIZE from GradienCache
05-06 14:27:14.534: E/OpenGLRenderer(2599): MAX_TEXTURE_SIZE: 16384
05-06 14:27:14.538: E/OpenGLRenderer(2599): Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
05-06 14:27:14.538: E/OpenGLRenderer(2599): MAX_TEXTURE_SIZE: 16384
05-06 14:27:14.538: D/OpenGLRenderer(2599): Enabling debug mode 0
05-06 14:27:20.670: D/AndroidRuntime(2599): Shutting down VM
05-06 14:27:20.670: W/dalvikvm(2599): threadid=1: thread exiting with uncaught exception (group=0xa4d56b20)
05-06 14:27:20.670: E/AndroidRuntime(2599): FATAL EXCEPTION: main
05-06 14:27:20.670: E/AndroidRuntime(2599): Process: com.projectmidas.eduwords, PID: 2599
05-06 14:27:20.670: E/AndroidRuntime(2599): java.lang.NullPointerException
05-06 14:27:20.670: E/AndroidRuntime(2599):     at com.projectmidas.eduwords.MainActivity$1.onClick(MainActivity.java:59)
05-06 14:27:20.670: E/AndroidRuntime(2599):     at android.view.View.performClick(View.java:4438)
05-06 14:27:20.670: E/AndroidRuntime(2599):     at android.view.View$PerformClick.run(View.java:18422)
05-06 14:27:20.670: E/AndroidRuntime(2599):     at android.os.Handler.handleCallback(Handler.java:733)
05-06 14:27:20.670: E/AndroidRuntime(2599):     at android.os.Handler.dispatchMessage(Handler.java:95)
05-06 14:27:20.670: E/AndroidRuntime(2599):     at android.os.Looper.loop(Looper.java:136)
05-06 14:27:20.670: E/AndroidRuntime(2599):     at android.app.ActivityThread.main(ActivityThread.java:5017)
05-06 14:27:20.670: E/AndroidRuntime(2599):     at java.lang.reflect.Method.invokeNative(Native Method)
05-06 14:27:20.670: E/AndroidRuntime(2599):     at java.lang.reflect.Method.invoke(Method.java:515)
05-06 14:27:20.670: E/AndroidRuntime(2599):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-06 14:27:20.670: E/AndroidRuntime(2599):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-06 14:27:20.670: E/AndroidRuntime(2599):     at dalvik.system.NativeStart.main(Native Method)

Generator.java:

package com.projectmidas.eduwordsgeneratorbazy;

import java.io.File;
import java.io.IOException;

import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Property;
import de.greenrobot.daogenerator.Schema;

public class Generator {

    public static void main(String[] args) throws Exception {
        Schema schema = makeSchema();

        Entity user = schema.addEntity("User");
        user.addLongProperty("id").primaryKey().autoincrement();
        user.addStringProperty("email");
        user.addStringProperty("password");     

        genereteDbSchema(schema, "../EduWords/src_db/");
    }

    private static Schema makeSchema() {
        return new Schema(2, "com.projectmidas.eduwords.db");
    }

    private static void genereteDbSchema(Schema schema, String filePath)
            throws Exception, IOException {
        Util.deleteDirectory(new File(filePath), false);
        new File(filePath).mkdirs();
        new DaoGenerator().generateAll(schema, filePath);
    }

    private static class Util {

        private static void deleteDirectory(File directory, boolean deleteRoot) {
            if (directory.exists()) {
                File[] files = directory.listFiles();
                if (null != files) {
                    for (int i = 0; i < files.length; i++) {
                        if (files[i].isDirectory()) {
                            deleteDirectory(files[i], true);
                        } else {
                            files[i].delete();
                        }
                    }
                }
            }
            if (deleteRoot) {
                directory.delete();
            }
        }
    }
}

MainActivity.java:

package com.projectmidas.eduwords;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.projectmidas.eduwords.db.DaoSession;
import com.projectmidas.eduwords.db.User;

public class MainActivity extends ActionBarActivity {

    private DaoSession session;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button buttonUser = (Button) findViewById(R.id.user_button);

        OnClickListener sendUser = new OnClickListener() {

            @Override
            public void onClick(View v) {
                EditText email = (EditText) findViewById(R.id.tag_editText);
                //stworzenie przykladowego usera
                User user = new User();
                //przypisanie mu mail
                user.setEmail(email.getText().toString());


                //dodanie do bazy
                session.getUserDao().insert(user);



                List<User> users = new ArrayList<User>();
                users = session.getUserDao().queryBuilder().list();
                for (User e: users){
                    Log.i("asdasd", e.getId() + e.getEmail());
                }


            }
        };

        buttonUser.setOnClickListener(sendUser);


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

2 个答案:

答案 0 :(得分:5)

正如Manu所说,您的DaoSession session未初始化。

您可以使用以下代码获取会话:

SQLiteOpenHelper helper = new DaoMaster.DevOpenHelper(MainActivity.this, "MY_DB_NAME", null);
DaoMaster master = new DaoMaster(helper.getWritableDatabase());
session = master.newSession();

请记住,DevOpenHelper类仅用于测试目的。对于最终的应用程序,您应该扩展OpenHelper并在那里处理DB-schema-updates。即:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.i(TAG, "Update DB-Schema: "+Integer.toString(oldVersion)+"->"+Integer.toString(newVersion));
    switch (oldVersion) {
        case 1:
            db.execSQL("CREATE INDEX IF NOT EXISTS SOME_INDEX ON SOME_TABLE (SOME_COLUMN);");
            // no break as we want to upgrade to the newest version.
        case 2:
            MyNewEntityDao.createTable(db, false);
            // no break as we want to upgrade to the newest version.
        default:
            // Do some things you want to do on every update, i.e. send a message to a server.
            break;
    }
}

有关如何在具有多项活动的应用中使用greendao的详细信息,请参阅this post

答案 1 :(得分:3)

非常简单的问题。您的

private DaoSession session;

未初始化,您需要执行类似

的操作
private DaoMaster daoMaster = new DaoMaster(db);
private DaoSession session = daoMaster.newSession();