java - 在主要 Activity 中使用 SQLiteOpenHelper 类访问数据库

标签 java android sqlite

我需要在 sqlite 数据库中预加载一些数据。我尝试使用插入查询。但每次我打开应用程序时它都会插入数据。我的搜索让我明白 SQLiteOpenHelper 是最好的选择。但我是初学者,我没有关于 SQLiteOpenHelper 的想法。我不知道如何实现它。

DataBaseHelper.java

public class DataBaseHandler extends SQLiteOpenHelper{

   public static final String DATABASE_NAME = "products.db";
   public static final String CONTACTS_TABLE_NAME = "product";
   public static final String CONTACTS_COLUMN_ID = "pid";
   public static final String CONTACTS_COLUMN_NAME = "pname";
   public static final String CONTACTS_COLUMN_EMAIL = "pspec";
   public static final String CONTACTS_COLUMN_STREET = "pprice";
   public static final String CONTACTS_COLUMN_CITY = "pfeature";
   public static final String CONTACTS_COLUMN_PHONE = "pimage";

public DataBaseHandler(Context context, String name, CursorFactory factory,
        int version) {
    super(context, name, factory, version);
    // TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL("CREATE TABLE IF NOT EXISTS product(pimage BLOB,pid INTEGER PRIMARY KEY,pname TEXT,pprice NUMERIC,pspec TEXT,pfeature TEXT)");
    db.execSQL("INSERT INTO product(pname,pprice,pspec) VALUES('Candle stick 3',4000,'Solar garden / pathway light,Solar Panel:1pc crystal silicon solar cell, Battery:1pc 1.2V Ni-MH/Ni-CD AA battery 600MA ,Material:Stainless steel ,WaterProof and safe ')");
    db.execSQL("INSERT INTO product(pname,pprice,pspec) VALUES('Candle stick 4',4500,'Solar garden / pathway light, Solar Panel:1pc crystal silicon solar cell, Battery:1pc 1.2V Ni-MH/Ni-CD AA battery 600MA, Material:Stainless steel, WaterProof and safe IP44 ')");
    db.execSQL("INSERT INTO product(pname,pprice,pspec) VALUES('Candle stick 5',3500,'Solar garden / pathway light, Solar Panel:1pc crystal silicon solar cell, Battery:1pc 1.2V Ni-MH/Ni-CD AA battery 600MA, Material:Stainless steel, WaterProof and safe IP44 ')");
    db.execSQL("INSERT INTO product(pname,pprice,pspec) VALUES('Candle stick 6',6000,'Solar garden / pathway light, Solar Panel:1pc crystal silicon solar cell, Battery:1pc 1.2V Ni-MH/Ni-CD AA battery 600MA, Material:Stainless steel, WaterProof and safe IP44 ')");
    db.execSQL("INSERT INTO product(pname,pprice,pspec) VALUES('lawn Delight',8800,'Solar garden / pathway light, Solar Panel:1pc crystal silicon solar cell, Battery:1pc 1.2V Ni-MH/Ni-CD AA battery 600MA, Material:Stainless steel, WaterProof and safe IP44 ')");
    db.execSQL("INSERT INTO product(pname,pprice,pspec) VALUES('SGLC10',4500,'Solar garden / pathway light, Solar Panel:1pc crystal silicon solar cell, Battery:1pc 1.2V Ni-MH/Ni-CD AA battery 600MA, Material:Stainless steel, WaterProof and safe IP44 ')");
    db.execSQL("INSERT INTO product(pname,pprice,pspec) VALUES('Senson',4500,'Solar garden / pathway light, Solar Panel:1pc crystal silicon solar cell, Battery:1pc 1.2V Ni-MH/Ni-CD AA battery 600MA, Material:Stainless steel, WaterProof and safe IP44 ')");
    db.execSQL("INSERT INTO product(pname,pprice,pspec) VALUES('Thejus',7500,'Solar garden / pathway light, Solar Panel:1pc crystal silicon solar cell, Battery:1pc 1.2V Ni-MH/Ni-CD AA battery 600MA, Material:Stainless steel, WaterProof and safe IP44 ')");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

}

}

Product_display.java

public class product_display extends Activity {

ListView prd_list;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.product_disply);
    prd_list = (ListView) findViewById(R.id.list);

    DataBaseHandler dbh = new DataBaseHandler(this);

     Intent in=getIntent();
     Bundle bundle=in.getExtras();
     final String list=bundle.getString("key");
     SQLiteDatabase db = dbh.getWritableDatabase();

    Cursor cr = db.rawQuery("SELECT * FROM product", null);
    final String[] pname = new String[cr.getCount()];
    String[] price = new String[cr.getCount()];

    int i = 0;
    while(cr.moveToNext())
    {
        String name = cr.getString(cr.getColumnIndex("pname"));
        String prprice = cr.getString(cr.getColumnIndex("pprice"));

        pname[i] = name;
        price[i] = prprice;
        i++;
    }

    ListAdapter adapter = new com.example.login_signup.ListAdapter(this, pname, price);
    prd_list.setAdapter(adapter);

    prd_list.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            String nme = pname[arg2];   

            Bundle bun = new Bundle();
            bun.putString("key",list);
            Bundle bn = new Bundle();
            bn.putString("name",nme);
            Intent in = new Intent(product_display.this, Product_Details.class);
            in.putExtras(bun);
            in.putExtras(bn);
            startActivity(in);
            }

    });



}

}

