change the toolbar menu in android when the recycle view items are longClicked

342 Views Asked by At

I have implemented a recycle view and add images to the view by the camera. It is working fine. Now what i am going to do is, when the user long clicks on a recycle view item change the toolbar menu. I am getting the following error.

   Process: com.example.fyp_patient, PID: 8797
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
        at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:164)
        at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
        at android.content.Context.obtainStyledAttributes(Context.java:677)
        at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
        at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
        at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
        at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
        at com.example.fyp_patient.MainActivity._$_findCachedViewById(Unknown Source:25)
        at com.example.fyp_patient.MainActivity.onLongClick(ImageRecycleViewActivity.kt:237)
        at android.view.View.performLongClickInternal(View.java:7444)
        at android.view.View.performLongClick(View.java:7392)
        at android.view.View.performLongClick(View.java:7410)
        at android.view.View$CheckForLongPress.run(View.java:27811)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7188)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)

My code is as follow.

ImageRecycleViewActivity.kt


    var isInActionMode = false
    private val uriArrayList = ArrayList<Uri>()
    private val arrayList = ArrayList<Model>()
    private var driveServiceHelper: DriveServiceHelper? = null
    private var RC_AUTHORIZE_DRIVE = 101
    private val REQUEST_IMAGE_CAPTURE: Int = 100
    private var image_uri: Uri? = null
    private val IMAGE_CAPTURE_CODE: Int = 101
    private var ACCESS_DRIVE_SCOPE = Scope(Scopes.DRIVE_FILE)
    private var SCOPE_EMAIL = Scope(Scopes.EMAIL)
    lateinit var googleDriveService: Drive
    var mDriveServiceHelper: DriveServiceHelper? = null
    var adapter = Adapter(arrayList,this)


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_imagerecycleview)
        setSupportActionBar(toolbar as Toolbar?)
        updateView()
        counter_text.visibility = View.GONE

        btn.setOnClickListener {
            checkForGooglePermissions()
            createFolderInDrive()
        }
        fab.setOnClickListener {
            getPermission()
        }

    }
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        val inflater: MenuInflater = menuInflater
        inflater.inflate(R.menu.main, menu)
        return true
    }


    /***********get the permission from the device to access the camera***********/
    private fun getPermission() {
        //if the system is marshmallow or above get the run time permission
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED ||
                checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED
            ) {
                //permission was not enabled
                val permission = arrayOf(
                    android.Manifest.permission.CAMERA,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
                //show popup to request permission
                requestPermissions(permission, REQUEST_IMAGE_CAPTURE)
            } else {
                //permission already granted
                openCamera()
            }
        } else {
            //system os < marshmallow
            openCamera()
        }
    }

    /************open the device camera*************/
    private fun openCamera() {
        val values = ContentValues()
        values.put(MediaStore.Images.Media.TITLE, "New Picture")
        values.put(MediaStore.Images.Media.DESCRIPTION, "this is an images")
        image_uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)

        //camera Intent
        val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri)
        startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE)
    }

    /*************call when user clicks on the permission request dialog********************/
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        //called when user allow or deny from permission request
        when (requestCode) {
            REQUEST_IMAGE_CAPTURE -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //permission from pop up was granted
                    openCamera()
                } else {
                    //permission from pop up was denied
                    Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    /************called when an image is captured*************/
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //called when image is captured from camera intent
        if (resultCode == Activity.RESULT_OK) {
            //set the image to the image view
            image_uri?.let { uriArrayList.add(it) }
            arrayList.add((image_uri?.let { Model("My title", "My description", it) }!!))
            Log.i("check123", image_uri.toString())
            updateView()
        }
    }

    private fun updateView() {
        val adapter = Adapter(arrayList, this)
        recycleView.layoutManager = LinearLayoutManager(this)
        recycleView.adapter = adapter
    }


    override fun onLongClick(view: View?): Boolean {
        Log.i("clicktest","clicked")
        toolbar.menu.clear()
        toolbar.inflateMenu(R.menu.menu_action_mode)
        counter_text.visibility=View.VISIBLE
        isInActionMode=true
        adapter.notifyDataSetChanged()
        ActionBar.DISPLAY_HOME_AS_UP
        return true
    }
}

Adapter.kt


class Adapter(val arrayList: ArrayList<Model>,val context:Context) :
    RecyclerView.Adapter<Adapter.ViewHolder>() {

    class ViewHolder (itemView : View) : RecyclerView.ViewHolder(itemView){

        fun bindItems (model: Model){
            itemView.title.text = model.title
            itemView.description.text = model.des
            itemView.imageIv.setImageURI(model.uri)

        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.image_list_item, parent, false)
        return ViewHolder(v)
    }

    override fun getItemCount(): Int {
        return arrayList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bindItems(arrayList[position])

        if (!MainActivity().isInActionMode){
            holder.itemView.checkbox.visibility=View.GONE
        }else {
            holder.itemView.checkbox.visibility=View.VISIBLE
        }

        holder.itemView.setOnLongClickListener(MainActivity())
    }

}

Error occurs from this line toolbar.menu.clear() Please help me

0

There are 0 best solutions below