尝试检索图像时,获取类未找到异常以及无法解码流异常

时间:2018-09-30 07:39:58

标签: android kotlin

尝试单击摄像机中的图像或从目录中获取图像时,出现类未找到异常。该代码在kotlin中,并在下面给出。 该类实现了捕获图像或从图库中拾取图像的功能。 实现了_openCamera()和openFileSelector()方法。
这样做的主要目的是捕获图像并将其上传到服务器中,但是所实现的方法不能给出正确的结果。

class MainActivity : AppCompatActivity() {
    private var drawerResult: Drawer? = null
    private var jobschedular: JobScheduler? = null
    private var jobschedularCode: Int = 1
    private var phoneNumber: String? = null
    private var toolbar: Toolbar? = null
    private var familyId: String? = null

    val TAG: String? = "Activity_Name"
    val REQUEST_IMAGE_CAPTURE = 1
    val REQUEST_CODE_FOR_GALLERY_CAPTURE = 2
    var photoFile: File? = null
    var progressDialog: Dialog? = null
    private var doubleBackToExitPressedOnce = false

    @SuppressLint("PrivateResource")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out)

        Log.d(TAG, "Inside MainActivity")
        //onclick listener for open camera
        onclickListenerForOpenCamera()


        //starting the services here  . .
        val service_checkAddedtoFamily = Intent(this, checkAddedToFamily::class.java)
        startService(service_checkAddedtoFamily)
        val service_checkDocsToBeVerified = Intent(this, checkDocsToBeVerified::class.java)
        startService(service_checkDocsToBeVerified)

        /*findViewById<Button>(R.id.scan).setOnClickListener {
            val i = Intent(this, Testers::class.java)
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            i.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            startActivity(i)
            overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
        }*/

        //onclick listener for select image button
        attach_onclick_listener_to_add_photos_from_gallery()

        //onclick listener for select pdf files
        onclickListenerForSelectPdfFile()
        //get toolbar for drawer
        toolbar = findViewById(R.id.toolbar_tabs)

        //get phone number
        val loginInfo = applicationContext.getSharedPreferences("loginInfo", Context.MODE_PRIVATE)
        phoneNumber = loginInfo.getString("phoneNumber", "")

        //onclick listener for upload button
        //onclickListenerForUploadButton()

        //onclick listener for retrieve button
        onclickListenerForRetrieveButton()

        //on click permanent diseases button
        //onclickPermanentDiseasesButtton()

        //navigation drawer
        left_drawer(this, this@MainActivity, toolbar!!).createNavigationDrawer()

        //verify auto upload
        verifyAutoLoginInformation()

        //create Sqlite database
        DB_HELPER(this@MainActivity).writableDatabase

        //get job schedular service
        jobschedular = applicationContext.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
        schedulTheJobForHealthGoals()
        schedulTheJobForHealthInsurance()
        setPreferencesForNutrition()
        schedulTheJobForNutrition()
        schedulTheJobForSyncNutritionOnline()

    }

    /*override fun onBackPressed() {
        if (doubleBackToExitPressedOnce) {
            super.onBackPressed()
            return
        }
        this.doubleBackToExitPressedOnce = true
        Toast.makeText(this, "Press back again to exit", Toast.LENGTH_SHORT).show()
        Handler().postDelayed(Runnable { doubleBackToExitPressedOnce = false }, 2000)
    }*/

    //job schedular
    fun schedulTheJobForHealthGoals() {
        val builder = JobInfo.Builder(jobschedularCode, ComponentName(this@MainActivity, health_goals_services::class.java))
                .setPersisted(true)
                .setPeriodic(5000)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
                .setRequiresCharging(false)
                .setRequiresDeviceIdle(false)

        val bundle = PersistableBundle()
        bundle.putString("key", "value")
        builder.setExtras(bundle)

        val s_response = jobschedular!!.schedule(builder.build())
        if (s_response <= 0) {
            //something goes wrong
        }
    }

    fun schedulTheJobForHealthInsurance() {
        val builder = JobInfo.Builder(jobschedularCode, ComponentName(this@MainActivity, health_insurance_service::class.java))
                .setPersisted(true)
                .setPeriodic(5000)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
                .setRequiresCharging(false)
                .setRequiresDeviceIdle(false)

        val bundle = PersistableBundle()
        bundle.putString("key", "value")
        builder.setExtras(bundle)

        val s_response = jobschedular!!.schedule(builder.build())
        if (s_response <= 0) {
            //something goes wrong
        }
    }

    fun schedulTheJobForNutrition() {
        val builder = JobInfo.Builder(jobschedularCode, ComponentName(this@MainActivity, nutrition_service::class.java))
                .setPersisted(true)
                .setPeriodic(5000) //change to 1 hour
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
                .setRequiresCharging(false)
                .setRequiresDeviceIdle(false)

        val bundle = PersistableBundle()
        bundle.putString("key", "value")
        builder.setExtras(bundle)

        val s_response = jobschedular!!.schedule(builder.build())
        if (s_response <= 0) {
            //something goes wrong
        }
    }

    fun setPreferencesForNutrition() {
        val nutritionInfo = getSharedPreferences("nutrition", Context.MODE_PRIVATE)
        val editor = nutritionInfo.edit()
        editor.putString("breakFastTime_Hour", "7")
        editor.putString("lunchTime_Hour", "14") //TODO: change to 13
        editor.putString("DinnerTime_Hour", "20")
        editor.apply()
    }

    fun schedulTheJobForSyncNutritionOnline() {
        val builder = JobInfo.Builder(jobschedularCode, ComponentName(this@MainActivity, sync_nutrition_online::class.java))
                .setPersisted(true)
                .setPeriodic(5000)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
                .setRequiresCharging(false)
                .setRequiresDeviceIdle(false)

        val bundle = PersistableBundle()
        bundle.putString("key", "value")
        builder.setExtras(bundle)

        val s_response = jobschedular!!.schedule(builder.build())
        if (s_response <= 0) {
            //something goes wrong
        }
    }

    //buttons on home screen
    /*fun onclickListenerForUploadButton(){
        findViewById<ImageView>(R.id.uploadButton).setOnClickListener{
            openModeOfUploadActivity()
        }
    }*/
    fun onclickListenerForRetrieveButton() {
        findViewById<Button>(R.id.retrieveButton).setOnClickListener {
            openHistoryActivity()
        }
    }

    /*fun onclickPermanentDiseasesButtton(){
        findViewById<Button>(R.id.permanentDiseasesButton).setOnClickListener{
            openPermanentDiseases()
        }
    }*/
    /*fun openModeOfUploadActivity(){
        val intent = Intent(this,MainActivity::class.java)
        startActivity(intent)
    }*/
    fun openHistoryActivity() {
        val intent = Intent(this, history_pickFamilyMember::class.java)
        startActivity(intent)
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
    }

    /*fun openPermanentDiseases(){
        val intent = Intent(this,permanentDiseaese::class.java)
        startActivity(intent)
    }
*/
    //verify auto login information
    fun verifyAutoLoginInformation() {
        val loginInfo = applicationContext.getSharedPreferences("loginInfo", Context.MODE_PRIVATE)

        if (loginInfo.contains("familyOrIndividual") == true) {

            //for family
            if (loginInfo.getString("familyOrIndividual", "").toString() == "f") {
                if (loginInfo.contains("phoneNumber") == true && loginInfo.contains("password") == true) {
                    val phoneNumber = loginInfo.getString("phoneNumber", "")
                    val password = loginInfo.getString("password", "")
                    individual_family_login(this@MainActivity).makeFamilyLoginApiRequest(phoneNumber, password)
                } else {
                    left_drawer(this, this@MainActivity, toolbar!!).makeUserLogOut()
                }
            }

            //for individual
            if (loginInfo.getString("familyOrIndividual", "").toString() == "i") {
                if (loginInfo.contains("phoneNumber") == true && loginInfo.contains("password") == true) {
                    val phoneNumber = loginInfo.getString("phoneNumber", "")
                    val password = loginInfo.getString("password", "")
                    individual_family_login(this@MainActivity).makeLoginApiRequest(phoneNumber, password)
                } else {
                    left_drawer(this, this@MainActivity, toolbar!!).makeUserLogOut()
                }
            }

            //for security
            if (loginInfo.getString("familyOrIndividual", "").toString() != "i" && loginInfo.getString("familyOrIndividual", "").toString() != "f") {
                left_drawer(this, this@MainActivity, toolbar!!).makeUserLogOut()
            }

        } else {
            left_drawer(this, this@MainActivity, toolbar!!).makeUserLogOut()
        }
    }


    //camera scan
    fun onclickListenerForOpenCamera() {
        findViewById<ImageView>(R.id.openCamera).setOnClickListener {
            get_permissions_camera()
        }
    }

    fun _openCamera() {
        Log.d("Errors__", "inside _openCamera()")
        try {
            val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                try {
                    photoFile = createImageFile()
                } catch (ex: Exception) {
                    Log.d("Errors__", "inside: " + ex.toString())
                }
                if (photoFile != null) {
                    val builder: StrictMode.VmPolicy.Builder = StrictMode.VmPolicy.Builder()
                    StrictMode.setVmPolicy(builder.build())

                    val photoURI: Uri = Uri.fromFile(photoFile!!)
                    Log.d("Path__", "photoURI: $photoURI")

                    Log.d("Path__", "photoURI.path: " + photoURI.path)
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                    takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
                }
            }
        } catch (e: Exception) {
            Log.d("Errors__", "_openCamera" + e.toString())
        }
    }

    fun createImageFile(): File {
        Log.d("Errors__", "inside createImageFile()")
        val mCurrentPhotoPath: String
        val imageFileName = "camera"
        val storageDir: File = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        val image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        )
        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath()
        Log.d("Path__", "Image: $image")
        return image
    }

    //file selector
    fun onclickListenerForSelectPdfFile() {
        findViewById<ImageView>(R.id.selectPdfFile).setOnClickListener {
            get_permissions_fileExplorer()
        }
    }

    @SuppressLint("SdCardPath")
    fun openFileSelector() {
        val properties = DialogProperties()

        properties.selection_mode = DialogConfigs.MULTI_MODE;
        properties.selection_type = DialogConfigs.FILE_SELECT;
        properties.root = File(DialogConfigs.DEFAULT_DIR);
        properties.error_dir = File(DialogConfigs.DEFAULT_DIR);
        properties.offset = File(DialogConfigs.DEFAULT_DIR);
        properties.extensions = null;

        val dialog: FilePickerDialog = FilePickerDialog(this@MainActivity, properties)
        dialog.setTitle("Select a File")

        dialog.setDialogSelectionListener(object : DialogSelectionListener {
            override fun onSelectedFilePaths(files: Array<out String>?) {
                convertPdfToImages(files!!)
            }
        })

        dialog.show()
    }

    fun convertPdfToImages(files: Array<out String>) {
        showProcessProgress()

        doAsync {
            var uriList: MutableList<Uri>? = mutableListOf()
            val no_of_files = files.size
            var counter = 0

            while (counter < no_of_files) {
                var pdfFile = File(files[counter])

                val decodeService = DecodeServiceBase(PdfContext())
                decodeService.setContentResolver(applicationContext.getContentResolver())
                decodeService.open(Uri.fromFile(pdfFile))
                val pageCount: Int = decodeService.getPageCount()
                var i = 0
                while (i < pageCount) {
                    val page: PdfPage = decodeService.getPage(i) as PdfPage
                    val rectF = RectF(0.toFloat(), 0.toFloat(), 1.toFloat(), 1.toFloat())

                    // do a fit center to 1920x1080
                    val scaleBy = 1
                    val with: Int = (page.getWidth() * scaleBy)
                    val height: Int = (page.getHeight() * scaleBy)

                    val bitmap: Bitmap = page.renderBitmap(with, height, rectF)

                    try {
                        val outputFile = File(applicationContext.externalCacheDir,
                                System.currentTimeMillis().toString() + ".jpg")
                        val outputStream = FileOutputStream(outputFile)

                        // a bit long running
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)

                        uriList!!.add(Uri.fromFile(outputFile))

                        outputStream.close()
                    } catch (e: IOException) {
                    }

                    i++
                }
                counter++
            }
            uiThread {
                progressDialog!!.hide()
                openPreview(uriList!!)
                Log.d("mess", "size: " + uriList.size + " " + uriList.toString())
            }
        }

    }

    //select image
    fun attach_onclick_listener_to_add_photos_from_gallery() {
        findViewById<ImageView>(R.id.selectImage).setOnClickListener {
            get_permissions_gallery()
        }
    }

    fun open_selector() {
        Matisse.from(this)
                .choose(MimeType.allOf())
                .countable(true)
                .maxSelectable(200)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.85f)
                .imageEngine(PicassoEngine())
                .forResult(REQUEST_CODE_FOR_GALLERY_CAPTURE)
    }

    //activity results
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
            var uriOfImage = Uri.fromFile(photoFile)

            Log.d("fileCapturing__", "URI Image: $uriOfImage")
            //start croper
            CropImage.activity(uriOfImage)
                    .start(this)
        }
        if (requestCode == REQUEST_CODE_FOR_GALLERY_CAPTURE && resultCode == Activity.RESULT_OK) {
            var selected_images = Matisse.obtainResult(data)
            openPreview(selected_images!!)
        }

        //for croper
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            val result: CropImage.ActivityResult = CropImage.getActivityResult(data)
            if (resultCode == RESULT_OK) {
                doAsync {
                    val builder: StrictMode.VmPolicy.Builder = StrictMode.VmPolicy.Builder()
                    StrictMode.setVmPolicy(builder.build())
                    var resultUri: Uri = result.getUri()

                    //save cropped image for persisitance
                    val croppedImage = createImageFile() //empty
                    val outputStream = FileOutputStream(croppedImage)
                    // a bit long running
                    (Picasso.with(this@MainActivity)
                            .load(resultUri)
                            .get()
                            ).compress(Bitmap.CompressFormat.JPEG, 100, outputStream)

                    Log.d("fileCapturing__", "outputStream: $outputStream")

                    resultUri = Uri.fromFile(croppedImage)
                    outputStream.close()
                    uiThread {
                        //add to mu list
                        var mu_list = ArrayList<Uri>(1)
                        mu_list.add(resultUri)
                        Log.d("fileCapturing__", "camera uri" + resultUri.toString())
                        openPreview(mu_list)
                    }
                }

            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                val error: Exception = result.getError()
                Log.d("fileCapturing__", "Error: $error")
            }
        }
    }

    //preview
    fun openPreview(list: MutableList<Uri>) {
        val _object = list
        val i = Intent(this, typeOfDocument::class.java)
        val args = Bundle()
        args.putSerializable("ARRAYLIST", _object as java.io.Serializable)
        i.putExtra("BUNDLE", args)
        startActivity(i)

        finish()
    }

    //get permissions
    //Camera
    fun get_permissions_camera() {
        if (ContextCompat.checkSelfPermission(this@MainActivity, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

            MaterialDialog.Builder(this@MainActivity)
                    .title("Camera permission")
                    .content("Camera permissions are required for opening Camera")
                    .negativeText("Cancel")
                    .onNegative(object : MaterialDialog.SingleButtonCallback {
                        override fun onClick(dialog: MaterialDialog, which: DialogAction) {

                        }
                    })
                    .positiveText("Give Permissions")
                    .onPositive(object : MaterialDialog.SingleButtonCallback {
                        override fun onClick(dialog: MaterialDialog, which: DialogAction) {
                            getPermissionsUsingDexter_camera(
                                    android.Manifest.permission.CAMERA
                            )
                        }
                    })
                    .show()

        } else {
            _openCamera()
        }

    }

    fun getPermissionsUsingDexter_camera(permissionString: String) {
        Dexter.withActivity(this)
                .withPermissions(
                        permissionString
                ).withListener(object : MultiplePermissionsListener {
                    override fun onPermissionRationaleShouldBeShown(permissions: MutableList<PermissionRequest>?, token: PermissionToken?) {

                    }

                    override fun onPermissionsChecked(report: MultiplePermissionsReport?) {
                        if (report!!.areAllPermissionsGranted() == true) {
                            _openCamera()

                            Log.d("mess", "permission given")
                        } else {
                            Log.d("mess", "permission not granted")
                        }
                    }
                })
                .check()
    }

    //gallery
    fun get_permissions_gallery() {
        if (ContextCompat.checkSelfPermission(this@MainActivity, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            MaterialDialog.Builder(this@MainActivity)
                    .title("Storage permission")
                    .content("Storage permissions are required for opening the Gallery")
                    .negativeText("Cancel")
                    .onNegative(object : MaterialDialog.SingleButtonCallback {
                        override fun onClick(dialog: MaterialDialog, which: DialogAction) {

                        }
                    })
                    .positiveText("Give Permissions")
                    .onPositive(object : MaterialDialog.SingleButtonCallback {
                        override fun onClick(dialog: MaterialDialog, which: DialogAction) {
                            getPermissionsUsingDexter_gallery(
                                    android.Manifest.permission.READ_EXTERNAL_STORAGE
                            )
                        }
                    })
                    .show()

        } else {
            open_selector()
        }

    }

    fun getPermissionsUsingDexter_gallery(permissionString: String) {
        Dexter.withActivity(this)
                .withPermissions(
                        permissionString
                ).withListener(object : MultiplePermissionsListener {
                    override fun onPermissionRationaleShouldBeShown(permissions: MutableList<PermissionRequest>?, token: PermissionToken?) {

                    }

                    override fun onPermissionsChecked(report: MultiplePermissionsReport?) {
                        if (report!!.areAllPermissionsGranted() == true) {
                            open_selector()

                            Log.d("mess", "permission given")
                        } else {
                            Log.d("mess", "permission not granted")
                        }
                    }
                })
                .check()
    }

    //file exploer
    fun get_permissions_fileExplorer() {
        if (ContextCompat.checkSelfPermission(this@MainActivity, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            MaterialDialog.Builder(this@MainActivity)
                    .title("Storage permission")
                    .content("Storage access permissions are required for opening File Explorer")
                    .negativeText("Cancel")
                    .onNegative(object : MaterialDialog.SingleButtonCallback {
                        override fun onClick(dialog: MaterialDialog, which: DialogAction) {

                        }
                    })
                    .positiveText("Give Permissions")
                    .onPositive(object : MaterialDialog.SingleButtonCallback {
                        override fun onClick(dialog: MaterialDialog, which: DialogAction) {
                            getPermissionsUsingDexter_fileExplores(
                                    android.Manifest.permission.READ_EXTERNAL_STORAGE
                            )
                        }
                    })
                    .show()

        } else {
            openFileSelector()
        }

    }

    fun getPermissionsUsingDexter_fileExplores(permissionString: String) {
        Dexter.withActivity(this)
                .withPermissions(
                        permissionString
                ).withListener(object : MultiplePermissionsListener {
                    override fun onPermissionRationaleShouldBeShown(permissions: MutableList<PermissionRequest>?, token: PermissionToken?) {

                    }

                    override fun onPermissionsChecked(report: MultiplePermissionsReport?) {
                        if (report!!.areAllPermissionsGranted() == true) {
                            openFileSelector()

                            Log.d("mess", "permission given")
                        } else {
                            Log.d("mess", "permission not granted")
                        }
                    }
                })
                .check()
    }

    //progress bar
    fun showProcessProgress() {
        progressDialog = MaterialDialog.Builder(this)
                .title("Please Wait")
                .content("Converting Pdf to Images")
                .progress(true, 0)
                .show()
    }

}

当我尝试单击图像或从库中获取时,显示错误。 使用的提供程序路径如下:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external_files"
        path="." />
</paths>

我尝试将路径更改为“ /”,但没有成功。该错误先前未显示,但现在存在该错误。

这是日志的快照。 log

接受所有建议。提前致谢。

0 个答案:

没有答案