0

being trying to add another item to a database but I just cant, been like this for weeks..im new here, im learning solo. tutorials in youtube cant respond me so Im desperate, I need help. I just want to learn to master sqlite databases in android mobile.

The only thing I need is to add a new item to the database but Its not working, I haVE NEVer used this sqlite before..seen like 4 tutorials in how to do it. I copied one exactly and didnt worked :(

Heres the log error

03-09 18:26:30.364 8123-8123/com.gohool.mygrocerylist.mygrocerylist E/SQLiteLog: (1) table groceryTBL has no column named quantity_number2
    03-09 18:26:30.366 8123-8123/com.gohool.mygrocerylist.mygrocerylist E/SQLiteDatabase: Error inserting date_added=1520641590363 quantity_number=1 grocery_item=caca quantity_number2=
                                                                                          android.database.sqlite.SQLiteException: table groceryTBL has no column named quantity_number2 (code 1): , while compiling: INSERT INTO groceryTBL(date_added,quantity_number,grocery_item,quantity_number2) VALUES (?,?,?,?)
                                                                                          #################################################################
                                                                                          Error Code : 1 (SQLITE_ERROR)
                                                                                          Caused By : SQL(query) error or missing database.
                                                                                            (table groceryTBL has no column named quantity_number2 (code 1): , while compiling: INSERT INTO groceryTBL(date_added,quantity_number,grocery_item,quantity_number2) VALUES (?,?,?,?))
                                                                                          #################################################################
                                                                                              at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                              at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1008)
                                                                                              at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:573)
                                                                                              at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                              at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
                                                                                              at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                                              at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1781)
                                                                                              at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1653)
                                                                                              at com.gohool.mygrocerylist.mygrocerylist.Data.DatabaseHandler.addGrocery(DatabaseHandler.java:67)
                                                                                              at com.gohool.mygrocerylist.mygrocerylist.Activities.MainActivity.saveGroceryToDB(MainActivity.java:131)
                                                                                              at com.gohool.mygrocerylist.mygrocerylist.Activities.MainActivity.access$300(MainActivity.java:22)
                                                                                              at com.gohool.mygrocerylist.mygrocerylist.Activities.MainActivity$2.onClick(MainActivity.java:107)
                                                                                              at android.view.View.performClick(View.java:6213)
                                                                                              at android.widget.TextView.performClick(TextView.java:11074)
                                                                                              at android.view.View$PerformClick.run(View.java:23645)
                                                                                              at android.os.Handler.handleCallback(Handler.java:751)
                                                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                              at android.os.Looper.loop(Looper.java:154)
                                                                                              at android.app.ActivityThread.main(ActivityThread.java:6692)
                                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

Heres datab java

package com.gohool.mygrocerylist.mygrocerylist.Data;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.SyncStateContract;
import android.util.Log;

import com.gohool.mygrocerylist.mygrocerylist.Model.Grocery;
import com.gohool.mygrocerylist.mygrocerylist.Util.Constants;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by paulodichone on 4/7/17.
 */

public class DatabaseHandler extends SQLiteOpenHelper {

    private Context ctx;
    public DatabaseHandler(Context context) {
        super(context, Constants.DB_NAME, null, Constants.DB_VERSION);
        this.ctx = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_GROCERY_TABLE = "CREATE TABLE " + Constants.TABLE_NAME + "("
                + Constants.KEY_ID + " INTEGER PRIMARY KEY," + Constants.KEY_GROCERY_ITEM + " TEXT,"
                + Constants.KEY_QTY_NUMBER + " TEXT,"
                + Constants.KEY_QTY_NUMBER2 + " TEXT,"
                + Constants.KEY_DATE_NAME + " LONG);";

        db.execSQL(CREATE_GROCERY_TABLE);


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS " + Constants.TABLE_NAME);

        onCreate(db);

    }

    /**
     *  CRUD OPERATIONS: Create, Read, Update, Delete Methods
     */

