【问题标题】:java.lang.NumberFormatException: Invalid int: "null"java.lang.NumberFormatException:无效的int:“null”
【发布时间】:2014-07-23 12:41:19
【问题描述】:

getAllActivities() 方法必须以数组列表格式返回数据库中的所有活动 但我得到: java.lang.NumberFormatException: Invalid int: "null", 在activity.setActivityType(Integer.parseInt(cursor.getString(1))); 不知道怎么回事

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import com.yast.util.Constants;
import com.yast.util.Utils;
import java.util.ArrayList;
import java.util.List;


public class DatabaseHandler extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "YastDB.db";

    // Activities table name
    private static final String TABLE_ACTIVITIES = "Activities";

    // Activities Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_ACTIVITYTYPE = "ActivityType";
    private static final String KEY_HARTRATE = "HartRate";
    private static final String KEY_HARTBATNO = "HartBatNo";
    private static final String KEY_DISTANCE = "Distance";
    private static final String KEY_SPEED = "Speed";
    private static final String KEY_STRIDES = "Strides";
    private static final String KEY_STARTDATETIME = "StartDateTime";
    private static final String KEY_ENDDATETIME = "EndDateTime";
    public static final String  KEY_CURRENTDATETIME = "CurrentDateTime";

    private String[] PROJECTION = new String[]{ KEY_ID,
            KEY_ACTIVITYTYPE, KEY_HARTRATE,KEY_HARTBATNO, KEY_DISTANCE,
            KEY_SPEED,KEY_STRIDES,KEY_STARTDATETIME,KEY_ENDDATETIME
            ,KEY_CURRENTDATETIME};

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_Activitys_TABLE = "CREATE TABLE " + TABLE_ACTIVITIES + "("
                + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                KEY_ACTIVITYTYPE + " INTEGER,"+
                KEY_HARTRATE + " INTEGER, "+
                KEY_HARTBATNO + " INTEGER,"+
                KEY_DISTANCE + " INTEGER," +
                KEY_SPEED + " INTEGER," +
                KEY_STRIDES + " INTEGER," +
                KEY_STARTDATETIME + " TEXT," +
                KEY_ENDDATETIME + " TEXT," +
                KEY_CURRENTDATETIME + " TEXT" +
                ")";
        db.execSQL(CREATE_Activitys_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_ACTIVITIES);

        // Create tables again
        onCreate(db);
    }

    //CRUD operations (Create, Read, Update and Delete)
    // Adding new activity
    public void addActivity(ActivityEntity activity) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ACTIVITYTYPE, activity.getActivityType()); // Activity type
        values.put(KEY_HARTRATE, activity.getHartRate());
        values.put(KEY_HARTBATNO, activity.getHartBatNo());
        values.put(KEY_DISTANCE, activity.getDistance());
        values.put(KEY_SPEED, activity.getSpeed());
        values.put(KEY_STRIDES, activity.getStrides());
        values.put(KEY_STARTDATETIME,activity.getStartDateTime().toString());
        values.put(KEY_ENDDATETIME, activity.getEndDateTime().toString());
        values.put(KEY_CURRENTDATETIME, activity.getCurrentDateTime().toString());

        // Inserting Row
        db.insert(TABLE_ACTIVITIES, null, values);
        db.close(); // Closing database connection

    }

    // Getting single Activity
    /*
    The following method getActivity() will read single contact row.
    It accepts id as parameter and will return the matched row from the database.
     */
    public ActivityEntity getActivity(int id) {
        ActivityEntity activity = null;
        SQLiteDatabase db = this.getReadableDatabase();

        String where = KEY_ID + "=?";
        String[] selectionArg = new String[]{String.valueOf(id)};

        Cursor cursor = db.query(TABLE_ACTIVITIES, PROJECTION, where, selectionArg,
 null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();

            activity = new ActivityEntity(Integer.parseInt(cursor.getString(0)),
                    Integer.parseInt(cursor.getString(1)),
                    Integer.parseInt(cursor.getString(2)),
                    Integer.parseInt(cursor.getString(3)),
                    Integer.parseInt(cursor.getString(4)),
                    Integer.parseInt(cursor.getString(5)),
                    Integer.parseInt(cursor.getString(6)),
                    cursor.getString(7),
                    cursor.getString(8),
                    cursor.getString(9));
        }
        return activity;
    }

    // Getting All Activities
    public ArrayList<ActivityEntity> getAllActivitys() {

        ArrayList<ActivityEntity> activitiesList = new ArrayList<ActivityEntity>();
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.query(TABLE_ACTIVITIES, PROJECTION, null, null, null, null, null, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                ActivityEntity activity = new ActivityEntity();
                activity.setID(Integer.parseInt(cursor.getString(0)));
                activity.setActivityType(Integer.parseInt(cursor.getString(1)));
                activity.setHartRate(Integer.parseInt(cursor.getString(2)));
                activity.setHartBatNo(Integer.parseInt(cursor.getString(3)));
                activity.setDistance(Integer.parseInt(cursor.getString(4)));
                activity.setSpeed(Integer.parseInt(cursor.getString(5)));
                activity.setStrides(Integer.parseInt(cursor.getString(6)));
                activity.setStartDateTime(cursor.getString(7));
                activity.setEndDateTime(cursor.getString(8));
                activity.set_currentDateTime(cursor.getString(9));

                // Adding activity to list
                activitiesList.add(activity);
            } while (cursor.moveToNext());

        }
        return activitiesList;
    }


    public int getActivitiesCount() {

        String countQuery = "SELECT  * FROM " + TABLE_ACTIVITIES;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }

    // Updating single Activity
    public int updateActivity(ActivityEntity activity) {
            SQLiteDatabase db = this.getWritableDatabase();

            String where = KEY_ID + "=?";

            ContentValues values = new ContentValues();
            values.put(PROJECTION[1], activity.getActivityType());
            values.put(PROJECTION[2], activity.getHartRate());
            values.put(PROJECTION[3], activity.getHartBatNo());
            values.put(PROJECTION[4], activity.getDistance());
            values.put(PROJECTION[5], activity.getSpeed());
            values.put(PROJECTION[6], activity.getStrides());
            values.put(PROJECTION[7], activity.getStartDateTime().toString());
            values.put(PROJECTION[8], activity.getEndDateTime().toString());
            values.put(PROJECTION[9], activity.getCurrentDateTime().toString());


            // updating row
            return db.update(TABLE_ACTIVITIES, values, where, new String[] { String.valueOf(activity.getID()) });
    }

    public void deleteActivity(ActivityEntity activity)
    {
        String where = KEY_ID + "=?";

        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_ACTIVITIES, where,
                new String[] { String.valueOf(activity.getID()) });
        db.close();
    }

    public void bulkInsert(ArrayList<ActivityEntity> arrayOfActivities) {
        SQLiteDatabase db = this.getWritableDatabase();
        String sql = "INSERT INTO "+ TABLE_ACTIVITIES +" VALUES (?,?,?,?,?,?,?,?,?,?);";
        SQLiteStatement statement = db.compileStatement(sql);
        db.beginTransaction();
       for (ActivityEntity a : arrayOfActivities ) {
            statement.clearBindings();
            statement.bindLong(1, (long) a.getID());
            statement.bindLong(2, (long) a.getActivityType());
            statement.bindLong(3, (long) a.getHartRate());
            statement.bindLong(4, (long) a.getHartBatNo());
            statement.bindLong(5, (long) a.getDistance());
            statement.bindLong(6, (long) a.getSpeed());
            statement.bindLong(7, (long) a.getStrides());
            statement.bindString(8, a.getStartDateTime());
            statement.bindString(9, a.getEndDateTime());
            statement.bindString(10,a.getCurrentDateTime());

            statement.clearBindings();
            statement.execute();
        }
        db.setTransactionSuccessful();
        db.endTransaction();
    }


}

