android .database.sqlite.SQLiteCantOpenDatabaseException: неизвестная ошибка (код 14 SQLITE_CANTOPEN): не удалось открыть базу данных - PullRequest
0 голосов
/ 13 марта 2020

Я читал на сайте разные об этой проблеме, но я не могу понять это. Я застрял этот шаг так долго. Как я могу исправить эту проблему

Выход Logcat

в соответствии с logcat, это вызвано SQLiteCantOpenDatabaseException

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test123/com.example.test123.Cart}: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14 SQLITE_CANTOPEN): Could not open database
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3304)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3443)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2040)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:224)
    at android.app.ActivityThread.main(ActivityThread.java:7520)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
 Caused by: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14 SQLITE_CANTOPEN): Could not open database
    at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
    at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:215)
    at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:197)
    at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:505)
    at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:206)
    at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:198)
    at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:915)
    at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:895)
    at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:786)
    at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:733)
    at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getReadableDatabase(SQLiteAssetHelper.java:264)
    at Database.Database.getCarts(Database.java:24)
    at com.example.test123.Cart.loadListFood(Cart.java:58)
    at com.example.test123.Cart.onCreate(Cart.java:54)
    at android.app.Activity.performCreate(Activity.java:7894)
    at android.app.Activity.performCreate(Activity.java:7881)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3279)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3443) 
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2040) 
    at android.os.Handler.dispatchMessage(Handler.java:107) 
    at android.os.Looper.loop(Looper.java:224) 
    at android.app.ActivityThread.main(ActivityThread.java:7520) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 

База данных. java

public class Database extends SQLiteAssetHelper {
private static final String DB_NAME="QODB.db";
private static  final int DB_ver=1;
public Database(Context context) {
    super(context, DB_NAME,null,DB_ver);
}

public List<Order> getCarts()
{
    SQLiteDatabase db = getReadableDatabase();
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    String[] sqlSelect={"ProductName","ProductId","Quantity","Price","Discount"};
    String sqlTable="OrderDetail";

    qb.setTables(sqlTable);
    Cursor c = qb.query(db,sqlSelect,null,null,null,null,null);

    final List<Order> result = new ArrayList<>();
    if (c.moveToFirst())
    {
        do{
            result.add(new Order(c.getString(c.getColumnIndex("ProductId")),
                    c.getString(c.getColumnIndex("ProductName")),
                    c.getString(c.getColumnIndex("Quantity")),
                    c.getString(c.getColumnIndex("Price")),
                    c.getString(c.getColumnIndex("Discount"))
            ));

        }while (c.moveToNext());
    }
    return result;
}

public  void  addToCart(Order order)
{
    SQLiteDatabase db = getReadableDatabase();
    String query = String.format("INSERT INTO OrderDetail(ProductId,ProductName,Quantity,Price,Discount) VALUES('%s','%s','%s','%s','%s');",
            order.getProductId(),
            order.getProductName(),
            order.getQuantity(),
            order.getPrice(),
            order.getDiscount());
    db.execSQL(query);

}

public  void  cleanCart(Order order)
{
    SQLiteDatabase db = getReadableDatabase();
    String query = String.format("DELETE FROM orderDetail");
    db.execSQL(query);
}

Корзина. java

public class Cart extends AppCompatActivity {

RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;

FirebaseDatabase database;
DatabaseReference request;
TextView txtTotalPrice;
FButton btnPlace;

List<Order> cart = new ArrayList<>();
CartAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cart);

    //Firebase
    database = FirebaseDatabase.getInstance();
    request=database.getReference("Requests");

    //Init
    recyclerView = (RecyclerView)findViewById(R.id.listCart);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);

    txtTotalPrice = (TextView)findViewById(R.id.total);
    btnPlace = (FButton)findViewById(R.id.btnPlaceOrde);

    loadListFood();
}

private void loadListFood() {
    cart = new Database(this).getCarts();
    adapter = new CartAdapter(cart,this);
    recyclerView.setAdapter(adapter);

    //Calculate total price
    int total =0;
    for(Order order:cart)
        total+=(Integer.parseInt(order.getPrice()))*(Integer.parseInt(order.getQuantity()));

    Locale locale = new Locale("en","US");
    NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);

    txtTotalPrice.setText(fmt.format(total));
}

AndroidManifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test123">

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity android:name=".Cart"></activity>
    <activity android:name=".FoodDetail" />
    <activity android:name=".FoodList" />
    <activity
        android:name=".Home"
        android:label="@string/title_activity_home"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity android:name=".SignUp" />
    <activity android:name=".SignIn" />
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

и ошибка в Database.Database.getCarts (База данных. java: 24): SQLiteDatabase db = getReadableDatabase ();

ошибка в com.example.test123.Cart.loadListFood (Cart. java: 58) is cart = new База данных (this) .getCarts ();

ошибка в com.example.test123.Cart.onCreate (Cart. java: 54) is loadListFood ();

1 Ответ

0 голосов
/ 13 марта 2020

Откройте файл AndroidManifest.xml и добавьте указанное ниже разрешение в тег манифеста (который должен быть тегом верхнего уровня).

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...