    //Add Grocery
    public void addGrocery(Grocery grocery) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(Constants.KEY_GROCERY_ITEM, grocery.getName());
        values.put(Constants.KEY_QTY_NUMBER, grocery.getQuantity());
        values.put(Constants.KEY_QTY_NUMBER2, grocery.getQuantity2());
        values.put(Constants.KEY_DATE_NAME, java.lang.System.currentTimeMillis());

        //Insert the row
        db.insert(Constants.TABLE_NAME, null, values);

        Log.d("Saved!!", "Saved to DB");

    }


    //Get a Grocery
    public Grocery getGrocery(int id) {
        SQLiteDatabase db = this.getWritableDatabase();

        Cursor cursor = db.query(Constants.TABLE_NAME, new String[] {Constants.KEY_ID,
             Constants.KEY_GROCERY_ITEM, Constants.KEY_QTY_NUMBER, Constants.KEY_QTY_NUMBER2, Constants.KEY_DATE_NAME},
                Constants.KEY_ID + "=?",
                new String[] {String.valueOf(id)}, null, null, null, null);

        if (cursor != null)
            cursor.moveToFirst();


            Grocery grocery = new Grocery();
            grocery.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Constants.KEY_ID))));
            grocery.setName(cursor.getString(cursor.getColumnIndex(Constants.KEY_GROCERY_ITEM)));
            grocery.setQuantity(cursor.getString(cursor.getColumnIndex(Constants.KEY_QTY_NUMBER)));
        grocery.setQuantity2(cursor.getString(cursor.getColumnIndex(Constants.KEY_QTY_NUMBER2)));

            //convert timestamp to something readable
            java.text.DateFormat dateFormat = java.text.DateFormat.getDateInstance();
            String formatedDate = dateFormat.format(new Date(cursor.getLong(cursor.getColumnIndex(Constants.KEY_DATE_NAME)))
            .getTime());

            grocery.setDateItemAdded(formatedDate);



        return grocery;
    }


    //Get all Groceries
    public List<Grocery> getAllGroceries() {
        SQLiteDatabase db = this.getReadableDatabase();

        List<Grocery> groceryList = new ArrayList<>();

        Cursor cursor = db.query(Constants.TABLE_NAME, new String[] {
                Constants.KEY_ID, Constants.KEY_GROCERY_ITEM, Constants.KEY_QTY_NUMBER, Constants.KEY_QTY_NUMBER2,
                Constants.KEY_DATE_NAME}, null, null, null, null, Constants.KEY_DATE_NAME + " DESC");

        if (cursor.moveToFirst()) {
            do {
                Grocery grocery = new Grocery();
                grocery.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Constants.KEY_ID))));
                grocery.setName(cursor.getString(cursor.getColumnIndex(Constants.KEY_GROCERY_ITEM)));
                grocery.setQuantity(cursor.getString(cursor.getColumnIndex(Constants.KEY_QTY_NUMBER)));
                grocery.setQuantity2(cursor.getString(cursor.getColumnIndex(Constants.KEY_QTY_NUMBER2)));
                //convert timestamp to something readable
                java.text.DateFormat dateFormat = java.text.DateFormat.getDateInstance();
                String formatedDate = dateFormat.format(new Date(cursor.getLong(cursor.getColumnIndex(Constants.KEY_DATE_NAME)))
                        .getTime());

                grocery.setDateItemAdded(formatedDate);

                // Add to the groceryList
                groceryList.add(grocery);

            }while (cursor.moveToNext());
        }

        return groceryList;
    }


    //Updated Grocery
    public int updateGrocery(Grocery grocery) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(Constants.KEY_GROCERY_ITEM, grocery.getName());
        values.put(Constants.KEY_QTY_NUMBER, grocery.getQuantity());
        values.put(Constants.KEY_QTY_NUMBER2, grocery.getQuantity2());
        values.put(Constants.KEY_DATE_NAME, java.lang.System.currentTimeMillis());//get system time


        //update row
        return db.update(Constants.TABLE_NAME, values, Constants.KEY_ID + "=?", new String[] { String.valueOf(grocery.getId())} );
    }


    //Delete Grocery
    public void deleteGrocery(int id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(Constants.TABLE_NAME, Constants.KEY_ID + " = ?",
                new String[] {String.valueOf(id)});

        db.close();

    }


    //Get count
    public int getGroceriesCount() {
        String countQuery = "SELECT * FROM " + Constants.TABLE_NAME;
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.rawQuery(countQuery, null);

        return cursor.getCount();
    }
}

