android – 从assets文件夹中读取sqlite错误
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了android – 从assets文件夹中读取sqlite错误,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含6927字,纯文字阅读大概需要10分钟。
内容图文
![android – 从assets文件夹中读取sqlite错误](/upload/InfoBanner/zyjiaocheng/903/846ee1918c184844b8f0dc8a2e85bd7c.jpg)
我的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)
这里发生了什么?
请帮我.
解决方法:
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" />
内容总结
以上是互联网集市为您收集整理的android – 从assets文件夹中读取sqlite错误全部内容,希望文章能够帮你解决android – 从assets文件夹中读取sqlite错误所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。