插入数据库Android时出现空指针异常

时间:2012-02-12 14:50:16

标签: android database

我在android中实现了一个数据库,当我尝试将用户插入数据库时​​,我会看到一个Null Poiner异常。我调试了用户输入的详细信息,那里有信息。

这是我的DbManager.java类

package com.fyp.run_race;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DbManager 
{

public static final String KEY_USER_ID = "_id";
public static final String KEY_USER_EMAIL = "email";
public static final String KEY_USER_WEIGHT = "weight";
public static final String KEY_USER_HEIGHT = "height";

public static final String KEY_TRACK_ID = "_id";
public static final String KEY_TRACK_FILEPATH = "file_path";
public static final String KEY_TRACK_NAME = "track_name";
public static final String KEY_TRACK_LOCATION = "location";
public static final String KEY_TRACK_TYPE = "track_type";
public static final String KEY_TRACK_CALORIES = "calories";
public static final String KEY_TRACK_DISTANCE = "distance";
public static final String KEY_TRACK_MAX_SPEED = "max_speed";
public static final String KEY_TRACK_AVG_SPEED = "avg_speed";

static final String USER_TABLE = "USERINFO";
static final String TRACK_TABLE = "TRACK";

private Context context;

private DbHelper dbHelper;
private SQLiteDatabase db;

public DbManager(Context cnxt)
{
    this.context = cnxt;
}

public DbManager open() throws SQLException
{
    dbHelper = new DbHelper(context);
    db = dbHelper.getReadableDatabase();

    return this;
}

public void close()
{
    dbHelper.close();
}

public long createUser(String email, float weight, float height)
{
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_USER_EMAIL, email);
    initialValues.put(KEY_USER_WEIGHT, weight);
    initialValues.put(KEY_USER_HEIGHT, height);
    return db.insert(USER_TABLE, null, initialValues);
}

public long createTrack(String filePath,String trackName, String location, String trackType, float calories, float distance, float avgSpeed, float maxSpeed)
{
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_TRACK_FILEPATH, filePath);
    initialValues.put(KEY_TRACK_NAME, trackName);
    initialValues.put(KEY_TRACK_LOCATION, location);
    initialValues.put(KEY_TRACK_TYPE, trackType);
    initialValues.put(KEY_TRACK_CALORIES, calories);
    initialValues.put(KEY_TRACK_DISTANCE, distance);
    initialValues.put(KEY_TRACK_AVG_SPEED, avgSpeed);
    initialValues.put(KEY_TRACK_MAX_SPEED, maxSpeed);
    return db.insert(TRACK_TABLE, null, initialValues);
}

public boolean deleteUser(long rowId)
{
    return db.delete(USER_TABLE, KEY_USER_ID+"="+rowId, null) > 0 ;
}

public boolean deleteTrack(long rowId)
{
    return db.delete(TRACK_TABLE, KEY_TRACK_ID+"="+rowId, null) > 0 ;
}

public Cursor getAllUsers()
{
    return db.query(true, USER_TABLE, new String[]{KEY_USER_ID,KEY_USER_EMAIL,KEY_USER_WEIGHT,KEY_USER_HEIGHT }, null, null, null, null, null, null);
}

public Cursor getAllTracks()
{
    return db.query(true, TRACK_TABLE, new String[]{KEY_TRACK_ID,KEY_TRACK_FILEPATH,KEY_TRACK_NAME,KEY_TRACK_LOCATION,KEY_TRACK_TYPE, KEY_TRACK_CALORIES, KEY_TRACK_DISTANCE, KEY_TRACK_AVG_SPEED,KEY_TRACK_MAX_SPEED}, null, null, null, null, null, null);
}

public Cursor getUser(long rowId)
{
    Cursor myCursor = db.query(true, USER_TABLE, new String[]{KEY_USER_ID,KEY_USER_EMAIL,KEY_USER_WEIGHT,KEY_USER_HEIGHT }, KEY_USER_ID + "="+ rowId, null, null, null, null, null);

    if(myCursor != null)
    {
        myCursor.moveToFirst();
    }

    return myCursor;
}

public Cursor getTrack(long rowId)
{
    Cursor myCursor = db.query(true, TRACK_TABLE, new String[]{KEY_TRACK_ID,KEY_TRACK_FILEPATH,KEY_TRACK_NAME,KEY_TRACK_LOCATION,KEY_TRACK_TYPE, KEY_TRACK_CALORIES, KEY_TRACK_DISTANCE, KEY_TRACK_AVG_SPEED,KEY_TRACK_MAX_SPEED}, KEY_TRACK_ID+ "=" + rowId, null, 
            null, null, null, null);

    if(myCursor != null)
    {
        myCursor.moveToFirst();
    }

    return myCursor;
}

