android – Finish an activity when onBackPressed

So, I want to make a simple app with a flow like this: MainActivity with a list of picture posted by different users -> user click FAB to post picture, move to AddPicture activity with intent -> AddPicture Activity, filled the required form, and then startActivity with intent to get back to Main -> MainActivity with a fresh new list and new story listed up top -> onBackPressed clicked, return to Home Screen of the smartphone

But, my app didn’t work like I intended. This is how my App work: MainActivity with a list of picture posted by different users -> user click FAB to post picture, move to AddPicture activity with intent -> AddPicture Activity, filled the required form, and then startActivity with intent to get back to Main -> MainActivity with a fresh new list and new story listed up top -> onBackPressed -> Main Activity with previous list of picture -> onBackPressed again -> return to Home Screen

To sum it up, my MainActivity got called instead of HomeScreen when onBackPressed clicked after user post a story. So I have to clicked onBackPressed twice to get back to HomeScreen. Do you guys know how to fix this?

Here’s my MainActivity:

class MainActivity : AppCompatActivity() {
    private lateinit var bind: ActivityMainBinding
    private lateinit var storyAdapter: StoryAdapter
    private val timelineStoryViewModel: TimelineStoryViewModel by viewModels {
        val context = this@MainActivity
        val pref =
            context.getSharedPreferences(R.string.token_pref.toString(), Context.MODE_PRIVATE)
        val token = pref.getString(R.string.token.toString(), "")!!
        ViewModelFactory(this, token)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bind = ActivityMainBinding.inflate(layoutInflater)
        setContentView(bind.root)
        showLoadingProcess(true)
        displayStories()
        bind.floatingActionButton.setOnClickListener {
            val intent = Intent(this, AddStoryActivity::class.java)
            startActivity(intent)
        }
        supportActionBar?.setTitle(R.string.app_name)
    }

    override fun onBackPressed() {
        super.onBackPressed()
        val intent = Intent(this, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        finish()
    }

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

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.app_bar_settings -> {
                val context = this
                val pref = context.getSharedPreferences(
                    R.string.token_pref.toString(),
                    Context.MODE_PRIVATE
                )
                val editor = pref.edit()
                editor.remove(R.string.token.toString())
                editor.remove(getString(R.string.email))
                editor.remove(getString(R.string.password))
                editor.apply()
                startActivity(Intent(this, LoginActivity::class.java))
                finish()
            }
            R.id.app_bar_maps -> {
                startActivity(Intent(this, MapsActivity::class.java))
            }
        }
        return super.onOptionsItemSelected(item)
    }

    private fun displayStories() {
        showLoadingProcess(false)
        storyAdapter = StoryAdapter()
        bind.storyRV.layoutManager = LinearLayoutManager(this)
        bind.storyRV.adapter = storyAdapter.withLoadStateFooter(
            footer = LoadingStateAdapter {
                storyAdapter.retry()
            }
        )
        timelineStoryViewModel.story.observe(this) { story ->
            storyAdapter.submitData(lifecycle, story)

        }
        storyAdapter.setOnProfileCallback(object : StoryAdapter.OnProfileCallback {
            override fun onProfileClicked(data: ListStoryItem) {
                chosenProfile(data)
            }
        })
    }

    private fun chosenProfile(story: ListStoryItem) {
        val name: TextView = findViewById(R.id.userName)
        val storyPict: ImageView = findViewById(R.id.userImageStory)
        val optionsCompat: ActivityOptionsCompat =
            ActivityOptionsCompat.makeSceneTransitionAnimation(
                this,
                Pair(storyPict, getString(R.string.imageStoryDetail)),
                Pair(name, getString(R.string.nama_pengguna)),
            )
        val sendData = Intent(this, StoryDetailActivity::class.java)
        sendData.putExtra(StoryDetailActivity.EXTRA_STORY, story)
        startActivity(sendData, optionsCompat.toBundle())
        Toast.makeText(this, "Memuat Story " + story.name, Toast.LENGTH_SHORT).show()
    }

    private fun showLoadingProcess(isLoading: Boolean) {
        if (isLoading) {
            bind.loading.visibility = View.VISIBLE
        } else {
            bind.loading.visibility = View.GONE
        }
    }
}

AddStoryActivity:

class AddStoryActivity : AppCompatActivity() {
    private lateinit var bind: ActivityAddStoryBinding
    private val utils = Utils()