ActivityEntity.java 类:

import com.yast.util.Constants;
import com.yast.util.Utils;
import java.util.Date;

public class ActivityEntity {

    int id;
    int activityType;
    int hartRate;
    int hartBatNo;
    int distance;
    int speed;
    int strides;
    String startDateTime;
    String endDateTime;
    String currentDateTime;

    public ActivityEntity(){

    }
    // constructor
    public ActivityEntity(int Id, int activityType, int hartRate, int _hartBatNo, int distance, int speed, int strides, String startDateTime, String endDateTime, String currentDateTime){
        this.id = Id;
        this.activityType = activityType;
        this.hartRate = hartRate;
        this.hartBatNo = _hartBatNo;
        this.distance = distance;
        this.speed = speed;
        this.strides = strides;
        this.startDateTime = startDateTime;
        this.endDateTime = endDateTime;
        this.currentDateTime = currentDateTime;
    }
    public void setID(int id){
        this.id = id;
    }
    public int getID(){
        return this.id;
    }
    public void setActivityType(int activityType){
        this.activityType = activityType;
    }
    public int getActivityType(){
        return this.activityType;
    }
    public void setHartRate(int hartRate){
        this.hartRate = hartRate;
    }

    public int getHartRate(){
        return this.hartRate;
    }
    public void setHartBatNo(int hartBatNo){
        this.hartBatNo = hartBatNo;
    }
    public int getHartBatNo(){
        return this.hartBatNo;
    }

