2

I know what an java.lang.IllegalArgumentException: the bind value at index 1 is null means and what causes the error. I my case I am still unable to find the reason for such an error in my case.

So, what do I intend to achieve?

I have 4 columns in my SQLite database table. I want to find the sum of each column and again find the sum of these four results. The row values for sum is filtered based on the product name chosen by the user from the autoCompleteTextView.

Where am I getting the error?

my stackTrace says I am getting the error in the line beginning with Cursor c = db.query... in the below code. The following code is part of my db file of my android project.

    public int addPurchaseQuantity(String itemName) {
    SQLiteDatabase db = helper.getReadableDatabase();
    int result = 0;
    String selection = VivzHelper.COLUMN_ADD_PURCHASE_ITEM_NAME + " =? ";
    String[] selectionArgs = {itemName};
    Cursor c = db.query(VivzHelper.ADD_PURCHASE_TABLE,
            new String[]{"sum(" + VivzHelper.COLUMN_ADD_PURCHASE_ITEM_QUANTITY + ")"},
            selection,
            selectionArgs,
            null,
            null,
            null);
    if (c.moveToFirst()) {
        result = c.getInt(0);
    }
    c.close();
    return result;
}

The itemName is obtained from the autoCompleteTextView based on user selection.

        String[] autoCompleteName = vivzHelper.getInventoryNameFilterBySupplierName(vivzHelper.getSupplierID(param1));
    ArrayAdapter<String> NameAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, autoCompleteName);
    addPurchaseItemName.setThreshold(1);// starts working from first char
    addPurchaseItemName.setAdapter(NameAdapter);

    addPurchaseItemName.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            itemName = String.valueOf(arg0.getItemAtPosition(arg2));
        }
    });

My stackTrace is also pointing to the following code of the java activity file.

int purchaseQty = vivzHelper.addPurchaseQuantity(itemName);

Here is my stackTrace

04-21 00:09:58.274  21975-21975/com.example.bharathduraiswamy.comboedittext E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bharathduraiswamy.comboedittext/com.example.bharathduraiswamy.comboedittext.AddPurchase}: java.lang.IllegalArgumentException: the bind value at index 1 is null
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2313)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
        at android.app.ActivityThread.access$600(ActivityThread.java:156)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:153)
        at android.app.ActivityThread.main(ActivityThread.java:5336)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.IllegalArgumentException: the bind value at index 1 is null
        at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:164)
        at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:200)
        at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
        at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
        at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
        at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
        at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200)
        at com.example.bharathduraiswamy.comboedittext.VivzDatabaseAdapter.addPurchaseQuantity(VivzDatabaseAdapter.java:2011)
        at com.example.bharathduraiswamy.comboedittext.AddPurchase.aggregateQty(AddPurchase.java:531)
        at com.example.bharathduraiswamy.comboedittext.AddPurchase.onCreate(AddPurchase.java:133)
        at android.app.Activity.performCreate(Activity.java:5122)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2277)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
        at android.app.ActivityThread.access$600(ActivityThread.java:156)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:153)
        at android.app.ActivityThread.main(ActivityThread.java:5336)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
        at dalvik.system.NativeStart.main(Native Method)

Can someone tell me where actually am I going wrong?

