0

I am getting a null pointer exception when trying to import a few lines from a csv file into an sqlite database. I am getting a npe when I call a method db.addProduct(...)

Heres my code:

  public class ImportDataHandler extends Activity {

    protected File file;
    protected DatabaseHandler db;
    private ArrayList<HashMap<String, Object>> mylist;
    protected ListView listView;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.importer);
      importData();
      listView = (ListView) findViewById(R.id.allProdList);
      mylist = new ArrayList<HashMap<String, Object>>();
      db = new DatabaseHandler(this); 

      if (db.getAllProducts().isEmpty()) {
          Log.i(null, "This is null");
      }
      if (!db.getAllProducts().isEmpty()){
         Log.i(db.getAllProducts().toString(), "Products");
          for (Product p : db.getAllProducts()) {
              HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("Product", p._name);
                map.put("Description", p._description);
                mylist.add(map);
            }
            ListAdapter adapter = new SimpleAdapter(this, mylist,
                    R.layout.list_layout, new String[] { "Product", "Description"},
                    new int[] { R.id.prod_name, R.id.prod_desc});


            listView.setAdapter(adapter);
      }
     }

     public void importData() {

         File exportDir = new File(Environment.getExternalStorageDirectory(), "");

         if (!exportDir.exists()) {
             exportDir.mkdirs();
         }

         file = new File(exportDir, "ProductCSV.csv");

         try {

             CSVReader reader = new CSVReader(new FileReader(file));
             String [] nextLine;

             try {

                 while ((nextLine = reader.readNext()) != null) {

                    String skuCode = nextLine[0];
                    String name = nextLine[1];
                    String description = nextLine[2];
                    String price = nextLine[3];
                    String image = nextLine[4];
                    String category = nextLine[5];

                    if(skuCode.equalsIgnoreCase("Sku Code")) {

                    } else {
                        db.addProduct(new Product(skuCode, name, description, Integer.parseInt(price), image, Integer.parseInt(category))); /** This where the npe is occuring */
                    }

                 }
             } catch (IOException e) {
                 e.printStackTrace();
             }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

     }

}

Database Helper:

public class DatabaseHandler extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "catalogueManager";

    private static final String TABLE_PRODUCTS = "products";

    // Product Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_PRODUCT_SKUCODE = "skuCode";
    private static final String KEY_PRODUCT_NAME = "name";
    private static final String KEY_PRODUCT_DESCRIPTION = "description";
    private static final String KEY_PRODUCT_PRICE = "price";    
    private static final String KEY_PRODUCT_IMAGE = "image";
    private static final String KEY_PRODUCT_CATEGORY = "category";

    // Create table Product
    private static final String CREATE_PRODUCT_TABLE = "CREATE TABLE " + TABLE_PRODUCTS + "("
            + KEY_ID + " INTEGER PRIMARY KEY," 
            + KEY_PRODUCT_SKUCODE + " TEXT,"
            + KEY_PRODUCT_NAME + " TEXT,"
            + KEY_PRODUCT_DESCRIPTION + " TEXT," 
            + KEY_PRODUCT_PRICE + " INTEGER," 
            + KEY_PRODUCT_IMAGE + " TEXT," 
            + KEY_PRODUCT_CATEGORY + " INTEGER" 
            + ")";

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

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_PRODUCT_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_PRODUCTS);

        // Create tables again
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    public void addProduct(Product product) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_PRODUCT_SKUCODE, product.getSkuCode()); 
        values.put(KEY_PRODUCT_NAME, product.getName()); 
        values.put(KEY_PRODUCT_DESCRIPTION, product.getDescription()); 
        values.put(KEY_PRODUCT_PRICE, product.getPrice()); 
        values.put(KEY_PRODUCT_IMAGE, product.getImage()); 
        values.put(KEY_PRODUCT_CATEGORY, product.getCategory()); 

        db.insert(TABLE_PRODUCTS, null, values);
        db.close();
}


}

Any help would greatly be appreciated.

Thanks.

7
  • 2
    post your code relevant to 'db' initialization and the add product, db helper Commented Apr 24, 2014 at 11:54
  • 1
    Based on the posted code, I’d say that db is NULL. Or is that variable assigned somewhere else? If so, please post that code, like @user2450263 suggests. Commented Apr 24, 2014 at 11:58
  • What is a NullReferenceException and how do I fix it? Commented Apr 24, 2014 at 11:59
  • The db is assigned in the onCreate method: db = new DatabaseHandler(this); Commented Apr 24, 2014 at 12:00
  • post logcat dear for idetify issue Commented Apr 24, 2014 at 12:00

1 Answer 1

1

In your code, it seems you call "importData" before initializing "db", the reason why it's null.

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

2 Comments

Oh wow thanks! I have no Idea how I missed that! Thank you so much!
You're welcome, sometime we are just too much in our code to spot basic idiotic mistakes ;)

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.