https://developer.android.com/training/camera/photobasics
I tried to follow this link for capturing an image through camera and storing it in the internal storage of mobile.
But whenever I click on capture button, the application gets crash. I have changed manifest and made an xml file for path of file too. I am new to android development so please try to explain step by step if possible.
I am attaching the code here:
class MainActivity : AppCompatActivity() {
var REQUEST_IMAGE_CAPTURE = 1
lateinit var image: ImageView
lateinit var currentPhotoPath: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
image = findViewById(R.id.image)
}
fun onClickingCapture(view: View) {
//createImageFile()
dispatchTakePictureIntent(this)
// galleryAddPic()
}
// private fun dispatchTakePictureIntent() {
//
// val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
// try {
// startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
// } catch (e: ActivityNotFoundException) {
// // display error state to the user
// }
// }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
val imageBitmap = data?.extras?.get("data") as Bitmap
image.setImageBitmap(imageBitmap)
//saveImage(this,imageBitmap,"Try","jpeg")
}
}
private fun dispatchTakePictureIntent(mainActivity: MainActivity) {
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
// Ensure that there's a camera activity to handle the intent
takePictureIntent.resolveActivity(mainActivity.packageManager)?.also {
// Create the File where the photo should go
val photoFile: File? = try {
createImageFile()
} catch (ex: IOException) {
null
}
// Continue only if the File was successfully created
photoFile?.also {
val photoURI: Uri = FileProvider.getUriForFile(
this,
"com.example.android.fileprovider",
it
)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(takePictureIntent, mainActivity.REQUEST_IMAGE_CAPTURE)
}
}
}
}
@Throws(IOException::class)
fun createImageFile(): File {
// Create an image file name
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
"JPEG_${timeStamp}_",
".jpg",
storageDir
).apply {
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = absolutePath
}
}
// private fun galleryAddPic() {
// Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE).also { mediaScanIntent ->
// val f = File(currentPhotoPath)
// mediaScanIntent.data = Uri.fromFile(f)
// sendBroadcast(mediaScanIntent)
// }
// }
fun saveImage(context: Context, bitmap: Bitmap, name: String, extension: String) {
var name = name
name = "$name.$extension"
val fileOutputStream: FileOutputStream
try {
fileOutputStream = context.openFileOutput(name, Context.MODE_PRIVATE)
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fileOutputStream)
fileOutputStream.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
This is manifest:
<?xml version="1.0" encoding="utf-8"?>
<uses-feature android:name="android.hardware.camera"
android:required="true" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<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/Theme.JpegToPdf">
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
This is file_path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="my_images" path="Android/data/com.example.jpegtopdf/files/Pictures" />
</paths>
This is the exception shown in my logcat when I capture the image and expected to go back to the main activity.
Process: com.example.jpegtopdf, PID: 25424
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.jpegtopdf/com.example.jpegtopdf.MainActivity}: java.lang.NullPointerException: null cannot be cast to non-null type android.graphics.Bitmap
at android.app.ActivityThread.deliverResults(ActivityThread.java:5202)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5243)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:100)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2239)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:227)
at android.app.ActivityThread.main(ActivityThread.java:7822)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1026)
Caused by: java.lang.NullPointerException: null cannot be cast to non-null type android.graphics.Bitmap
at com.example.jpegtopdf.MainActivity.onActivityResult(MainActivity.kt:53)
at android.app.Activity.dispatchActivityResult(Activity.java:8303)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5195)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5243)?
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)?
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)?
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:100)?
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2239)?
at android.os.Handler.dispatchMessage(Handler.java:107)?
at android.os.Looper.loop(Looper.java:227)?
at android.app.ActivityThread.main(ActivityThread.java:7822)?
at java.lang.reflect.Method.invoke(Native Method)?
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)?
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1026)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…