    public void setDistance(int distance){
        this.distance = distance;
    }

    public int getDistance(){
        return this.distance;
    }

    public void setSpeed(int speed){
        this.speed = speed;
    }

    public int getSpeed(){
        return this.speed;
    }

    public void setStrides(int strides){
        this.strides = strides;
    }

    public int getStrides(){
        return this.strides;
    }

    public void setStartDateTime(String startDateTime){
        this.startDateTime = startDateTime;
    }

    public String getStartDateTime(){
        return this.startDateTime;
    }

    public void setEndDateTime(String endDateTime){
        this.endDateTime = endDateTime;
    }

    public String getEndDateTime(){
        return this.endDateTime;
    }

    public void set_currentDateTime(String currentDateTime){
        this.currentDateTime = currentDateTime;
    }
    public String getCurrentDateTime(){
        return this.currentDateTime;
    }

    @Override
    public String toString() {
        return "ActivityEntity{" +
                "id=" + id +
                ", activityType=" + activityType +
                ", hartRate=" + hartRate +
                ", hartBatNo=" + hartBatNo +
                ", distance=" + distance +
                ", speed=" + speed +
                ", strides=" + strides +
                ", startDateTime='" + startDateTime + '\'' +
                ", endDateTime='" + endDateTime + '\'' +
                ", currentDateTime='" + currentDateTime + '\'' +
                '}';
    }
}