Update 01 : onCreate() from AddPurchase activity added

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_purchase);

    // Set a toolbar to replace the action bar
    Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar_addPurchase);
    setSupportActionBar(myToolbar);
    myToolbar.setNavigationIcon(R.drawable.logo);

    //Disable the Toolbar Title
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    // Adding UP icon for Setting Activity
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    SharedPreferences myPreferences = getSharedPreferences("sharedSupplierData", Context.MODE_PRIVATE);
    param1 = myPreferences.getString("sharedSupplierName", DEFAULT);
    if (param1.equals(DEFAULT)) {
        Message.message(this, "No data was found");
    }

    addPurchaseItemName = (AutoCompleteTextView) findViewById(R.id.addPurchaseProductName);
    addPurchaseItemQty = (EditText) findViewById(R.id.addPurchaseProductQuantity);
    addPurchaseCostPrice = (EditText) findViewById(R.id.addPurchaseCostPrice);
    addPurchaseSalePrice = (EditText) findViewById(R.id.addPurchaseSalePrice);
    myDate = (TextView) findViewById(R.id.addPurchaseDatum);
    purchaseSum = (TextView) findViewById(R.id.addPurchaseSum);
    primarySpinner = (Spinner) findViewById(R.id.toolbar_spinner);
    vivzHelper = new VivzDatabaseAdapter(this);

    showDialogOnButtonClick();
    populateListView();

    String[] autoCompleteName = vivzHelper.getInventoryNameFilterBySupplierName(vivzHelper.getSupplierID(param1));
    ArrayAdapter<String> NameAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, autoCompleteName);
    addPurchaseItemName.setThreshold(1);// starts working from first char
    addPurchaseItemName.setAdapter(NameAdapter);

    addPurchaseItemName.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            itemName = String.valueOf(arg0.getItemAtPosition(arg2));
        }
    });

    Message.message(this, ("Item Name  = " + itemName));

    aggregateQty();

    //Initializing an Adapter
    ArrayAdapter<String> toolbar_adapter = new ArrayAdapter<>(
            this, android.R.layout.simple_spinner_dropdown_item, primarySpinner_array);
    //Providing the Resource xml for Drop down Layout
    toolbar_adapter.setDropDownViewResource(R.layout.custom_simple_spinner_dropdown_item);
    primarySpinner.setAdapter(toolbar_adapter);

    //Setting a default Spinner value before onItemClick
    primarySpinner.setSelection(0);
    //Initializing an OnItemClick Listener for Spinner Item
    primarySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            int position_toolbar = primarySpinner.getSelectedItemPosition();

            //Changing Spinner TextSize and Text Color
            ((TextView) arg0.getChildAt(0)).setTextColor(Color.WHITE);
            ((TextView) arg0.getChildAt(0)).setTextSize(20);
            //Changing Spinner Pointer Color - partially effective
            primarySpinner.getBackground().setColorFilter(getResources().getColor(R.color.White), PorterDuff.Mode.SRC_ATOP);

            //Using Switch to move to other Activities
            Intent intent_spinner;
            switch (arg2) {
                case 1:
                    intent_spinner = new Intent(AddPurchase.this, SupplierDues.class);
                    AddPurchase.this.startActivity(intent_spinner);
                    break;
                case 2:
                    intent_spinner = new Intent(AddPurchase.this, SupplierReturns.class);
                    AddPurchase.this.startActivity(intent_spinner);
                    break;
                case 3:
                    intent_spinner = new Intent(AddPurchase.this, SupplierBalanceSheet.class);
                    AddPurchase.this.startActivity(intent_spinner);
                    break;
                case 4:
                    intent_spinner = new Intent(AddPurchase.this, AddSupplier.class);
                    AddPurchase.this.startActivity(intent_spinner);
                    break;
                default:
                    break;
            }
            //Changing Spinner Pointer Color - partially effective
            primarySpinner.getBackground().setColorFilter(getResources().getColor(R.color.White), PorterDuff.Mode.SRC_ATOP);
            //Setting a default Spinner value after onItemClick
            primarySpinner.setSelection(0);
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });
}

