0

I have implemented a Database in android and when I try to insert a user into the database I get presented with a Null Poiner Exception. I have debugged the user input of there details and there is information there.

Here is my DbManager.java class

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

}

The logcat is identifying line 59 return db.insert(USER_TABLE, null, initialValues); in the db manager class

and line 66 in Enter_User_Details.java class which is long id = db.createUser(vEmail, Float.parseFloat(vWeight), Float.parseFloat(vHeight));

Here is the full Enter_User_Details class

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();

}

}

And here is the Logcat output include the System.out.println to show that the user entered fileds actually have data in them

02-12 14:36:29.802: I/System.out(1693): Email: [email protected] 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 Answer 1

1

I think DbHelper dbHelper is null because you never call DbManager.open()!

Try adding db.open() before db.createUser(..) in Enter_User_Details.

Sign up to request clarification or add additional context in comments.

2 Comments

Fixes that problem but now have foregin key error from creating my other table.
Foregin key problem was coding slip, forgot to include a comma

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.