I'm trying to ContentResolver outside Mainactivity . Is there a way to access without null pointer exception
ImageFragment.kt extends Appcompatactivity()
Val uri=contentResolver.insert(MediaStore.images.Media.EXTERNAL_CONTENT_URI,value)
Edit
This line works perfectly inside Mainactivity. I there a way to access outside main class correctly or it should be only inside Mainactivity
class ImageFragment(context:Context) :AppCompatActivity() {
var isImageSaved: Boolean = true
var rot=0
val mainContext = context // updated code
var lensFacing=CameraSelector.LENS_FACING_BACK
fun savingImg(img: Image) {
val ios: OutputStream?
val bit: Bitmap?
var rotBit: Bitmap?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val value = ContentValues()
val filename =
SimpleDateFormat(
FILENAME_FORMAT,
Locale.US
).format(System.currentTimeMillis()) + ".jpg"
value.put(MediaStore.Images.Media.TITLE, filename)
value.put(MediaStore.Images.Media.DISPLAY_NAME, filename)
value.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
value.put(
MediaStore.Images.Media.RELATIVE_PATH,
Environment.DIRECTORY_DCIM + "/" + "Camcorder"
)
val uri = mainContext.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, value)!! // Updated with main context
ios =mainContext.contentResolver.openOutputStream(uri)!!
bit = img.toBitmap()
setThumbnail(uri)
}
ios.close()
img.close()
isImageSaved = true
}
private fun Image.toBitmap():Bitmap{
val yBuffer=planes[0].buffer
val ySize=ByteArray(yBuffer.remaining())
yBuffer.get(ySize)
return BitmapFactory.decodeByteArray(ySize,0,ySize.size,null)
}
private fun setThumbnail(uri: Uri) {
gallery.post {
gallery.setPadding(4)
gallery.load(uri) {
crossfade(true)
transformations(CircleCropTransformation())
}
}
}
private fun rotateBitmap(Bit: Bitmap, angle: Int): Bitmap {
val newMat = Matrix()
if (lensFacing == CameraSelector.LENS_FACING_FRONT) {
newMat.preScale(1F, -1F)
}
newMat.postRotate(angle.toFloat())
return Bitmap.createBitmap(Bit, 0, 0, Bit.width, Bit.height, newMat, true)
}
}
MainActivity.kt
val obj=ImageFragment(this)
I tried passing Main context to this class but doesn't works I don't know why this happens as idle shows me the content resolver which has no scope .
Thank you