MAIN CLASS

package com.gohool.mygrocerylist.mygrocerylist.Activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;

import com.gohool.mygrocerylist.mygrocerylist.Data.DatabaseHandler;
import com.gohool.mygrocerylist.mygrocerylist.Model.Grocery;
import com.gohool.mygrocerylist.mygrocerylist.R;

public class MainActivity extends AppCompatActivity {

    private AlertDialog.Builder dialogBuilder;
    private AlertDialog dialog;
    private EditText groceryItem;
    private EditText quantity;
    private EditText quantity2;


    private Button saveButton;
    private DatabaseHandler db;


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


        db = new DatabaseHandler(this);

        byPassActivity();

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();

                createPopupDialog();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    private void createPopupDialog() {

        dialogBuilder = new AlertDialog.Builder(this);
        View view = getLayoutInflater().inflate(R.layout.popup, null);
        groceryItem = (EditText) view.findViewById(R.id.groceryItem);
       quantity = (EditText) view.findViewById(R.id.groceryQty);
        quantity2 = (EditText) view.findViewById(R.id.groceryQty2);


        saveButton = (Button) view.findViewById(R.id.saveButton);

        dialogBuilder.setView(view);
        dialog = dialogBuilder.create();
        dialog.show();

        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Todo: Save to db
                //Todo: Go to next screen

                if (!groceryItem.getText().toString().isEmpty()
                        && !quantity.getText().toString().isEmpty()) {
                    saveGroceryToDB(v);
                }

            }
        });


    }

    private void saveGroceryToDB(View v) {

        Grocery grocery = new Grocery();

        String newGrocery = groceryItem.getText().toString();
        String newGroceryQuantity = quantity.getText().toString();
        String newGroceryQuantity2 = quantity2.getText().toString();



        grocery.setName(newGrocery);
        grocery.setQuantity(newGroceryQuantity);
        grocery.setQuantity2(newGroceryQuantity2);

        //Save to DB
        db.addGrocery(grocery);

        Snackbar.make(v, "Item Saved!", Snackbar.LENGTH_LONG).show();

       // Log.d("Item Added ID:", String.valueOf(db.getGroceriesCount()));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
                //start a new activity
                startActivity(new Intent(MainActivity.this, ListActivity.class));
            }
        }, 1200); //  1 second.

    }


    public void byPassActivity() {
        //Checks if database is empty; if not, then we just
        //go to ListActivity and show all added items

        if (db.getGroceriesCount() > 0) {
            startActivity(new Intent(MainActivity.this, ListActivity.class));
            finish();
        }

    }
}

I just want to add quantity_number2 new item to app but it doenst work, it always crashes. If you can help me with entire project I can send it to you I just need an email thx!

Memo333
  • 101
  • 3
  • If you change your database code after having run your app once, you need to clear the existing database first, to allow it to be recreated with the new structure. Either select "Clear data" on your app's page in the device Settings, or uninstall/reinstall your app. – Mike M. Mar 10 '18 at 00:54
  • why? because the database needs to reload? mike? I need to recreat the apk? or..? mmm , you how to upload all the project in github? – Memo333 Mar 10 '18 at 05:10
  • "because the database needs to reload?" - It needs to be recreated with your new column. "I need to recreat the apk?" - When you recompile your project after adding the column, you will already have a new apk. – Mike M. Mar 10 '18 at 15:16
  • thx mike for helping me...im new to this..can u plz see all my project? – Memo333 Mar 10 '18 at 19:03
  • Sorry, but Stack Overflow is only for specific questions. If you need overall help with an entire project, you may have to hire someone. – Mike M. Mar 11 '18 at 02:51

0 Answers0