【问题讨论】:

    标签: java android sqlite


    【解决方案1】:

    在你的代码中,如果cursor.getString(int num) 返回null,那么Integer.parseInt(String str) 将抛出NumberFormatException

    为避免这种情况,您应该检查cursor.getString(int num) 返回的内容。

    或者,您可以使用try-catch 并在catch 中打印相应的消息,如果您会收到NumberFormatException

    【讨论】:

      【解决方案2】:

      您应该检查您的cursor 值是否为null

      if(cursor.isNull(column))
      {
      //Value is null
      }else{
      
      return cursor.getString(column);
      
      }
      

      【讨论】:

      • 这样你支付两倍的价格:)
      【解决方案3】:

      在将值转换为整数之前,您必须检查该值是否为整数。如果不是整数,则将其替换为默认整数。

      activity.setActivityType(Integer.parseInt(nulltoIntegerDefalt(cursor.getString(1))));
      activity.setActivityType(Integer.parseInt(nulltoIntegerDefalt(cursor.getString(1))));
      activity.setHartRate(Integer.parseInt(nulltoIntegerDefalt(cursor.getString(2))));
      activity.setHartBatNo(Integer.parseInt(nulltoIntegerDefalt(cursor.getString(3))));
      activity.setDistance(Integer.parseInt(nulltoIntegerDefalt(cursor.getString(4))));
      activity.setSpeed(Integer.parseInt(nulltoIntegerDefalt(cursor.getString(5))));
      activity.setStrides(Integer.parseInt(nulltoIntegerDefalt(cursor.getString(6))));
      
       String nulltoIntegerDefalt(String value){
          if(!isIntValue(value)) value="0";
          return value;
      
      }
      
      boolean isIntValue(String val)
      {
          try {
              val=val.replace(" ","");
              Integer.parseInt(val);
          } catch (Exception e) {return false;}
          return true;
      }
      

      【讨论】:

        【解决方案4】:

        "null" 不是有效的 int。首先检查 null。

        【讨论】:

        • 是的,我知道。但我现在不知道为什么/或从哪里取“空”值。理论上应该取一个 Int 值,这是我尝试做的
        • 该行在数据库中的列为空。而且您正在尝试将其作为字符串而不是 int 检索。
        【解决方案5】:

        您需要更加仔细地检查是否为空:

        1) cursor 本身可以是 null

        2) cursor.getString(1) 可以是 null

        把这些放在一起:

        if (cursor != null && cursor.getString(1) != null){
            /*your parse will be safe here*/
        }
        

        请注意,我正在利用 if 将从左到右评估并在知道结果后停止评估这一事实。

        作为优化,您可能希望存储cursor.getString(1) 的结果,以防止您不得不对其进行两次评估。但首先要让代码正常工作。

        【讨论】:

        • 1) 不,因为你会在 cursor.getString(1) 上获得 NPE。
        • @DaveNewton Java 的 &amp;&amp; short circuits,所以这不会发生。无论如何,SQLiteDatabase.query 永远不会返回 null
        • @CL。在 OP 的问题中,cursor 不为空,这就是我的回应。 Bathsheba 的回答旨在通用,我是说原始问题并非如此。我知道 Java 的表达式执行细节,但谢谢。
        【解决方案6】:

        Cursor cursor = db.query(TABLE_ACTIVITIES, PROJECTION, null, null, null, null, null, null);

        您的 SQL 查询字符串,即查询方法中的第一个空输入,为空。您尚未提供查询。我假设您想要表中的所有列,所以也许填写如下查询:

        String SQLSTATEMENT = "SELECT " + KEY_ID + "," + KEY_ACTIVITYTYPE + "," KEY_HARTRATE + "," KEY_HARTBATNO + "," KEY_DISTANCE + "," KEY_SPEED,KEY_STRIDES + "," KEY_STARTDATETIME + "," KEY_ENDDATETIM + "," KEY_CURRENTDATETIME;

        Cursor cursor = db.query(TABLE_ACTIVITIES, PROJECTION, SQLSTATEMENT, null, null, null, null, null);

        【讨论】:

          【解决方案7】:
          activity.setActivityType(Integer.parseInt(cursor.getString(1)));
          

          在这个cursor.getString(1) 中得到空值,这就是你得到 null 指针异常的原因。检查该字符串值。

          【讨论】:

          • 没有得到 NPE,但得到了 NumberFormatException
          【解决方案8】:

          问题应该已经解决了,所以我只是解决异常

          更简单的方法是更改​​if(){}else{}" by "try{}catch(Exception e){}

          例子:

          try { 
          //Avoid/Éviter (FATAL EXCEPTION: main java.lang.NumberFormatException: Invalid int: "")
          
          //exemple / Exemple d'action
          
              int userWeight = Integer.parseInteger(userData);
              Intent intent = new Intent(MainActivity.this, SecondActivity.class);
              intent.putExtra("weight", userWeight);  
          
          //                control Toast/Toast de contrôle
              Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_LONG).show();
          
          }
          catch (Exception e) {
              Toast.makeText(MainActivity.this, "not OK", Toast.LENGTH_LONG).show();
          }
          

          【讨论】:

            【解决方案9】:

            感谢@user3091530 的回答。我使用了自己的 ParsInt 方法。 创建一个名为 Math 的类。

            public class Math {
            
                //Checking the value if null return zero
                public int ParsIntOrDefalt(String value){
                    return Integer.parseInt(NullIntegerDefalt(value));
                }
            
                private String NullIntegerDefalt(String value) {
                    if (!isIntValue(value)) value = "0";
                    return value;
                }
            
                private boolean isIntValue(String val){
                    try {
                        val=val.replace(" ","");
                        Integer.parseInt(val);
                    } catch (Exception e) {return false;}
                    return true;
                }
            }
            

            所以,我们可以使用它来代替主要的 Integer.parseInt() 方法:

            Math math = new Math();
            activity.setActivityType(math.ParsIntOrDefalt(cursor.getString(1)));
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2016-04-29
              • 1970-01-01
              • 1970-01-01
              • 2016-02-05
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多