Не удалось открыть базу данных sqlite, указанный каталог или файл базы данных не существует - PullRequest
0 голосов
/ 01 ноября 2019

Я пытаюсь добавить информацию в свою базу данных, используя sqlite. Я добавил файл базы данных Order.db в свой каталог ресурсов, но все еще получаю эту ошибку. Я немного новичок в программировании.

      #################################################################
Error Code : 1294 (SQLITE_CANTOPEN_ENOENT)
Caused By : Specified directory or database file does not exist.
    (unknown error (code 1294): Could not open database)
#################################################################
    com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getReadableDatabase(SQLiteAssetHelper.java:264)
    at com.urbanx.urbaninsure.Database.Database.addToCart(Database.java:64)
    at com.urbanx.urbaninsure.ProposalForm1.onClick(ProposalForm1.java:723)
    at android.view.View.performClick(View.java:5076)
    at android.view.View$PerformClick.run(View.java:20279)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5910)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)

ниже является частью класса Proposal. Я не смог опубликовать весь код. Когда я нажимаю кнопку bSubmit, я получаю ошибку при попытке доступа к базе данных.

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.bSubimt:
            fillProposalForm();

            new Database(getBaseContext()).addToCart(new Order(
                    currentProposer.getFirstNameProposer(),
                    currentProposer.getSurnameProposer(),
                    currentProposer.getLastNameProposer(),
                    currentProposer.getMobile(),
                    currentProposer.getIdNumber(),
                    currentProposer.getDuration(),
                    currentProposer.getVehicleReg(),
                    currentProposer.getTotalPremium()));

            startActivity(new Intent(ProposalForm1.this, Cart.class));



            break;


        case R.id.bOwnershipAttachCert:


            break;




        case R.id.cbWindscreen:

            if (cbWindscreen.isChecked()) {
                etLimitWindscreen.setVisibility(View.VISIBLE);
            }else {
                etLimitWindscreen.setVisibility(View.GONE);
            }
            break;


        case R.id.cbDvd:

            if (cbDvd.isChecked()) {
                etLimitDvd.setVisibility(View.VISIBLE);
            }else {
                etLimitDvd.setVisibility(View.GONE);
            }
            break;


        case R.id.cbRiot:

            if (cbRiot.isChecked()) {
                etLimitRiot.setVisibility(View.VISIBLE);
            }
            else {
                etLimitRiot.setVisibility(View.GONE);
            }
            break;

        case R.id.cbExcessProtect:

            if (cbExcessProtect.isChecked()) {
                etLimitExcessProtect.setVisibility(View.VISIBLE);
            }
            else {
                etLimitExcessProtect.setVisibility(View.GONE);
            }
            break;

        case R.id.cbTerrorism:

            if (cbTerrorism.isChecked()) {
                etLimitTerrorism.setVisibility(View.VISIBLE);
            }
            else {
                etLimitTerrorism.setVisibility(View.GONE);
            }
            break;

        case R.id.cbCourtesyCar:

            if (cbCourtesyCar.isChecked()){
                etCourtesyCar.setVisibility(View.VISIBLE);
            }
            else {
                etCourtesyCar.setVisibility(View.GONE);
            }
            break;



    }

}

