简体   繁体   中英

Why am I getting null when trying to retrieve a value from a ContentValues object?

I am getting a NullPointerException when trying to retrieve/insert values from a ContentValues object that I'm a passing to my database method. I have several columns in my db table and instead of passing all those as params to the method, I'm trying to simplify it a little bit.

Here's a sample of the code:

public class MyActivity extends Activity {
 private Calendar calendar = Calendar.getInstance();

  // other methods in here....

 public void onClick( View v ) {
    int year = calendar.get( Calendar.YEAR );
    int month = calendar.get( Calendar.MONTH );
    int date = calendar.get( Calendar.DAY_OF_WEEK );
    int weekOfYear = calendar.get( Calendar.WEEK_OF_YEAR );

    ContentValues values = new ContentValues();
    values.put( YEAR, year );
    values.put( MONTH, month );
    values.put( DATE, date );
    values.put( WEEK_OF_YEAR, weekOfYear );

    if( everythingIsGood ) {
      // the problem starts after this.
      mDb.addToDatabase( values );

    }
 }

Here's the database method:

public class Database {
  // other methods....

  public long addToDatabase( ContentValues values ) {
    // I'm getting a NullPointerException right here, trying to retrieve 
    // a value from this ContentValues object 
    int weekOfYear = values.getAsInteger( WEEK_OF_YEAR );
    values.remove( WEEK_OF_YEAR );

    // do other stuff

    long pId = this.getParentId( weekOfYear );

   // And, if I take the above out, right here
   values.put( PARENT_ID, pId );

  mDb.insert( table_name, null, values );
  }
}

So, am I not allowed to manipulate the ContentValues object? Is this bad practice, should I just pass all those variables to the method?

Note: I know for a fact that the values are not null.

Thanks in advance.

Doesn't look like you opened the database mDb, bro. You gotta do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM