ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

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

2019-07-06 09:33:12  阅读:201  来源: 互联网

标签:android sqlite android-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" />

标签:android,sqlite,android-sqlite
来源: https://codeday.me/bug/20190706/1396323.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有