2

I am not getting the add string returned back. The android app takes input as food item and prints its respective calories. here is the code for creating table:

public class dietclass extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "diet7.db";
    public static final String TABLE_NAME = "Cal_val";
    public static final String COL1 = "ID";
    public static final String COL2 = "ITEM";
    public static final String COL3 = "QUANTITY";
    public static final String COL4 = "CALORIES";
    public dietclass(Context context) {
        super(context,DATABASE_NAME,null,1);
        SQLiteDatabase db = this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
       db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,ITEM TEXT,QUANTITY VARCHAR,CALORIES INTEGER)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
       db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
        onCreate(db);
    }
}

And here is the code for retrieving data from my activity which is taking item and calories as input.

public class foodcal extends AppCompatActivity {
    EditText item;
    EditText quantity;
    TextView calories;
    Button calculate;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_foodcal);
        item = (EditText)findViewById(R.id.etitem);
        quantity = (EditText)findViewById(R.id.etquantity);
        calories = (TextView)findViewById(R.id.calories);
        calculate = (Button)findViewById(R.id.calculate);
        calculate.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                String itemstr = item.getText().toString();
                printDatabase(itemstr);
                //String dbstring = dietclass.databaseToString(itemstr);
                //calories.setText(String.valueOf(dbstring));
            }
    });
    }

    public void printDatabase(String item){
        String dbstring = dietclass.databaseToString(this,item);
        //String label;
        //label = dbstring + "calories";
        calories.setText(String.valueOf(dbstring));
  }

    private static class dietclass extends SQLiteOpenHelper {
        private static String DB_PATH = "/data/data/com.example.janhvik.dietapp/databases/";
        private static String DB_NAME = "diet7.db";
        private static String TABLE_NAME = "Cal_val";
        private static SQLiteDatabase myDataBase;
        private Context myContext;

        public dietclass(Context context) {
            super(context, DB_NAME, null, 1);
            this.myContext = context;
        }
    private static String databaseToString(Context ctx, String item_name) {
            String myDbPath;
            int cal = 0 ;
            String add="";
            myDbPath = DB_PATH+DB_NAME;
            myDataBase = SQLiteDatabase.openOrCreateDatabase(myDbPath, null);
            String query = "SELECT * FROM "+TABLE_NAME+" WHERE ITEM='"+item_name+"'";
            Cursor c = myDataBase.rawQuery(query,null);

            if(c!= null && c.moveToFirst()){
                add = c.getString(c.getColumnIndex("CALORIES"));
                c.close();
            }
            add = add + " calories";
            //Toast.makeText(ctx,add, Toast.LENGTH_LONG).show();
            return add;
            }

I am not getting any error but the code is not taking the value from the select query, can anyone help in this.

Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
Sophia
  • 145
  • 2
  • 12

1 Answers1

0

I think you've got rather mixed up and complicated matters by appearing to use multiple database helpers/methods to open the same database when you only need to use the database helper. I'm unsure what the exact issue was, there was insufficient code to build an exact replica.

Instead a created simplified working code.

Here's a rewrite/simplification based upon your code :-

First ONE databasehelper class namely dietclass :-

public class dietclass extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "diet7.db";
    public static final String TABLE_NAME = "Cal_val";
    public static final String COL1 = "ID";
    public static final String COL2 = "ITEM";
    public static final String COL3 = "QUANTITY";
    public static final String COL4 = "CALORIES";
    //private static String DB_PATH = "/data/data/com.example.janhvik.dietapp/databases/";
    //private static String DB_NAME = "diet7.db";
    SQLiteDatabase myDataBase;


    private Context myContext;

    public dietclass(Context context) {
        super(context,DATABASE_NAME,null,1);
        myDataBase = this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,ITEM TEXT,QUANTITY VARCHAR,CALORIES INTEGER)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
        onCreate(db);
    }

    public long insertCal_ValEntry(String item, String quantity, int calories) {
        ContentValues cv = new ContentValues();
        cv.put(COL2,item);
        cv.put(COL3,quantity);
        cv.put(COL4,calories);
        return myDataBase.insert(TABLE_NAME,null,cv);
    }


    public String databaseToString(String item_name) {

        //String myDbPath;
        int cal = 0 ;
        String add="";
        //myDbPath = DB_PATH+DB_NAME;
        //myDataBase = SQLiteDatabase.openOrCreateDatabase(myDbPath, null);

        String query = "SELECT * FROM "+TABLE_NAME+" WHERE ITEM='"+item_name+"'";
        Cursor c = myDataBase.rawQuery(query,null);

        if(c.moveToFirst()){
            add = c.getString(c.getColumnIndex("CALORIES"));
            c.close();
        }
        add = add + " calories";
        //Toast.makeText(ctx,add, Toast.LENGTH_LONG).show();
        return add;
    }
}

Notes

  • For testing purposes, method insertCal_ValEntry has been added.
  • Done away with any attempt to open Database rather this is done by the helper.
  • The check to see if the cursor is null has been removed, it is basically useless as SQLite will not return a null, it will always return a cursor, which may be empty. the Cursor move??? methods, such as moveToFirst return false if the move cannot be made.
  • Context isn't required by the databaseToString method so removed it.
  • databaseToString method made to be an instance method rather than class method (i.e not static) and made it public.

The activity in this case I've used MainActivity

public class MainActivity extends AppCompatActivity {

    EditText item;
    EditText quantity;
    TextView calories;
    Button calculate;

    dietclass dbhelper; //<<<< we want an instance of the database helper
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_foodcal);

        item = (EditText)findViewById(R.id.etitem);
        quantity = (EditText)findViewById(R.id.etquantity);
        calories = (TextView)findViewById(R.id.calories);
        calculate = (Button)findViewById(R.id.calculate);

        dbhelper = new dietclass(this); //<<<< get the instance of the database helper

        dbhelper.insertCal_ValEntry("Porridge", "100g",5000); //<<<< For testing 
        dbhelper.insertCal_ValEntry("Cake","500g", 20000); //<<<< For testing


        calculate.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                String itemstr = item.getText().toString();
                printDatabase(itemstr);

                //String dbstring = dietclass.databaseToString(itemstr);
                //calories.setText(String.valueOf(dbstring));
            }
        });
    }

    public void printDatabase(String item){
        String dbstring =  dbhelper.databaseToString(item); //<<<< 
        //String label;wr
        //label = dbstring + "calories";
        calories.setText(String.valueOf(dbstring));
    }
}

Notes

  • The principle used above could be used in any activity. That is get an instance of the database helper and then invoked methods within the helper to get/add/alter data in the database.

Results from the above:-

  • 1) When App is started:-

enter image description here

  • 2) Clicking without input (or inputting item not in table) :-

enter image description here

  • 3) Clicking after inputting valid item :-

enter image description here

Additional Info

If you really want to get the database path the following is less prone to errors:-

    String databasepath = getDatabasePath(dietclass.DATABASE_NAME).getPath();
    ((TextView) findViewById(R.id.dbpath)).setText(databasepath);

With the dbpath TextView (note run on 7.0.0 device):-

enter image description here

On a 4.1.1 device :-

enter image description here

MikeT
  • 51,415
  • 16
  • 49
  • 68
  • Thanks for it, i got the problem and it is working. I added the data in the table externally and it wasn't accessed by the android. – Sophia Dec 17 '17 at 06:29