private void fillProposalForm() {


    if (etFirstNameOfProposer.getText().toString().isEmpty()){
        etFirstNameOfProposer.setError("First name cannot be empty");
    } else if (etSurnameProposer.getText().toString().isEmpty()){
        etSurnameProposer.setError("Surname cannot be empty");
    } else if (etLastNameProposer.getText().toString().isEmpty()){
        etLastNameProposer.setError("Last name cannot be empty");
    } else if (etPassportNo.getText().toString().isEmpty()){
        etPassportNo.setError("ID/Passport number cannot be empty");
    } else if (etPinNo.getText().toString().isEmpty()){
        etPinNo.setError("KRA pin number cannot be empty");

    }else if (etMobile.getText().toString().isEmpty()){
        etMobile.setError("Mobile number cannot be empty");
    }else if (etEmail.getText().toString().isEmpty()){
        etEmail.setError("Email cannot be empty");


    } else if (etDrivingTime.getText().toString().isEmpty()){
        etDrivingTime.setError("Driving time duration cannot be empty");

    } else if (etDuration.getText().toString().isEmpty()) {
        etDuration.setError("Duraion of insurance cannot be empty");

    } else if (etVehicelReg.getText().toString().isEmpty()){
        etVehicelReg.setError("Vehicle registration cannot be empty");

    } else if (etEstimate.getText().toString().isEmpty()) {
        etEstimate.setError("The present estimated value of vehicle cannot be empty");


    } else if (!Patterns.EMAIL_ADDRESS.matcher(etEmail.getText().toString()).matches()){
        etEmail.setError("Invalid email address");
    }


     firstNameProposer = etFirstNameOfProposer.getText().toString();
     lastNameProposer = etLastNameProposer.getText().toString();
     surnameProposer = etSurnameProposer.getText().toString();
     idNumber = etPassportNo.getText().toString();
     pinNo = etPinNo.getText().toString();
     email = etEmail.getText().toString();
     mobile = etMobile.getText().toString();
     drivingTime = etDrivingTime.getText().toString();

     duration = etDuration.getText().toString();


     vehicleReg  = etVehicelReg.getText().toString();

    marketValue = etEstimate.getText().toString();
    if (marketValue == null || marketValue.isEmpty()){
        marketValue.equals("0.0");
    }


    spTypeOfCoverage.setAdapter(TypeOfCoverageAdapter);
    spTypeOfCoverage.setOnItemSelectedListener(new 
        AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, 
      long id) {
             typeOfCoverage = 
       spTypeOfCoverage.getItemAtPosition(position).toString();

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });


    spMake.setAdapter(MakeAdapter);
    spMake.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, 
       long id) {
            if (i == 0) {

                vehicleMake = spMake.getItemAtPosition(position).toString();


               //                    vehicleModelLayout.setVisibility(View.GONE);
               //                    otherMakeRow.setVisibility(View.GONE);
              //                    otherModelRow.setVisibility(View.GONE);
            } else if (i == 1) {
                spModel.setAdapter(subaruCarsAdapter);

                vehicleMake = spMake.getItemAtPosition(position).toString();

             //                    vehicleModelLayout.setVisibility(View.VISIBLE);
             //                    otherMakeRow.setVisibility(View.GONE);
            //                    otherModelRow.setVisibility(View.GONE);
            } else if (i == 2) {
                spModel.setAdapter(toyotaCarsAdapter);

                vehicleMake = spMake.getItemAtPosition(position).toString();

            //                    vehicleModelLayout.setVisibility(View.VISIBLE);
            //                    otherMakeRow.setVisibility(View.GONE);
            //                    otherModelRow.setVisibility(View.GONE);
            } else if (i == 3) {
                spModel.setAdapter(nissanCarsAdapter);

                vehicleMake = spMake.getItemAtPosition(position).toString();

             //                    vehicleModelLayout.setVisibility(View.VISIBLE);
             //                    otherMakeRow.setVisibility(View.GONE);
              //                    otherModelRow.setVisibility(View.GONE);
            } else if (i == 4) {
                spModel.setAdapter(mercedesBenzCarsAdapter);

                vehicleMake = spMake.getItemAtPosition(position).toString();

             //                    vehicleModelLayout.setVisibility(View.VISIBLE);
              //                    otherMakeRow.setVisibility(View.GONE);
             //                    otherModelRow.setVisibility(View.GONE);
            } else if (i == 5) {
                spModel.setAdapter(BMWCarsAdapter);

                vehicleMake = spMake.getItemAtPosition(position).toString();

             //                    vehicleModelLayout.setVisibility(View.VISIBLE);
             //                    otherMakeRow.setVisibility(View.GONE);
              //                    otherModelRow.setVisibility(View.GONE);
            } else if (i == 6) {
                spModel.setAdapter(audiCarsAdapter);
             //                    vehicleModelLayout.setVisibility(View.VISIBLE);
                vehicleMake = spMake.getItemAtPosition(position).toString();

            //                    otherMakeRow.setVisibility(View.GONE);
             //                    otherModelRow.setVisibility(View.GONE);
            } else if (i == 7) {
                spModel.setAdapter(landRoverCarsAdapter);
             //                    vehicleModelLayout.setVisibility(View.VISIBLE);
             //                    otherMakeRow.setVisibility(View.GONE);
                vehicleMake = spMake.getItemAtPosition(position).toString();

               //                    otherModelRow.setVisibility(View.GONE);
            } else if (i == 8) {
                spModel.setAdapter(hondaCarsAdapter);
             //                    vehicleModelLayout.setVisibility(View.VISIBLE);

                vehicleMake = spMake.getItemAtPosition(position).toString();

             //                    otherMakeRow.setVisibility(View.GONE);
               //                    otherModelRow.setVisibility(View.GONE);
            } else if (i == 9) {
                spModel.setAdapter(mazdaCarsAdapter);
              //                    vehicleModelLayout.setVisibility(View.VISIBLE);
             //                    otherMakeRow.setVisibility(View.GONE);
                vehicleMake = spMake.getItemAtPosition(position).toString();

            //                    otherModelRow.setVisibility(View.GONE);
            } else if (i == 10) {
                spModel.setAdapter(mitsubishiCarsAdapter);
              //                    vehicleModelLayout.setVisibility(View.VISIBLE);
             //                    otherMakeRow.setVisibility(View.GONE);
                vehicleMake = spMake.getItemAtPosition(position).toString();

            //                    otherModelRow.setVisibility(View.GONE);
            } else if (i == 11) {
                spModel.setAdapter(peugeotCarsAdapter);
            //                    vehicleModelLayout.setVisibility(View.VISIBLE);
            //                    otherMakeRow.setVisibility(View.GONE);
                vehicleMake = spMake.getItemAtPosition(position).toString();

             //                    otherModelRow.setVisibility(View.GONE);
            } else if (i == 12) {
                spModel.setAdapter(isuzuCarsAdapter);
            //                    vehicleModelLayout.setVisibility(View.VISIBLE);
            //                    otherMakeRow.setVisibility(View.GONE);
                vehicleMake = spMake.getItemAtPosition(position).toString();

            //                    otherModelRow.setVisibility(View.GONE);
            } else if (i == 13) {
                spModel.setAdapter(volkswagenCarsAdapter);
            //                    vehicleModelLayout.setVisibility(View.VISIBLE);
             //                    otherMakeRow.setVisibility(View.GONE);
                vehicleMake = spMake.getItemAtPosition(position).toString();

           //                    otherModelRow.setVisibility(View.GONE);
            } else {
           //                    vehicleModelLayout.setVisibility(View.GONE);
           //                    otherMakeRow.setVisibility(View.VISIBLE);
                vehicleMake = spMake.getItemAtPosition(position).toString();

          //                    otherModelRow.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
    spUseOfVehicle.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            useOfVehicle= (String) parent.getItemAtPosition(position);

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });



    spModel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (spModel.getSelectedItem().toString().contains("Other")) {
                 vehicleModel = spModel.getSelectedItem().toString();


        //                    otherModelRow.setVisibility(View.VISIBLE);
            } else {
        //                    otherModelRow.setVisibility(View.GONE);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    spinnerModelYear.setAdapter(yearAdapter);
    spinnerModelYear.setOnItemSelectedListener(new 
      AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, 
      long id) {
            yearOfManf = spinnerModelYear.getSelectedItem().toString();

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
     if (etLimitWindscreen.getText().toString().isEmpty()){
     }
    windscreenValue = etLimitWindscreen.getText().toString();


    if (etLimitDvd.getText().toString().isEmpty()){
    }

    dvd = etLimitDvd.getText().toString();

    if ( etLimitRiot.getText().toString().isEmpty()){
    }


    riot = etLimitRiot.getText().toString();


    if ( etLimitExcessProtect.getText().toString().isEmpty()){
    }
    excessProtector = etLimitExcessProtect.getText().toString();




    if (etLimitTerrorism.getText().toString().isEmpty()){
    }
    terrorism = etLimitTerrorism.getText().toString();


    if (etCourtesyCar.getText().toString().isEmpty()){
    }
    courtesyCar = etCourtesyCar.getText().toString();


    calculateInsurance();



    currentProposer = new ProposalDetails( firstNameProposer
            ,lastNameProposer,surnameProposer, idNumber, pinNo,
            email, mobile, drivingTime, duration, vehicleReg,
            marketValue, typeOfCoverage, useOfVehicle, vehicleMake, vehicleModel,
            yearOfManf, windscreenValue, dvd, riot,
            excessProtector, terrorism, courtesyCar, basicPremium, trainingLevy,
            policyHolders, stampDuty, totalPremium);
    String proposalId = mProposalInformation.push().getKey();
    currentProposer.setInsuranceNo(proposalId);











    mProposalInformation.child(FirebaseAuth.getInstance().getCurrentUser()
    .getUid()).child(proposalId).setValue(currentProposer);








    final AlertDialog waitingDialog = new SpotsDialog(ProposalForm1.this,"Loading",R.style.Custom);
    waitingDialog.show();



    startActivity(new Intent(ProposalForm1.this,Cart.class));

}


private void chooseImage() {

    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture:"), Common.PICK_IMAGE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == Common.PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK
            && data != null && data.getData() != null) {
        imagelogbookUri = data.getData();

        if (imagelogbookUri != null){
            final ProgressDialog mDialog = new ProgressDialog(this);
            mDialog.setMessage("Uploading...");
            mDialog.show();

            String imageName = UUID.randomUUID().toString(); //random name image upload
            final StorageReference imageFolder = storageReference.child("images/" + imageName);
            imageFolder.putFile(imagelogbookUri)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            mDialog.dismiss();

                            imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {

                                    //update this url to be avatar property of of User
                                    //First you need avatr property on user model

                                    Map<String, Object> avatarUpdate = new HashMap<>();
                                    avatarUpdate.put("LogBook",uri.toString());

                                    DatabaseReference driverInformation = FirebaseDatabase.getInstance().getReference(Common.customer_tbl);
                                    driverInformation.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                                            .updateChildren(avatarUpdate)
                                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                                @Override
                                                public void onComplete(@NonNull Task<Void> task) {
                                                    if (task.isSuccessful())
                                                        Toast.makeText(ProposalForm1.this, "Uploaded!", Toast.LENGTH_SHORT).show();
                                                    else
                                                        Toast.makeText(ProposalForm1.this, "Upload error !", Toast.LENGTH_SHORT).show();

                                                }
                                            });
                                }
                            });

                        }
                    }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                    double progress = (100.0* taskSnapshot.getBytesTransferred()/ taskSnapshot.getTotalByteCount());
                    mDialog.setMessage("Uploaded" + progress + "%");

                }
            });


        }

    }
}


    }