    private var getFile: File? = null
    val context = this@AddStoryActivity
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CODE_PERMISSIONS) {
            if (!allPermissionsGranted()) {
                Toast.makeText(
                    this,
                    "Tidak mendapatkan permission.",
                    Toast.LENGTH_SHORT
                ).show()
                finish()
            }
        }
    }

    private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all {
        ContextCompat.checkSelfPermission(baseContext, it) == PackageManager.PERMISSION_GRANTED
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bind = ActivityAddStoryBinding.inflate(layoutInflater)
        setContentView(bind.root)

        if (!allPermissionsGranted()) {
            ActivityCompat.requestPermissions(
                this,
                REQUIRED_PERMISSIONS,
                REQUEST_CODE_PERMISSIONS
            )
        }
        showLoadingProcess(false)
        bind.cameraXButton.setOnClickListener { startCameraX() }
        bind.galleryButton.setOnClickListener { startGallery() }
        bind.uploadButton.setOnClickListener { uploadImage() }
    }

    private fun startGallery() {
        val intent = Intent()
        intent.action = ACTION_GET_CONTENT
        intent.type = "image/*"
        val chooser = Intent.createChooser(intent, "Choose a Picture")
        launcherIntentGallery.launch(chooser)
    }

    private fun startCameraX() {
        val intent = Intent(this, CameraActivity::class.java)
        launcherIntentCameraX.launch(intent)
    }

    private val launcherIntentCameraX = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) {
        if (it.resultCode == CAMERA_X_RESULT) {
            val myFile = it.data?.getSerializableExtra("picture") as File
            val isBackCamera = it.data?.getBooleanExtra("isBackCamera", true) as Boolean

            getFile = myFile
            val result = utils.rotateBitmap(
                BitmapFactory.decodeFile(getFile?.path),
                isBackCamera
            )

            bind.previewImage.setImageBitmap(result)
        }
    }

    private val launcherIntentGallery = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == RESULT_OK) {
            val selectedImg: Uri = result.data?.data as Uri

            val myFile = utils.uriToFile(selectedImg, this@AddStoryActivity)

            getFile = myFile

            bind.previewImage.setImageURI(selectedImg)
        }
    }

    private fun uploadImage() {
        val pref =
            context.getSharedPreferences(R.string.token_pref.toString(), Context.MODE_PRIVATE)
        val token = pref.getString(R.string.token.toString(), "")!!
        Log.d("TokenStory", token)
        if (getFile != null) {
            val file = utils.reduceFileImage(getFile as File)
            val desc = findViewById<EditText>(R.id.imageDesc)
            val description = desc.text.toString().toRequestBody("text/plain".toMediaType())
            val requestImageFile = file.asRequestBody("image/jpeg".toMediaTypeOrNull())
            val imageMultipart: MultipartBody.Part = MultipartBody.Part.createFormData(
                "photo",
                file.name,
                requestImageFile
            )

            val client = APIConfig.getAPIServices()
                .postStories("Bearer ${token}", imageMultipart, description)

            client.enqueue(object : Callback<AddNewStoryResponse> {
                override fun onResponse(
                    call: Call<AddNewStoryResponse>,
                    response: Response<AddNewStoryResponse>
                ) {
                    if (response.isSuccessful) {
                        val responseBody = response.body()
                        Log.d("ResBodyStory", responseBody.toString())
                        if (responseBody != null && !responseBody.error) {
                            Toast.makeText(
                                this@AddStoryActivity,
                                responseBody.message,
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                        startActivity(Intent(this@AddStoryActivity, MainActivity::class.java))
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                        finish()
                    } else {
                        Toast.makeText(
                            this@AddStoryActivity,
                            response.message(),
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }

                override fun onFailure(call: Call<AddNewStoryResponse>, t: Throwable) {
                    Toast.makeText(
                        this@AddStoryActivity,
                        "Gagal instance Retrofit",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            })
        } else {
            Toast.makeText(
                this@AddStoryActivity,
                "Silakan masukkan berkas gambar terlebih dahulu.",
                Toast.LENGTH_SHORT
            ).show()
        }
        showLoadingProcess(true)
    }

    private fun showLoadingProcess(isLoading: Boolean) {
        if (isLoading) {
            bind.loading.visibility = View.VISIBLE
        } else {
            bind.loading.visibility = View.GONE
        }
    }

    companion object {
        const val CAMERA_X_RESULT = 200

        private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA)
        private const val REQUEST_CODE_PERMISSIONS = 10
    }


}

Leave a Comment