Я создал базу данных sqlite и поместил ее в папку активов моего проекта Android.Теперь я хочу выполнить Insert,Delete,Retrieve
операции с этой базой данных.
Я создал новое действие, в котором я буду вводить данные о человеке, а затем я нажму кнопку сохранения (checkout_btn)
, чтобы сохранить эту информацию в существующейбаза данных.
Я не знаю, что не так в этом коде.Я не получаю никаких ошибок, и даже данные не вставляются в существующую базу данных.
Я также хочу добавить Извлечение данных (on button click)
из базы данных на основе значения поля поиска, предоставленного пользовательскими функциями в этом приложении.
Вот мой код:
This class talk about my database which is already present in my assets folder in my project. In this database only i have to insert my data from a form.
**DBConstant.Java**
public abstract class DBConstant
{ //database file directory
public static String DATABASE_PATH = "/data/data/activity.test/databases";
//database file name
public static String DATABASE_FILE = "test.db";
//database version
public static int DATABASE_VERSION = 1;
}
**This is my DBOpenHelper.Java file**
**DBOpenHelper.Java**
public class DBOpenHelper extends SQLiteOpenHelper {
public DBOpenHelper(Context context, String path, int version){
super(context, path, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
**Below is my DBOperator.Java file**
/**
* Class to manipulate tables & data
* Uses singleton pattern to create single instance
*/
public class DBOperator
{
private static DBOperator instance = null;
private SQLiteDatabase db;
private DBOperator()
{
//path of database file
String path = DBConstant.DATABASE_PATH + "/" + DBConstant.DATABASE_FILE;
db = SQLiteDatabase.openDatabase(path, null,
SQLiteDatabase.OPEN_READWRITE);
}
/*
* Singleton Pattern
* Why should we avoid multiple instances here?
*/
public static DBOperator getInstance()
{
if (instance==null) instance = new DBOperator();
return instance;
}
/**
* Copy database file
* From assets folder (in the project) to android folder (on device)
*/
public static void copyDB(Context context) throws
IOException,FileNotFoundException{
String path = DBConstant.DATABASE_PATH + "/" + DBConstant.DATABASE_FILE;
File file = new File(path);
if (!file.exists()){
DBOpenHelper dbhelper = new DBOpenHelper(context, path ,1);
dbhelper.getWritableDatabase();
InputStream is = context.getAssets().open(DBConstant.DATABASE_FILE);
OutputStream os = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer))>0){
os.write(buffer, 0, length);
}
is.close();
os.flush();
os.close();
}
}
/**
* execute sql without returning data, such as alter
* @param sql
*/
public void execSQL(String sql) throws SQLException
{
db.execSQL(sql);
}
/**
* execute sql such as update/delete/insert
* @param sql
* @param args
* @throws SQLException
*/
public void execSQL(String sql, Object[] args) throws SQLException
{
db.execSQL(sql, args);
}
/**
* execute sql query
* @param sql
* @param selectionArgs
* @return cursor
* @throws SQLException
*/
public Cursor execQuery(String sql,String[] selectionArgs) throws
SQLException
{
return db.rawQuery(sql, selectionArgs);
}
/**
* execute query without arguments
* @param sql
* @return
* @throws SQLException
*/
public Cursor execQuery(String sql) throws SQLException
{
return this.execQuery(sql, null);
}
/**
* close database
*/
public void closeDB()
{
if (db!=null) db.close();
}
}
Here is my DBOperator.Java
/**
* Class to manipulate tables & data
* Uses singleton pattern to create single instance
*/
public class DBOperator
{
private static DBOperator instance = null;
private SQLiteDatabase db;
private DBOperator()
{
//path of database file
String path = DBConstant.DATABASE_PATH + "/" + DBConstant.DATABASE_FILE;
db = SQLiteDatabase.openDatabase(path, null,
SQLiteDatabase.OPEN_READWRITE);
}
/*
* Singleton Pattern
* Why should we avoid multiple instances here?
*/
public static DBOperator getInstance()
{
if (instance==null) instance = new DBOperator();
return instance;
}
/**
* Copy database file
* From assets folder (in the project) to android folder (on device)
*/
public static void copyDB(Context context) throws
IOException,FileNotFoundException{
String path = DBConstant.DATABASE_PATH + "/" + DBConstant.DATABASE_FILE;
File file = new File(path);
if (!file.exists()){
DBOpenHelper dbhelper = new DBOpenHelper(context, path ,1);
dbhelper.getWritableDatabase();
InputStream is = context.getAssets().open(DBConstant.DATABASE_FILE);
OutputStream os = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer))>0){
os.write(buffer, 0, length);
}
is.close();
os.flush();
os.close();
}
}
/**
* execute sql without returning data, such as alter
* @param sql
*/
public void execSQL(String sql) throws SQLException
{
db.execSQL(sql);
}
/**
* execute sql such as update/delete/insert
* @param sql
* @param args
* @throws SQLException
*/
public void execSQL(String sql, Object[] args) throws SQLException
{
db.execSQL(sql, args);
}
/**
* execute sql query
* @param sql
* @param selectionArgs
* @return cursor
* @throws SQLException
*/
public Cursor execQuery(String sql,String[] selectionArgs) throws
SQLException
{
return db.rawQuery(sql, selectionArgs);
}
/**
* execute query without arguments
* @param sql
* @return
* @throws SQLException
*/
public Cursor execQuery(String sql) throws SQLException
{
return this.execQuery(sql, null);
}
/**
* close database
*/
public void closeDB()
{
if (db!=null) db.close();
}
}
NewActivity.java
public class NewpActivity extends AppCompatActivity
{
String PaFirstName,PaLastName,PaDOB,PaGender,PaContact,PaStreetAPT,PaCity,PaState,country,PaPincode,PaInsurance;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_newp);
Button signUpBtn = (Button) findViewById(R.id.checkout_btn);
signUpBtn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
//Running method for updating string variables from input boxes
getValues();
DBOperator.getInstance().execSQL(SQLCommand.NEW_USER, getArgs());
Toast.makeText(getBaseContext(), "Checkout successfully", Toast.LENGTH_SHORT).show();
}
});
}
SQLCommand.java
public abstract class SQLCommand {
public static String NEW_USER = "insert into Patient(PaFirstName,PaLastName,PaDOB,PaGender,PaContact,PaStreetAPT,PaCity,PaState,PaPincode,PaInsurance) values(?,?,?,?,?,?,?,?,?,?)";
}