问题描述
我正在尝试在Mainactivity之外使用ContentResolver。有没有没有空指针异常的访问方式
ImageFragment.kt扩展了Appcompatactivity()
Val uri=contentResolver.insert(MediaStore.images.Media.EXTERNAL_CONTENT_URI,value)
编辑
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,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,Bit.width,Bit.height,newMat,true)
}
}
MainActivity.kt
val obj=ImageFragment(this)
我尝试将Main上下文传递给此类,但不起作用 我不知道为什么会这样,因为空闲状态向我显示了没有作用域的内容解析器。
谢谢
解决方法
使用MainActivity“ context”访问另一个类中的contentResolver。
如果您正在使用适配器类,则
context.getContentResolver();
和片段
getActivity.getContentResolver();