android – 从assets文件夹中读取sqlite错误

我的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" />

相关文章

SQLite架构简单,又有Json计算能力,有时会承担Json文件/RES...
使用Python操作内置数据库SQLite以及MySQL数据库。
破解微信数据库密码,用python导出微信聊天记录
(Unity)SQLite 是一个软件库,实现了自给自足的、无服务器...
安卓开发,利用SQLite实现登陆注册功能