我的Databasehelper.class
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "db3000.sqlite";
public static final String DBLOCATION = "/data/data/com.gnirt69.sqlitefromassetexample/databases/";
private Context mContext;
private SQLiteDatabase mDatabase;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, 1);
this.mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void openDatabase() {
String dbPath = mContext.getDatabasePath(DBNAME).getPath();
if(mDatabase != null && mDatabase.isOpen()) {
return;
}
mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase() {
if(mDatabase!=null) {
mDatabase.close();
}
}
public ArrayList<word> getListWord() {
word product = null;
ArrayList<word> productList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM word", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
product = new word(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3),cursor.getString(4),cursor.getInt(5));
productList.add(product);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return productList;
}
}
我的framgnet.class
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mDBHelper = new DatabaseHelper(getActivity());
//Check exists database
File database = getActivity().getDatabasePath(DatabaseHelper.DBNAME);
if(false == database.exists()) {
mDBHelper.getReadableDatabase();
//Copy db
if(copyDatabase(getActivity())) {
Toast.makeText(getActivity(), "Copy database succes", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Copy data error", Toast.LENGTH_SHORT).show();
return;
}
}
// Get product list in db when db exists
mProductList = mDBHelper.getListWord();
// getCategoryFromDataBase();
}
private boolean copyDatabase(Context context) {
try {
InputStream inputStream = context.getAssets().open(DatabaseHelper.DBNAME);
String outFileName = DatabaseHelper.DBLOCATION + DatabaseHelper.DBNAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[]buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0) {
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.w("MainActivity","DB copied");
return true;
}catch (Exception e) {
e.printStackTrace();
return false;
}
}
最初,我尝试在Activity.class中调用读取数据;它工作得很好,但是当我在片段中尝试它时,它不会运行并显示
java.io.FileNotFoundException: /data/data/com.gnirt69.sqlitefromassetexample/databases/db3000.sqlite: open failed: EACCES (Permission denied)
这里发生了什么? 请帮帮我。
答案 0 :(得分:1)
您需要在清单文件中添加以下权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
答案 1 :(得分:0)
public class Category extends Fragment {
Context con;
public DBHelper db;
@SuppressLint("NewApi")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
con=getActivity();
View rootView = inflater.inflate(R.layout.activity_category, container, false);
db=new DBHelper(con);
try {
db.createDataBase();
db.exportDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//insert data in table
db.dml("insert into tablename(c_id,c_name,c_subcat_id,c_icon)values('"+t1+"','"+t2+"','"+t3+"','"+t4+"')");
//delete data in table
db.dml("delete from tablename");
//update table
db.dml("update tablename set colum=value where id=1");
filldata();
return rootView;
}
public void filldata()
{
try
{
Cursor c=db.getData("select * from tablename");
while(c.moveToNext())
{
id=c.getString(0);
name=c.getString(1);
city=c.getString(2);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
/* DBHelper class */
public class DBHelper extends SQLiteOpenHelper {
private static String DB_NAME = "your database name"; // Read sqlite from assets folder in sqlite database
private SQLiteDatabase db;
private final Context context;
private String DB_PATH;
String outFileName="";
SharedPreferences.Editor spEdit;
public DBHelper(Context context) {
super(context, DB_NAME, null, 1);
this.context = context;
DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
}
public void exportDataBase() throws IOException {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
String formattedDate = df.format(c.getTime());
FileInputStream dbFile = new FileInputStream(DB_PATH+""+DB_NAME);
String outFileName = Environment.getExternalStorageDirectory()+"/"+formattedDate+""+DB_NAME+".db";
String outFileName1 = Environment.getExternalStorageDirectory()+"/";
File yourFile = new File(outFileName1);
if(!yourFile.exists()) {
yourFile.mkdir();
}
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = dbFile.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
//------------------------------------------------------------
PackageInfo pinfo = null;
if(!dbExist){
getReadableDatabase();
copyDataBase();
}
}
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException {
InputStream myInput = context.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public Cursor getData(String Query) {
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
try{
Cursor c = db.rawQuery(Query, null);
return c;
}catch(Exception e){
return null;
}
}
//UPDATE temp_dquot SET age='20',name1='--',rdt='11/08/2014',basic_sa='100000',plno='814',pterm='20',mterm='20',mat_date='11/08/2034',mode='YLY',dab_sa='100000',tr_sa='0',cir_sa='',bonus_rate='42',prem='5276',basic_prem='5118',dab_prem='100.0',step_rate='for Life',loyal_rate='0',bonus_rate='42',act_mat='1,88,000',mly_b_pr='448',qly_b_pr='1345',hly_b_pr='2664',yly_b_pr='5276' WHERE uniqid=1
public void dml(String Query) {
String myPath = DB_PATH + DB_NAME;
if(db==null)
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
try{
db.execSQL(Query);
}catch(Exception e){
Log.e("Error",e.toString());
}
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
/* add permission in manifest */
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />