Я получаю ошибку android.database.sqlite.SQLiteException: нет такой таблицы в Android Studio - PullRequest
0 голосов
/ 29 ноября 2018

Я пытаюсь получить данные из своей базы данных SQLite в папке ресурсов, но получаю ошибку Caused by: android.database.sqlite.SQLiteException: no such table: Product (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM product.Я сделал правильную копию базы данных и проверил, существует ли база данных, и также база данных открывается, но каждый раз показывает эту ошибку.Я также добавил разрешение WRITE_EXTERNAL_STORAGE в AndroidManifest.xml.

Как мне решить эту проблему?

enter image description here

DatabaseSql.java

public class DatabaseSql extends SQLiteOpenHelper {
    public static final String DBNAME = "sample.sqlite";
    public static final String DBLOCATION = "/data/data/com.flag.flags/databases/";
    private Context mContext;
    private SQLiteDatabase mDatabase;

    public DatabaseSql(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 List<TL_Model> getListProduct() {
        TL_Model product = null;
        List<TL_Model> productList = new ArrayList<>();
        openDatabase();
        Cursor cursor = mDatabase.rawQuery("SELECT * FROM Product", null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            product = new TL_Model(cursor.getInt(0), cursor.getString(1), cursor.getInt(2), cursor.getString(3));
            productList.add(product);
            cursor.moveToNext();
        }
        cursor.close();
        closeDatabase();
        return productList;
    }
}

MainActivity.java

public class TouchLearnActivity extends AppCompatActivity {
    private ImageView imgBackToMain;
    RecyclerView recyclerView_tl;
    LinearLayoutManager linearLayoutManager;
    List<TL_Model> info_list;
    TL_Model model;
    private DatabaseSql mDatabase;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_touch_learn);
        initViews();
        doClicks();

    }

    private void doClicks() {
        imgBackToMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                startActivity(new Intent(TouchLearnActivity.this,MainActivity.class));
                overridePendingTransition(R.anim.slide_toleft,R.anim.slide_outright);
            }
        });


    }

    private void initViews() {
        mDatabase = new DatabaseSql(this);
        checkdbisexists();
        imgBackToMain = findViewById(R.id.imgbacktomaintl);
        recyclerView_tl = findViewById(R.id.recyclertl);
        recyclerView_tl.setLayoutManager(new GridLayoutManager(this,2));
        info_list = mDatabase.getListProduct();
        GetDataOfTL adapter = new GetDataOfTL(this,info_list);
        recyclerView_tl.setAdapter(adapter);
    }

    private void checkdbisexists() {
        File database = getApplicationContext().getDatabasePath(DatabaseSql.DBNAME);
        if(false == database.exists()){
            mDatabase.getReadableDatabase();
                Log.i("result","Database exists");
            if(CopyDb(this)){
                Log.i("result","copy database successfuly");
            }else{
                Log.i("result","copy database failed");
                return;
            }
        }
    }

    private boolean CopyDb(Context context){
        try {
            InputStream inputStream = context.getAssets().open(DatabaseSql.DBNAME);
            String outfilename = DatabaseSql.DBLOCATION + DatabaseSql.DBNAME;
            OutputStream outputStream = new FileOutputStream(outfilename);
            byte[] buff = new byte[1024];
            int lenght = 0;
            while ((lenght = inputStream.read(buff)) > 0){
                outputStream.write(buff,0,lenght);
            }
            outputStream.flush();
            outputStream.close();
            Log.d("result","DB copied");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("result","DB copy failed" + e.getMessage());
            return false;
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_toright,R.anim.slide_outleft);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...