Update 02 : aggregateQty() from when the addPurchaseQuantity() is called

    public void aggregateQty() {

    int purchaseQty = vivzHelper.addPurchaseQuantity(itemName);
    int saleQty = vivzHelper.addSaleQuantity(itemName);
    int supplierRtnQty = vivzHelper.returnedToSupplierQuantity(itemName, rtnPrice);
    int supplierRtnScrapQty = vivzHelper.returnedToSupplierForScrapQuantity(itemName, rtnPrice);
    int customerRtnQty = vivzHelper.returnedByCustomerQuantity(itemName, rtnPrice);

    if (itemName.length() != 0) {
        availableQuantity = String.valueOf(purchaseQty - saleQty - supplierRtnQty - supplierRtnScrapQty + customerRtnQty);
        addPurchaseItemQty.setHint(availableQuantity);

        Message.message(this, ("Item Name  = " + itemName + "\n" +
                "Purchase Quantity = " + purchaseQty + "\n" +
                "Sale Quantity = " + saleQty + "\n" +
                "Supplier Return Quantity = " + supplierRtnQty + "\n" +
                "Customer Return Quantity = " + customerRtnQty));

    } else {
        Message.message(this, "Please Select an Item");
    }
}
user3314337
  • 341
  • 3
  • 13
  • Can you show the code for `onCreate()` of `AddPurchase` class? – TactMayers Apr 21 '15 at 02:59
  • @TactMayers have added the code you asked for – user3314337 Apr 21 '15 at 03:33
  • can you post the method, from where you are calling `addPurchaseQuantity()` method – Bharatesh Apr 21 '15 at 06:43
  • If you are calling `addPurchaseQuantity(itemName)` inside `aggregateQty()` then it will crash because Still the user is not selected item from AutoCompleteTextView means before selection itemName is null. – Bharatesh Apr 21 '15 at 10:55
  • @bharat have added the code you asked for in Update 02 in the above description. `addPurchaseItemName.setOnItemClickListener(new AdapterView.OnItemClickListener()` is used to save the selected product name to `itemName`. But you might be right about the `itemName` being null. Now how am I supposed to assign the selected product name to `itemName` and use the `itemName` as parameter to various methods? – user3314337 Apr 21 '15 at 14:28
  • I told that you are passing itemName=null `int purchaseQty = vivzHelper.addPurchaseQuantity(itemName);` bcz here still user is not selected Item from `AutoCompleteTextView` – Bharatesh Apr 21 '15 at 15:32
  • @bharat I agree about your null value statement. I already have tried using **setOnItemClickListener** as posted in Update 01. Also, tried the suggestion posted by _@dtmilano_. Yet for some reason I am still getting the string value of *itemName* as NULL. I have looked into various sources from the web, but in vain. There seem to be some error which I am unable to identify. If it is not an issue, could you please look into the Update 01 and point out where am I going wrong? I mean why NULL despite using **setOnItemClickListener** or _@dtmilano_ suggestion? – user3314337 Apr 22 '15 at 05:48
  • Ok. Now you just avoid crash by checking `itemName!=null` then execute query. – Bharatesh Apr 22 '15 at 05:57

2 Answers2

1

itemName is null in addPurchaseQuantity() invocation and thus why when SQLite tries to use it to replace the selection argument ('?') you receive this exception.

Try setting itemName to a known value and check the results.

EDIT

You should test every method independently so you can easily discover the errors or bugs. Learn to apply unit testing as described in Testing Fundamentals.

Then, you'll discover that the problem is reduced to get the text value from an AutoCompletTextView which you can find plenty of examples out there (i.e. How to get string text from AutoCompleteTextView?).

Community
  • 1
  • 1
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
  • Yes, I know that the value of `itemName` is null and that's the reason for exception. That is exactly my question. I have been trying to assign the value selected by the user in `autoCompleteTextView` to `itemName` using the following code `itemName = String.valueOf(arg0.getItemAtPosition(arg2));` in _onCreate()_ as mentioned above. But for some reason, the string value selected by the user from the `autoCompleteTextView` is not getting assigned to `itemName`. Where am I going wrong? – user3314337 Apr 21 '15 at 03:57
  • So your question has nothing to do with the Exception, sqlite, etc. but with getting the value of an AutoCompleteTextView. – Diego Torres Milano Apr 21 '15 at 04:02
  • I was unsure if the error was due to failure to fetch the value from autoCompleteTextView or due to any other reasons. My apologies. But are you able to identify the reason for the exception? – user3314337 Apr 21 '15 at 04:17
  • I already have tried using **setOnItemClickListener** as posted in Update 01. Also, tried your (i.e. [How to get string text from AutoCompleteTextView?](http://stackoverflow.com/questions/9854790/how-to-get-string-text-from-autocompletetextview)). Yet for some reason I am still getting the string value of *itemName* as NULL. I have looked into various sources from the web, but in vain. There seem to be some error which I am unable to identify. If it is not an issue, could you please look into the Update 01 and point out where am I going wrong? – user3314337 Apr 22 '15 at 05:43
-1

I would try removing the sum in : new String[]{"sum(" + VivzHelper.COLUMN_ADD_PURCHASE_ITEM_QUANTITY + ")"}, See if bind works.