public boolean updateUser(long rowId,String email, float weight, float height)
{
    ContentValues args = new ContentValues();

    args.put(KEY_USER_EMAIL, email);
    args.put(KEY_USER_WEIGHT, weight);
    args.put(KEY_USER_HEIGHT, height);

    return db.update(USER_TABLE, args, KEY_USER_ID + "=" + rowId, null) > 0;
}

}

logcat正在标识db manager类

中的第59行return db.insert(USER_TABLE, null, initialValues);

和Enter_User_Details.java类中的第66行long id = db.createUser(vEmail, Float.parseFloat(vWeight), Float.parseFloat(vHeight));

这是完整的Enter_User_Details类

package com.fyp.run_race;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.fyp.run_race.DbManager;

public class Enter_User_Details extends Activity
{
private DbManager db;
Long rowId = null;
EditText email,weight,height;
Button confirm,clear;
String vEmail, vWeight,vHeight;
boolean emailCheck;

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.user_details);
    db = new DbManager(this);

    email = (EditText)findViewById(R.id.EmailEntry);
    weight = (EditText)findViewById(R.id.Weight);
    height = (EditText)findViewById(R.id.Height);
    confirm = (Button)findViewById(R.id.ConfirmBtn);
    clear = (Button)findViewById(R.id.ClearBtn);



    confirm.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View arg0) 
        {
            // TODO Auto-generated method stub
            vEmail = email.getText().toString();
            vWeight = weight.getText().toString();
            vHeight = height.getText().toString();

            if(vEmail.equalsIgnoreCase("")||vWeight.equalsIgnoreCase("")||vHeight.equalsIgnoreCase(""))
            {
                Toast.makeText(Enter_User_Details.this, "All fields are required", Toast.LENGTH_LONG).show();
            }

            if(isNumeric(vWeight) == true && isNumeric(vHeight) == true)
            {
                Toast.makeText(Enter_User_Details.this, "Weight or Height must be a number", Toast.LENGTH_LONG).show();
            }

            checkEmail(vEmail);
            if(emailCheck == true)
            {
                System.out.println("Email: "+vEmail+" Weight: "+Float.parseFloat(vWeight)+" Height: "+Float.parseFloat(vHeight));
                long id = db.createUser(vEmail, Float.parseFloat(vWeight), Float.parseFloat(vHeight));
                db.close();
                Intent i = new Intent(Enter_User_Details.this, Begin_Run.class);
                startActivity(i);
            }


        }



    });

}

public static boolean isNumeric(String str)
{
    try
    {
        float f = Float.parseFloat(str);
    }

    catch(NumberFormatException nfe)
    {
        return false;
    }

    return true;
}

private void checkEmail(String vEmail) 
{
    // TODO Auto-generated method stub
    Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+");
    Matcher matcher = pattern.matcher(vEmail);
    emailCheck = matcher.matches();

}

}

这里是Logcat输出包含System.out.println以显示用户输入的文件实际上有数据

02-12 14:36:29.802: I/System.out(1693): Email: sean.w.hannon@gmail.com Weight: 75.5 Height: 160.5
02-12 14:36:29.802: D/AndroidRuntime(1693): Shutting down VM
02-12 14:36:29.802: W/dalvikvm(1693): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
02-12 14:36:29.812: E/AndroidRuntime(1693): FATAL EXCEPTION: main
02-12 14:36:29.812: E/AndroidRuntime(1693): java.lang.NullPointerException
02-12 14:36:29.812: E/AndroidRuntime(1693):     at com.fyp.run_race.DbManager.createUser(DbManager.java:59)
02-12 14:36:29.812: E/AndroidRuntime(1693):     at com.fyp.run_race.Enter_User_Details$1.onClick(Enter_User_Details.java:66)
02-12 14:36:29.812: E/AndroidRuntime(1693):     at android.view.View.performClick(View.java:2408)
02-12 14:36:29.812: E/AndroidRuntime(1693):     at android.view.View$PerformClick.run(View.java:8816)
02-12 14:36:29.812: E/AndroidRuntime(1693):     at android.os.Handler.handleCallback(Handler.java:587)
02-12 14:36:29.812: E/AndroidRuntime(1693):     at android.os.Handler.dispatchMessage(Handler.java:92)
02-12 14:36:29.812: E/AndroidRuntime(1693):     at android.os.Looper.loop(Looper.java:123)
02-12 14:36:29.812: E/AndroidRuntime(1693):     at android.app.ActivityThread.main(ActivityThread.java:4627)
02-12 14:36:29.812: E/AndroidRuntime(1693):     at java.lang.reflect.Method.invokeNative(Native Method)
02-12 14:36:29.812: E/AndroidRuntime(1693):     at java.lang.reflect.Method.invoke(Method.java:521)
02-12 14:36:29.812: E/AndroidRuntime(1693):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
02-12 14:36:29.812: E/AndroidRuntime(1693):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
02-12 14:36:29.812: E/AndroidRuntime(1693):     at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

我认为DbHelper dbHelpernull,因为您从不致电DbManager.open()

尝试在db.open()db.createUser(..)之前添加Enter_User_Details