Create SQLite database in android

前端 未结 8 558
故里飘歌
故里飘歌 2020-11-29 03:12

I want to create a SQLite database in my app, which contains three tables, I will add data into tables and will use them later on.

but I like to keep database ,as if

相关标签:
8条回答
  • 2020-11-29 03:49

    Here is code

    DatabaseMyHandler.class

    public class DatabaseMyHandler extends SQLiteOpenHelper {
    
        private SQLiteDatabase myDataBase;
        private Context context = null;
        private static String TABLE_NAME = "customer";
        public static final String DATABASE_NAME = "Student.db";
        public final static String DATABASE_PATH = "/data/data/com.pkgname/databases/";
        public static final int DATABASE_VERSION = 2;
    
        public DatabaseMyHandler(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            this.context = context;
            try {
                createDatabase();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    
        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {
            myDataBase = sqLiteDatabase;
    
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    
        }
    
        //Check database already exists or not
    
        private boolean checkDatabaseExists() {
            boolean checkDB = false;
            try {
                String PATH = DATABASE_PATH + DATABASE_NAME;
                File dbFile = new File(PATH);
                checkDB = dbFile.exists();
    
            } catch (SQLiteException e) {
    
            }
            return checkDB;
        }
    
    
        //Create a empty database on the system
        public void createDatabase() throws IOException {
            boolean dbExist = checkDatabaseExists();
    
            if (dbExist) {
                Log.v("DB Exists", "db exists");
            }
    
            boolean dbExist1 = checkDatabaseExists();
            if (!dbExist1) {
                this.getWritableDatabase();
                try {
                    this.close();
                    copyDataBase();
                } catch (IOException e) {
                    throw new Error("Error copying database");
                }
            }
        }
    
        //Copies your database from your local assets-folder to the just created empty database in the system folder
        private void copyDataBase() throws IOException {
            String outFileName = DATABASE_PATH + DATABASE_NAME;
            OutputStream myOutput = new FileOutputStream(outFileName);
            InputStream myInput = context.getAssets().open(DATABASE_NAME);
    
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }
            myInput.close();
            myOutput.flush();
            myOutput.close();
        }
    
    
        //Open Database
        public void openDatabase() throws SQLException {
            String PATH = DATABASE_PATH + DATABASE_NAME;
            myDataBase = SQLiteDatabase.openDatabase(PATH, null, SQLiteDatabase.OPEN_READWRITE);
        }
    
        //for insert data into database
    
    
        public void insertCustomer(String customer_id, String email_id, String password, String description, int balance_amount) {
            try {
                openDatabase();
                SQLiteDatabase db = this.getWritableDatabase();
                ContentValues contentValues = new ContentValues();
                contentValues.put("customer_id", customer_id);
                contentValues.put("email_id", email_id);
                contentValues.put("password", password);
                contentValues.put("description", description);
                contentValues.put("balance_amount", balance_amount);
                db.insert(TABLE_NAME, null, contentValues);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    
    
        public ArrayList<ModelCreateCustomer> getLoginIdDetail(String email_id, String password) {
    
            ArrayList<ModelCreateCustomer> result = new ArrayList<ModelCreateCustomer>();
            //boolean flag = false;
            String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE email_id='" + email_id + "' AND password='" + password + "'";
    
            try {
                openDatabase();
                Cursor cursor = myDataBase.rawQuery(selectQuery, null);
                //cursor.moveToFirst();
    
    
                if (cursor.getCount() > 0) {
                    if (cursor.moveToFirst()) {
                        do {
                            ModelCreateCustomer model = new ModelCreateCustomer();
                            model.setId(cursor.getInt(cursor.getColumnIndex("id")));
                            model.setCustomerId(cursor.getString(cursor.getColumnIndex("customer_id")));
                            model.setCustomerEmailId(cursor.getString(cursor.getColumnIndex("email_id")));
                            model.setCustomerPassword(cursor.getString(cursor.getColumnIndex("password")));
                            model.setCustomerDesription(cursor.getString(cursor.getColumnIndex("description")));
                            model.setCustomerBalanceAmount(cursor.getInt(cursor.getColumnIndex("balance_amount")));
    
                            result.add(model);
                        }
                        while (cursor.moveToNext());
                    }
                    Toast.makeText(context, "Login Successfully", Toast.LENGTH_SHORT).show();
                }
    
    //            Log.e("Count", "" + cursor.getCount());
                cursor.close();
                myDataBase.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
    
    
            return result;
        }
    
        public void updateCustomer(String id, String email_id, String description, int balance_amount) {
    
            try {
                openDatabase();
                SQLiteDatabase db = this.getWritableDatabase();
                ContentValues contentValues = new ContentValues();
                contentValues.put("email_id", email_id);
                contentValues.put("description", description);
                contentValues.put("balance_amount", balance_amount);
    
                db.update(TABLE_NAME, contentValues, "id=" + id, null);
    
            } catch (SQLException e) {
                e.printStackTrace();
            }
    
        }
    }
    

    Customer.class

    public class Customer extends AppCompatActivity{
      private DatabaseMyHandler mydb;
      @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_customer);
    
            mydb = new DatabaseMyHandler(CreateCustomerActivity.this);
     mydb.insertCustomer("1", "a@a.com", "123", "test", 100);
    
        }
    
    }
    
    0 讨论(0)
  • 2020-11-29 03:50

    Why not refer to the documentation or the sample code shipping with the SDK? There's code in the samples on how to create/update/fill/read databases using the helper class described in the document I linked.

    0 讨论(0)
  • 2020-11-29 03:53

    If you want to keep the database between uninstalls you have to put it on the SD Card. This is the only place that won't be deleted at the moment your app is deleted. But in return it can be deleted by the user every time.

    If you put your DB on the SD Card you can't use the SQLiteOpenHelper anymore, but you can use the source and the architecture of this class to get some ideas on how to implement the creation, updating and opening of a databse.

    0 讨论(0)
  • 2020-11-29 03:54

    this is the full source code to direct use,

        public class CardDBDAO {
    
            protected SQLiteDatabase database;
            private DataBaseHelper dbHelper;
            private Context mContext;
    
            public CardDBDAO(Context context) {
                this.mContext = context;
                dbHelper = DataBaseHelper.getHelper(mContext);
                open();
    
            }
    
            public void open() throws SQLException {
                if(dbHelper == null)
                    dbHelper = DataBaseHelper.getHelper(mContext);
                database = dbHelper.getWritableDatabase();
            }
    
        }
    
    
    
        public class DataBaseHelper extends SQLiteOpenHelper {
    
            private static final String DATABASE_NAME = "mydbnamedb";
            private static final int DATABASE_VERSION = 1;
    
            public static final String CARDS_TABLE = "tbl_cards";
            public static final String POICATEGORIES_TABLE = "tbl_poicategories";
            public static final String POILANGS_TABLE = "tbl_poilangs";
    
            public static final String ID_COLUMN = "id";
    
            public static final String POI_ID = "poi_id";
            public static final String POICATEGORIES_COLUMN = "poi_categories";
    
            public static final String POILANGS_COLUMN = "poi_langs";
    
            public static final String CARDS = "cards";
            public static final String CARD_ID = "card_id";
            public static final String CARDS_PCAT_ID = "pcat_id";
    
            public static final String CREATE_PLANG_TABLE = "CREATE TABLE "
                    + POILANGS_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY,"
                    + POILANGS_COLUMN + " TEXT, " + POI_ID + " TEXT)";
    
            public static final String CREATE_PCAT_TABLE = "CREATE TABLE "
                    + POICATEGORIES_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY,"
                    + POICATEGORIES_COLUMN + " TEXT, " + POI_ID + " TEXT)";
    
            public static final String CREATE_CARDS_TABLE = "CREATE TABLE "
                    + CARDS_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY," + CARD_ID
                    + " TEXT, " + CARDS_PCAT_ID + " TEXT, " + CARDS + " TEXT)";
    
            private static DataBaseHelper instance;
    
            public static synchronized DataBaseHelper getHelper(Context context) {
                if (instance == null)
                    instance = new DataBaseHelper(context);
                return instance;
            }
    
            private DataBaseHelper(Context context) {
                super(context, DATABASE_NAME, null, DATABASE_VERSION);
            }
    
            @Override
            public void onOpen(SQLiteDatabase db) {
                super.onOpen(db);
                if (!db.isReadOnly()) {
                    // Enable foreign key constraints
                    // db.execSQL("PRAGMA foreign_keys=ON;");
                }
            }
    
            @Override
            public void onCreate(SQLiteDatabase db) {
                db.execSQL(CREATE_PCAT_TABLE);
                db.execSQL(CREATE_PLANG_TABLE);
                db.execSQL(CREATE_CARDS_TABLE);
            }
    
            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
            }
        }
    
    
    
    
        public class PoiLangDAO extends CardDBDAO {
    
                private static final String WHERE_ID_EQUALS = DataBaseHelper.ID_COLUMN
                        + " =?";
    
                public PoiLangDAO(Context context) {
                    super(context);
                }
    
                public long save(PLang plang_data) {
    
                    ContentValues values = new ContentValues();
                    values.put(DataBaseHelper.POI_ID, plang_data.getPoi_id());
                    values.put(DataBaseHelper.POILANGS_COLUMN, plang_data.getLangarr());
    
                    return database
                            .insert(DataBaseHelper.POILANGS_TABLE, null, values);
                }
    
                public long update(PLang plang_data) {
                    ContentValues values = new ContentValues();
                    values.put(DataBaseHelper.POI_ID, plang_data.getPoi_id());
                    values.put(DataBaseHelper.POILANGS_COLUMN, plang_data.getLangarr());
    
                    long result = database.update(DataBaseHelper.POILANGS_TABLE,
                            values, WHERE_ID_EQUALS,
                            new String[] { String.valueOf(plang_data.getId()) });
                    Log.d("Update Result:", "=" + result);
                    return result;
    
                }
    
                public int deleteDept(PLang plang_data) {
                    return database.delete(DataBaseHelper.POILANGS_TABLE,
                            WHERE_ID_EQUALS, new String[] { plang_data.getId() + "" });
                }
    
                public List<PLang> getPLangs1() {
                    List<PLang> plang_list = new ArrayList<PLang>();
                    Cursor cursor = database.query(DataBaseHelper.POILANGS_TABLE,
                            new String[] { DataBaseHelper.ID_COLUMN, DataBaseHelper.POI_ID,
                                    DataBaseHelper.POILANGS_COLUMN }, null, null, null,
                            null, null);
    
                    while (cursor.moveToNext()) {
                        PLang plang_bin = new PLang();
                        plang_bin.setId(cursor.getInt(0));
                        plang_bin.setPoi_id(cursor.getString(1));
                        plang_bin.setLangarr(cursor.getString(2));
                        plang_list.add(plang_bin);
                    }
                    return plang_list;
                }
    
                public List<PLang> getPLangs(String pid) {
                    List<PLang> plang_list = new ArrayList<PLang>();
    
                    String selection = DataBaseHelper.POI_ID + "=?";
                    String[] selectionArgs = { pid };
    
                    Cursor cursor = database.query(DataBaseHelper.POILANGS_TABLE,
                            new String[] { DataBaseHelper.ID_COLUMN, DataBaseHelper.POI_ID,
                                    DataBaseHelper.POILANGS_COLUMN }, selection,
                            selectionArgs, null, null, null);
    
                    while (cursor.moveToNext()) {
                        PLang plang_bin = new PLang();
                        plang_bin.setId(cursor.getInt(0));
                        plang_bin.setPoi_id(cursor.getString(1));
                        plang_bin.setLangarr(cursor.getString(2));
                        plang_list.add(plang_bin);
                    }
                    return plang_list;
                }
    
                public void loadPLangs(String poi_id, String langarrs) {
                    PLang plangbin = new PLang(poi_id, langarrs);
    
                    List<PLang> plang_arr = new ArrayList<PLang>();
                    plang_arr.add(plangbin);
    
                    for (PLang dept : plang_arr) {
                        ContentValues values = new ContentValues();
                        values.put(DataBaseHelper.POI_ID, dept.getPoi_id());
                        values.put(DataBaseHelper.POILANGS_COLUMN, dept.getLangarr());
                        database.insert(DataBaseHelper.POILANGS_TABLE, null, values);
                    }
                }
    
            }
    
    
    
    
            public class PLang {
    
                public PLang() {
                    super();
                }
    
                public PLang(String poi_id, String langarrs) {
                    // TODO Auto-generated constructor stub
    
                    this.poi_id = poi_id;
                    this.langarr = langarrs;
                }
    
                public int getId() {
                    return id;
                }
    
                public void setId(int id) {
                    this.id = id;
                }
    
                public String getPoi_id() {
                    return poi_id;
                }
    
                public void setPoi_id(String poi_id) {
                    this.poi_id = poi_id;
                }
    
                public String getLangarr() {
                    return langarr;
                }
    
                public void setLangarr(String langarr) {
                    this.langarr = langarr;
                }
    
                private int id;
                private String poi_id;
                private String langarr;
    
        }
    
    0 讨论(0)
  • 2020-11-29 04:00

    Better example is [here]

     try {
       myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
    
       /* Create a Table in the Database. */
       myDB.execSQL("CREATE TABLE IF NOT EXISTS "
         + TableName
         + " (Field1 VARCHAR, Field2 INT(3));");
    
       /* Insert data to a Table*/
       myDB.execSQL("INSERT INTO "
         + TableName
         + " (Field1, Field2)"
         + " VALUES ('Saranga', 22);");
    
       /*retrieve data from database */
       Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);
    
       int Column1 = c.getColumnIndex("Field1");
       int Column2 = c.getColumnIndex("Field2");
    
       // Check if our result was valid.
       c.moveToFirst();
       if (c != null) {
        // Loop through all Results
        do {
         String Name = c.getString(Column1);
         int Age = c.getInt(Column2);
         Data =Data +Name+"/"+Age+"\n";
        }while(c.moveToNext());
       }
    
    0 讨论(0)
  • 2020-11-29 04:00

    To understand how to use sqlite database in android with best practices see - Android with sqlite database

    There are few classes about which you should know and those will help you model your tables and models i.e android.provider.BaseColumns

    Below is an example of a table

    public class ProductTable implements BaseColumns {
      public static final String NAME = "name";
      public static final String PRICE = "price";
      public static final String TABLE_NAME = "products";
    
      public static final String CREATE_QUERY = "create table " + TABLE_NAME + " (" +
          _ID + " INTEGER, " +
          NAME + " TEXT, " +
          PRICE + " INTEGER)";
    
      public static final String DROP_QUERY = "drop table " + TABLE_NAME;
      public static final String SElECT_QUERY = "select * from " + TABLE_NAME;
    }
    
    0 讨论(0)
提交回复
热议问题