質問

i have a problem. I am learning Greendao, but on first step i have error.. When I want use insert I get a nullPointerException. I don't know why.. I have autoincrement on id and I don't need put password. I don't know how to work with it..

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

Very simple problem. Your

private DaoSession session;

is not initialized, you need to do something like

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

他のヒント

As Manu said, your DaoSession sessionis not initialized.

you can obtain a session using the following code:

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

Keep in mind, that the DevOpenHelper-class is only for testing purpose. For your final app you should extend OpenHelper and handle DB-schema-updates in there. I.e:

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

For further information on how to use greendao in Apps with multiple Activities see this post.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top