从sqlite数据库中检索数据是通过此代码

时间:2017-12-16 11:34:59

标签: java android sqlite

我没有收到返回的添加字符串。 Android应用程序将输入作为食物项目并打印其各自的卡路里。 这是创建表的代码:

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);
    }
}

这是从我的活动中检索数据的代码,它将项目和卡路里作为输入。

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;
            }

我没有收到任何错误,但代码没有从select查询中获取值,任何人都可以帮忙。

1 个答案:

答案 0 :(得分:0)

我认为当您只需要使用数据库帮助程序时,您似乎使用多个数据库帮助程序/方法来打开同一个数据库,从而使事情变得混乱和复杂。我不确定究竟是什么问题,没有足够的代码来构建精确的副本。

而是创建简化的工作代码。

根据您的代码进行重写/简化: -

第一个数据库帮助类,即 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;
    }
}

注释

  • 出于测试目的,已添加方法insertCal_ValEntry
  • 完成任何打开数据库的尝试,而不是由帮助程序完成。
  • 检查游标是否为空已被删除,它基本上没用,因为SQLite不会返回null,它将始终返回一个游标,该游标可能为空。如果无法移动,则move???方法(例如moveToFirst)将返回false。
  • databaseToString方法不需要上下文,因此将其删除。
  • databaseToString方法是一个实例方法而不是类方法(即非静态方法),并将其公之于众。

在这种情况下的活动我使用了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));
    }
}

注释

  • 上述原则可用于任何活动。这是获取数据库帮助程序的一个实例,然后调用帮助程序中的方法来获取/添加/更改数据库中的数据。

以上结果: -

  • 1)启动应用程序时: -

enter image description here

  • 2)点击没有输入(或输入不在表格中的项目): -

enter image description here

  • 3)输入有效项目后点击: -

enter image description here

其他信息

如果您真的想要获取数据库路径,则以下内容不容易出错: -

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

使用 dbpath TextView(注意在7.0.0设备上运行): -

enter image description here

在4.1.1设备上: -

enter image description here