Это мой класс базы данных

  public class Database extends SQLiteAssetHelper {

private static final String DB_NAME = "Order.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 = {  " firstNameProposer","surnameProposer","lastNameProposer","phone"
    ,"idNumber","duration","vehicleReg", "totalPremium"};
    String sqlTable = "OrderDetail";

    qb.setTables(sqlTable);

    Cursor c = qb.query(db,sqlselect,null,null,null,null,null,null,null);

    final List<Order> result = new ArrayList<>();
    if (c.moveToFirst())
    {
        do {
            result.add(new Order(
                    c.getString(c.getColumnIndex("firstNameProposer")),
                     c.getString(c.getColumnIndex("surnameProposer")),
                     c.getString(c.getColumnIndex("lastNameProposer")),
                     c.getString(c.getColumnIndex("phone")),
                     c.getString(c.getColumnIndex("idNumber")),
                    c.getString(c.getColumnIndex("duration")),
                    c.getString(c.getColumnIndex("vehicleReg")),
                    c.getString(c.getColumnIndex("totalPremium"))));
        }while (c.moveToNext());
    }return result;

}

public void cleanCart()
{
    SQLiteDatabase db = getReadableDatabase();
    String query = String.format("DELETE FROM OrderDetail");

    db.execSQL(query);
}
public void addToCart(Order order)
{
    SQLiteDatabase db = getReadableDatabase();
    String query = String.format("INSERT INTO OrderDetail (  firstNameProposer,surnameProposer,lastNameProposer,phone" +
                    "idNumber,duration,vehicleReg, totalPremium )VALUES('%s','%s','%s','%s','%s','%s','%s','%s');",
            order.getFirstNameProposer(),
            order.getSurnameProposer(),
            order.getLastNameProposer(),
            order.getMobile(),
            order.getIdNumber(),
            order.getDuration(),
            order.getVehicleReg(),
            order.getTotalPremium());

    db.execSQL(query);
}


   }

1 Ответ

0 голосов
/ 02 ноября 2019

Я добавил файл базы данных Order.db в свой каталог ресурсов, но все еще получаю эту ошибку. Я немного новичок в программировании.

Вам необходимо добавить файл базы данных Order.db в активы / базы данных каталог (после создания каталога) в соответствии с: -

SQLiteAssetHelper опирается на соглашения об именах файлов и папок .

Ваша папка ресурсов будет либо находиться в корневом каталоге вашего проекта, либо в каталоге src / main, если вы используете структуру проекта gradle по умолчанию. Как минимум, вы должны предоставить следующие :

  • A базы данных папка внутри ресурсов
  • База данных SQLite внутри папки баз данных, чей файлимя соответствует имени базы данных, которое вы указываете в коде (включая расширение файла, если оно есть)

Android SQLiteAssetHelper

...