在Android中复制SQLite数据库时出错

时间:2017-01-11 19:46:50

标签: java android database sqlite

我运行应用程序时遇到此错误。你能帮帮我吗

  

流程:com.abdallahmurad.quoter001,PID:6218                                                    java.lang.Error:ErrorCopyingDataBase                                                        在com.abdallahmurad.quoter001.DBHelper.createDataBase(DBHelper.java:123)                                                        在com.abdallahmurad.quoter001.DBHelper。(DBHelper.java:65)                                                        在com.abdallahmurad.quoter001.QuoterActivity.onCreate(QuoterActivity.java:77)

这是班级:

public class DBHelper extends SQLiteOpenHelper{

SQLiteDatabase db = null;
Context context = null;

static String packageName = "com.easwareapps.quoter";
private static String DB_PATH = "/data/data/" + packageName + "/databases/";
private static String DB_NAME ="quoter.db";
private static final int VERSION = 1;



@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


}

public DBHelper(Context context) {
    super(context, DB_NAME, null, VERSION);
    try{
        this.context = context;
        createDataBase();
    }catch(Exception e){
        e.printStackTrace();
    }


}

public Cursor getQuotes(int tag, int author){

    db = this.getReadableDatabase();
    String authorFilter = (author == 0)?"":" and author._id=" + author;
    String tagFilter = (tag == 0)?"":" INNER JOIN quotes_tags tag ON tag.quote=quote._id AND tag.tag=" + tag + " ";
    String sql = "SELECT quote.quote, author.author, author._id, quote._id from quotes quote, authors author " +  tagFilter + "where quote.author=author._id and quote.status=1 " + authorFilter;// + " ORDER BY RANDOM()";
    return db.rawQuery(sql, null);

}

public String[] getRandomQuote(){

    db = this.getReadableDatabase();
    String sql = "SELECT quote.quote, author.author, author._id, quote._id from quotes quote, authors author where quote.author=author._id and quote.status=1 ORDER BY RANDOM() LIMIT 1";
    Cursor c = db.rawQuery(sql, null);
    if(c.moveToFirst()) {
        return new String[]{c.getString(1), c.getString(0), c.getString(2), c.getString(3)};
    }else{
        return new String[]{"", "", "", ""};
    }

}

public String[] getQuote(int id){

    db = this.getReadableDatabase();
    String sql = "SELECT quote.quote, author.author, author._id, quote._id from quotes quote, authors author where quote.author=author._id and quote.status=1 and quote._id=" + id;
    Cursor c = db.rawQuery(sql, null);
    if(c.moveToFirst()) {
        return new String[]{c.getString(1), c.getString(0), c.getString(2), c.getString(3)};
    }else{
        return new String[]{"", "", "", ""};
    }

}





public void createDataBase() throws IOException {

    boolean mDataBaseExist = checkDataBase();
    if(!mDataBaseExist) {
        try  {
            copyDataBase();
            Log.e("DB", "createDatabase database created");
        }
        catch (IOException mIOException)  {
            Log.d("Error", Log.getStackTraceString(mIOException));
            throw new Error("ErrorCopyingDataBase");
        }
    }
}

private boolean checkDataBase() {
    File dbFile = new File(DB_PATH + DB_NAME);
    return dbFile.exists();
}

private void copyDataBase() throws IOException {
    InputStream mInput = context.getAssets().open(DB_NAME);
    String outFileName = DB_PATH + DB_NAME;
    File dir = new File(DB_PATH);
    if(!dir.exists()){
        dir.mkdir();
    }
    OutputStream mOutput = new FileOutputStream(outFileName);
    byte[] mBuffer = new byte[1024];
    int mLength;
    while ((mLength = mInput.read(mBuffer))>0)
    {
        mOutput.write(mBuffer, 0, mLength);
    }
    mOutput.flush();
    mOutput.close();
    mInput.close();
}

public Cursor getTags() {
    db = this.getReadableDatabase();
    String sql = "SELECT _id, tag from tags where status > 0";
    return db.rawQuery(sql, null);

}

}

public class DBHelper extends SQLiteOpenHelper{

SQLiteDatabase db = null;
Context context = null;

static String packageName = "com.easwareapps.quoter";
private static String DB_PATH = "/data/data/" + packageName + "/databases/";
private static String DB_NAME ="quoter.db";
private static final int VERSION = 1;



@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


}

public DBHelper(Context context) {
    super(context, DB_NAME, null, VERSION);
    try{
        this.context = context;
        createDataBase();
    }catch(Exception e){
        e.printStackTrace();
    }


}

public Cursor getQuotes(int tag, int author){

    db = this.getReadableDatabase();
    String authorFilter = (author == 0)?"":" and author._id=" + author;
    String tagFilter = (tag == 0)?"":" INNER JOIN quotes_tags tag ON tag.quote=quote._id AND tag.tag=" + tag + " ";
    String sql = "SELECT quote.quote, author.author, author._id, quote._id from quotes quote, authors author " +  tagFilter + "where quote.author=author._id and quote.status=1 " + authorFilter;// + " ORDER BY RANDOM()";
    return db.rawQuery(sql, null);

}

