如何从SQLite中提取数据?

时间:2018-04-30 11:39:39

标签: android sqlite

我必须从sqlite中提取数据然后进行比较。但我有运行时错误 这是我从sqlite检索数据但不起作用的代码 我有两节课 1-dbmanagerclass 2-mainactivity类 这是我的dbmanager类:

public class DBManager extends SQLiteOpenHelper {
static String dbName= "managmentdb";
static int dbVersion=1;
static String tblName= "user";
static String column_id= "_id";
static String column_username= "username";
static String column_password= "password";
SQLiteDatabase db;
Activity context;
public DBManager(Activity context) {
    super(context, dbName, null, dbVersion);
    this.context=context;
}
@Override
public void onCreate(SQLiteDatabase db) {
    try { db.execSQL( " create table " + tblName + " ( " + column_id + " 
integer primary key  autoincrement , " + column_username + " text , " + 
column_password + " text ); ");
        Toast.makeText(context,"db is created",Toast.LENGTH_LONG).show();

    }catch (Exception err){
        Toast.makeText(context,err.toString(),Toast.LENGTH_LONG).show();
    }
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
void insert(String user, String pass) {
    db = this.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(column_username, user);
    cv.put(column_password, pass);
    try {
        db.insert(tblName, null, cv);
        Toast.makeText(context, "insert!!!", Toast.LENGTH_SHORT).show();
    } catch (Exception ex) {
        Toast.makeText(context, ex.toString(), Toast.LENGTH_SHORT).show();
    }
}
Cursor selectAll(){
    db=this.getReadableDatabase();
    Cursor c=db.rawQuery("Select * from "+tblName,null);
    return c;
}
Cursor select(){
    db=this.getReadableDatabase();
    Cursor c=db.rawQuery("Select * from "+tblName,);
    return c;
}
}

这是检索的类

public class MainActivity extends AppCompatActivity implements 
View.OnClickListener {
DBManager dbManager;
String[] from = 
{DBManager.column_id,DBManager.column_username,DBManager.column_password};
int[] to={R.id.txtid,R.id.txtuser,R.id.txtpass};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button register= (Button) findViewById(R.id.act_login_btnregister);
    Button enter= (Button) findViewById(R.id.act_login_btnenter);
    register.setOnClickListener(this);
    enter.setOnClickListener(this);
}
@Override
public void onClick(View v) {
    if(v.getId()==R.id.act_login_btnregister){
        startActivity(new Intent(this,RegisterPage.class));
    }
    else if (v.getId()==R.id.act_login_btnenter){
        DBManager dbManager=new DBManager(this);
        Cursor cursor;
        cursor=dbManager.selectAll();
        String name=cursor.getString(1);
Toast.makeText(getApplicationContext(),name,Toast.LENGTH_LONG).show();
        }
    }
}

为什么我的应用有错误以及我如何解决问题

1 个答案:

答案 0 :(得分:-1)

我提供了一些代码,您可以更好地管理SQLite数据库。

为数据库创建单独的类以执行如下的CRUD操作..

public class DBHelper extends SQLiteOpenHelper{

//USER TABLE
public static final String USER_TABLE_NAME = "MyTableTwo";
public static final String USER_COLUMN_USER_ID = "id";
public static final String USER_COLUMN_USER_NAME = "Item_Name";
public static final String USER_COLUMN_USER_ADDRESS = "Weight";
public static final String USER_COLUMN_USER_CREATED_AT = "MRP";
public static final String USER_COLUMN_USER_UPDATED_AT = "BARCODE";

public DBHelper(Context context,
                String dbName,
                Integer version) {
    super(context, dbName, null, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
    tableCreateStatements(db);
}

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

private void tableCreateStatements(SQLiteDatabase db) {
    try {
        db.execSQL(
                "CREATE TABLE IF NOT EXISTS "
                        + USER_TABLE_NAME + "("
                        + USER_COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                        + USER_COLUMN_USER_NAME + " VARCHAR(20), "
                        + USER_COLUMN_USER_ADDRESS + " VARCHAR(50), "
                        + USER_COLUMN_USER_CREATED_AT + " VARCHAR(10) DEFAULT " + getCurrentTimeStamp() + ", "
                        + USER_COLUMN_USER_UPDATED_AT + " VARCHAR(10) DEFAULT " + getCurrentTimeStamp() + ")"
        );

    } catch (SQLException e) {
        e.printStackTrace();
    }
}
public List<MyTableTwo> getMyItems() {
    List<MyTableTwo> mySuperList = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();
    String selectQuery = "SELECT  * FROM " + USER_TABLE_NAME ;
    Cursor c = db.rawQuery(selectQuery, null);
    if (c != null) {
        c.moveToFirst();
        while (c.isAfterLast() == false) {
            MyTableTwo myTable = new MyTableTwo();
            myTable.itemName = (c.getString(c.getColumnIndex("Item_Name")));
            myTable.weight = (c.getString(c.getColumnIndex("Weight")));
            myTable.mrp = (c.getString(c.getColumnIndex("MRP")));
            myTable.barcod = (c.getString(c.getColumnIndex("BARCODE")));

            mySuperList.add(myTable);
            c.moveToNext();
        }
    }
    return mySuperList;
}

public Long insertUser(MyTableTwo user) throws Exception {
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(USER_COLUMN_USER_NAME, user.itemName);
        contentValues.put(USER_COLUMN_USER_ADDRESS, user.barcod);
        contentValues.put(USER_COLUMN_USER_CREATED_AT, user.weight);
        contentValues.put(USER_COLUMN_USER_UPDATED_AT, user.barcod);

        return db.insert(USER_TABLE_NAME, null, contentValues);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

private String getCurrentTimeStamp() {
    return String.valueOf(System.currentTimeMillis() / 1000);
}

}

然后在make pojo类之后插入任何类型的对象,如下面的代码..

public class MyTableTwo {

public String itemName,weight,mrp,barcod;
public MyTableTwo(){}
public MyTableTwo(String itemName, String weight, String mrp, String barcod) {
    this.itemName = itemName;
    this.weight = weight;
    this.mrp = mrp;
    this.barcod = barcod;
}

}

然后在inset的mainactivity之后使用下面的代码..

DBHelper dbHelper=new DBHelper(DbInsert.this,"DB",1);
 MyTableTwo myTableTwo=new MyTableTwo("abcd","5kg","120","xyz");
            try {
                dbHelper.insertUser(myTableTwo);
            } catch (Exception e) {
                e.printStackTrace();
            }

用于从代码中使用的表中读取数据..

            List<MyTableTwo> myTableTwos=dbHelper.getMyItems();
            for (MyTableTwo myTableTwo1:myTableTwos){
                Log.d("Name",myTableTwo1.itemName);
            }

你可以在pojo类中创建setter或getter方法。