product_dtls.java

public class Product_Details extends Activity{

TextView name,price,specification,feature;
String nme;
String pname;
String prprice;
String pspec;
String pfeature;
Button add2cart,by_nw;
ImageView image;
ImageButton imgbtn; 

Integer [] pmge ={R.drawable.candle1,R.drawable.candl3,
        R.drawable.candl4,R.drawable.candl5,R.drawable.candl6,
        R.drawable.lawn,R.drawable.sglc10,R.drawable.senson,R.drawable.thejus6669};
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.product_dtls);
    image=(ImageView)findViewById(R.id.pr_img);
    name = (TextView) findViewById(R.id.txtPr_name);
    price = (TextView) findViewById(R.id.txtprice);
    specification=(TextView)findViewById(R.id.txtPr_spec);
    feature=(TextView)findViewById(R.id.txtPr_feature);
    imgbtn=(ImageButton)findViewById(R.id.cartimg);
    add2cart=(Button)findViewById(R.id.add2cart);
    by_nw=(Button)findViewById(R.id.buy_nw);
    DataBaseHandler dbh = new DataBaseHandler(this);
    SQLiteDatabase db = dbh.getWritableDatabase();
    Intent in = getIntent();
    Bundle bn = in.getExtras();
    Bundle bun=in.getExtras();
    final String dtl=bun.getString("key");
    nme = bn.getString("name");
    Cursor cr = db.rawQuery("SELECT * FROM product WHERE pname = '"+nme+"'", null);

    while(cr.moveToNext())
    {
        String name = cr.getString(cr.getColumnIndex("pname"));
        String pr1price = cr.getString(cr.getColumnIndex("pprice"));
        String prspc=cr.getString(cr.getColumnIndex("pspec"));
        String prfeature=cr.getString(cr.getColumnIndex("pfeature"));
        pname = name;
        prprice = pr1price;
        pspec=prspc;
        pfeature=prfeature;
    }
    name.setText(pname);
    price.setText("Rs " +prprice + "/-");
    specification.setText(pspec);
    feature.setText(pfeature);


    add2cart.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            boolean incart=false;
            String nm=name.getText().toString();
            db=Product_Details.this.openOrCreateDatabase("addcart", MODE_PRIVATE, null);
            Cursor cur=db.rawQuery("select * from add2cart where pnme='"+nm+"'",null);

            if (cur.moveToFirst()){
                String prdname=cur.getString(cur.getColumnIndex("pnme"));

                if (nm.equals(prdname)){
                    add2cart.setText("Already in Cart");
                    incart=true;
                }
            }

            if(incart==false){
                db.execSQL("INSERT INTO add2cart (pnme,prate)VALUES('"+nm+"','"+prprice+"')");
                Toast.makeText(getApplicationContext(),"added to cart",Toast.LENGTH_SHORT).show();


            }

        }

    });

}

}

最佳答案

  1. 考虑在代码本身中嵌入数据库名称和版本。改变

    public DataBaseHandler(Context context, String name, CursorFactory factory,
        int version) {
        super(context, name, factory, version);
    

    类似于

    public DataBaseHandler(Context context) {
        super(context, DATABASE_NAME, null, 1);
    
  2. 在您的 Activity 中实例化助手:

    DataBaseHandler dbh = new DataBaseHandler(this);
    
  3. 调用getWritableDatabase() 在助手上:

    SQLiteDatabase db = dbh.getWritableDatabase();
    
  4. 为您的数据库操作使用 db,而不是您现在通过 openOrCreateDatabase() 获取的操作。

关于java - 在主要 Activity 中使用 SQLiteOpenHelper 类访问数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28040474/

相关文章:

java - 是否可以在 java android 项目中使用 lua 脚本?

sql - 如何按日期排序但按特定列值 SQL 分组

java - 如何在不更改数据库架构的情况下将 UrlType 从 Hibernate 3.6 迁移到 4.3?

java - 什么时候是使用应用服务器的合适时机?

android - 与当前 View 相关的问题

android - 通过套接字发送和接收数据

java - SQLite 文件打开器 Android Studio

python - 如何将内存中的 SQLite 数据库复制到 Python 中的另一个内存中的 SQLite 数据库?

使用下一代插件的 java 小程序

java - 如何从字节中提取 Mime 类型 []