public String[] getRandomQuote(){

    db = this.getReadableDatabase();
    String sql = "SELECT quote.quote, author.author, author._id, quote._id from quotes quote, authors author where quote.author=author._id and quote.status=1 ORDER BY RANDOM() LIMIT 1";
    Cursor c = db.rawQuery(sql, null);
    if(c.moveToFirst()) {
        return new String[]{c.getString(1), c.getString(0), c.getString(2), c.getString(3)};
    }else{
        return new String[]{"", "", "", ""};
    }

}

public String[] getQuote(int id){

    db = this.getReadableDatabase();
    String sql = "SELECT quote.quote, author.author, author._id, quote._id from quotes quote, authors author where quote.author=author._id and quote.status=1 and quote._id=" + id;
    Cursor c = db.rawQuery(sql, null);
    if(c.moveToFirst()) {
        return new String[]{c.getString(1), c.getString(0), c.getString(2), c.getString(3)};
    }else{
        return new String[]{"", "", "", ""};
    }

}





public void createDataBase() throws IOException {

    boolean mDataBaseExist = checkDataBase();
    if(!mDataBaseExist) {
        try  {
            copyDataBase();
            Log.e("DB", "createDatabase database created");
        }
        catch (IOException mIOException)  {
            Log.d("Error", Log.getStackTraceString(mIOException));
            throw new Error("ErrorCopyingDataBase");
        }
    }
}

private boolean checkDataBase() {
    File dbFile = new File(DB_PATH + DB_NAME);
    return dbFile.exists();
}

private void copyDataBase() throws IOException {
    InputStream mInput = context.getAssets().open(DB_NAME);
    String outFileName = DB_PATH + DB_NAME;
    File dir = new File(DB_PATH);
    if(!dir.exists()){
        dir.mkdir();
    }
    OutputStream mOutput = new FileOutputStream(outFileName);
    byte[] mBuffer = new byte[1024];
    int mLength;
    while ((mLength = mInput.read(mBuffer))>0)
    {
        mOutput.write(mBuffer, 0, mLength);
    }
    mOutput.flush();
    mOutput.close();
    mInput.close();
}

public Cursor getTags() {
    db = this.getReadableDatabase();
    String sql = "SELECT _id, tag from tags where status > 0";
    return db.rawQuery(sql, null);

}

}

public class QuoterActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {





private static String BANERID ="ca-app-pub-5013563814074355/3472037827";
QuotesAdapter qa;
RecyclerView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quoter);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);



    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    //navigationView.addView();

    lv = (RecyclerView)findViewById(R.id.quotesList);
    lv.setLayoutManager(new LinearLayoutManager(this));

    DBHelper dbh = new DBHelper(getApplicationContext());
    Cursor tags = dbh.getTags();

    int i = 0;
    final Menu menu = navigationView.getMenu();
    menu.add(R.id.tags, i, i, "All");

    if(tags.moveToFirst()) {
        do {
            i++;
            menu.add(R.id.tags, tags.getInt(0), i, tags.getString(1));
        }while (tags.moveToNext());
    }

    qa = new QuotesAdapter(getApplicationContext(),
            new DBHelper(getApplicationContext()).getQuotes(0, 0), this);
    lv.setAdapter(qa);


    menu.setGroupCheckable(R.id.tags, true, true);
    int count = 0;
    for (i = 0, count = navigationView.getChildCount(); i < count; i++) {
        final View child = navigationView.getChildAt(i);
        if (child != null && child instanceof ListView) {
            final ListView menuView = (ListView) child;
            final HeaderViewListAdapter adapter = (HeaderViewListAdapter) menuView.getAdapter();
            final BaseAdapter wrapped = (BaseAdapter) adapter.getWrappedAdapter();
            wrapped.notifyDataSetChanged();
        }
    }



    new EANotificationManager().setAlarmIfNeeded(getApplicationContext());







}



@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        saveScrollPositon();
        super.onBackPressed();
    }
}

@Override
public void onPause() {
    saveScrollPositon();
    super.onPause();
}

@Override
public void onResume() {

    super.onResume();
    scrollToLastPosition();

}

private void scrollToLastPosition(){
    SharedPreferences pref = getSharedPreferences(getPackageName(), MODE_PRIVATE);
    int y = pref.getInt("scroll-y", 0);
    if(lv != null ){
        //lv.smoothScrollToPosition(y);
        lv.scrollToPosition(y);
    }
}

private void saveScrollPositon(){
    if(lv != null ){
        int y = ((LinearLayoutManager)lv.getLayoutManager()).
                findFirstCompletelyVisibleItemPosition();
        SharedPreferences pref = getSharedPreferences(getPackageName(), MODE_PRIVATE);
        SharedPreferences.Editor edit = pref.edit();
        edit.putInt("scroll-y", y);
        edit.commit();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.quoter, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        Intent settings = new Intent(this, SettingsActivity.class);
        startActivity(settings);
        return true;
    }if (id == R.id.random) {
        Intent random = new Intent(this, DailyQuoteActivity.class);
        random.putExtra("from_quote", true);
        startActivity(random);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    lv.setAdapter(null);
    qa = new QuotesAdapter(getApplicationContext(),
            new DBHelper(getApplicationContext()).getQuotes(id, 0), this);
    lv.setAdapter(qa);
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.getMenu().getItem(id+1).setChecked(true);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

public void gotoWebsite(View v){
    String url = "http://quoter.easwareapps.com";
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    startActivity(i);
}

}

0 个答案:

没有答案