skip to Main Content

I have a cartActivity and when I click the proceed button it goes to PaymentActivity. Now, If I click baack button from the paymentActivity I want to go back to the CartActivity.

CartActivity

class CartActivity : AppCompatActivity() {

lateinit var toolbar: androidx.appcompat.widget.Toolbar
lateinit var txtOrderingFrom: TextView
lateinit var btnPlaceOrder: Button
lateinit var recyclerView: RecyclerView
lateinit var layoutManager: RecyclerView.LayoutManager
lateinit var menuAdapter: CartAdapter
lateinit var restaurantId: String
lateinit var restaurantName: String
lateinit var selectedItemsId: ArrayList<String>
lateinit var linearLayout: LinearLayout
lateinit var cartProgressLayout: RelativeLayout

var totalAmount = 0
var cartListItems = arrayListOf<CartItems>()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_cart)

    btnPlaceOrder = findViewById(R.id.btnPlaceOrder)
    txtOrderingFrom = findViewById(R.id.txtOrderingFrom)
    linearLayout = findViewById(R.id.linearLayout)
    toolbar = findViewById(R.id.toolBar)
    cartProgressLayout = findViewById(R.id.cartProgressLayout)

    restaurantId = intent.getStringExtra("restaurantId").toString()
    restaurantName = intent.getStringExtra("restaurantName").toString()
    selectedItemsId = intent.getStringArrayListExtra("selectedItemsId") as ArrayList<String>
    txtOrderingFrom.text = restaurantName

    setToolBar()
    fetchData()

    btnPlaceOrder.setOnClickListener {



        val sharedPreferences = this.getSharedPreferences(
            getString(R.string.shared_preferences),
            Context.MODE_PRIVATE
        )

        if (ConnectionManager().checkConnectivity(this)) {

            cartProgressLayout.visibility = View.VISIBLE
            try {
                val foodArray = JSONArray()

                for (foodItem in selectedItemsId) {
                    val singleItemObject = JSONObject()
                    singleItemObject.put("food_item_id", foodItem)
                    foodArray.put(singleItemObject)
                }

                val sendOrder = JSONObject()
                sendOrder.put("user_id", sharedPreferences.getString("user_id", "0"))
                sendOrder.put("restaurant_id", restaurantId)
                sendOrder.put("total_cost", totalAmount)
                sendOrder.put("food", foodArray)

                val queue = Volley.newRequestQueue(this)
                val url = "http://13.235.250.119/v2/place_order/fetch_result"

                val jsonObjectRequest = object : JsonObjectRequest(
                    Method.POST,
                    url,
                    sendOrder,
                    Response.Listener {

                        val response = it.getJSONObject("data")
                        val success = response.getBoolean("success")
                        val LAUNCH_SECOND_ACTIVITY = 1
                        if (success) {
                            val intent = Intent(this, PaymentActivity::class.java)
                            intent.putExtra("total_amount",totalAmount)
                            startActivityForResult(intent,LAUNCH_SECOND_ACTIVITY)
                            finishAffinity()

                        } else {
                            val responseMessageServer =
                                response.getString("errorMessage")
                            Toast.makeText(
                                this,
                                responseMessageServer.toString(),
                                Toast.LENGTH_SHORT
                            ).show()

                        }
                        cartProgressLayout.visibility = View.INVISIBLE
                    },
                    Response.ErrorListener {

                        Toast.makeText(
                            this,
                            "Some Error occurred!!!",
                            Toast.LENGTH_SHORT
                        ).show()
                    }) {
                    override fun getHeaders(): MutableMap<String, String> {
                        val headers = HashMap<String, String>()
                        headers["Content-type"] = "application/json"
                        headers["token"] = "9bf534118365f1"
                        return headers
                    }
                }
                queue.add(jsonObjectRequest)

            } catch (e: JSONException) {
                Toast.makeText(
                    this,
                    "Some unexpected error occurred!!",
                    Toast.LENGTH_SHORT
                ).show()
            }

        } else {

            val alterDialog = androidx.appcompat.app.AlertDialog.Builder(this)
            alterDialog.setTitle("No Internet")
            alterDialog.setMessage("Check Internet Connection!")
            alterDialog.setPositiveButton("Open Settings") { _, _ ->
                val settingsIntent = Intent(Settings.ACTION_SETTINGS)
                startActivity(settingsIntent)
            }
            alterDialog.setNegativeButton("Exit") { _, _ ->
                finishAffinity()
            }
            alterDialog.setCancelable(false)
            alterDialog.create()
            alterDialog.show()
        }
    }

    layoutManager = LinearLayoutManager(this)
    recyclerView = findViewById(R.id.recyclerViewCart)

}

fun fetchData() {

    if (ConnectionManager().checkConnectivity(this)) {

        cartProgressLayout.visibility = View.VISIBLE

        try {
            val queue = Volley.newRequestQueue(this)
            val url = "http://13.235.250.119/v2/restaurants/fetch_result/$restaurantId"

            val jsonObjectRequest = @SuppressLint("SetTextI18n")
            object : JsonObjectRequest(
                Method.GET,
                url,
                null,
                Response.Listener {

                    val response = it.getJSONObject("data")
                    val success = response.getBoolean("success")
                    if (success) {

                        val data = response.getJSONArray("data")
                        cartListItems.clear()
                        totalAmount = 0

                        for (i in 0 until data.length()) {
                            val cartItem = data.getJSONObject(i)
                            if (selectedItemsId.contains(cartItem.getString("id"))) {
                                val menuObject = CartItems(
                                    cartItem.getString("id"),
                                    cartItem.getString("name"),
                                    cartItem.getString("cost_for_one"),
                                    cartItem.getString("restaurant_id")
                                )

                                totalAmount += cartItem.getString("cost_for_one").toString()
                                    .toInt()
                                cartListItems.add(menuObject)


                            }
                            menuAdapter = CartAdapter(this, cartListItems)
                            recyclerView.adapter = menuAdapter
                            recyclerView.layoutManager = layoutManager
                        }

                        btnPlaceOrder.text = "Place Order(Total: Rs. $totalAmount)"

                    }
                    cartProgressLayout.visibility = View.INVISIBLE
                },
                Response.ErrorListener {

                    Toast.makeText(
                        this,
                        "Some Error occurred!!!",
                        Toast.LENGTH_SHORT
                    ).show()

                    cartProgressLayout.visibility = View.INVISIBLE
                }) {
                override fun getHeaders(): MutableMap<String, String> {
                    val headers = HashMap<String, String>()
                    headers["Content-type"] = "application/json"
                    headers["token"] = "26c5144c5b9c13"
                    return headers
                }
            }

            queue.add(jsonObjectRequest)

        } catch (e: JSONException) {
            Toast.makeText(
                this,
                "Some Unexpected error occurred!!!",
                Toast.LENGTH_SHORT
            ).show()
        }

    } else {

        val alterDialog = androidx.appcompat.app.AlertDialog.Builder(this)
        alterDialog.setTitle("No Internet")
        alterDialog.setMessage("Check Internet Connection!")
        alterDialog.setPositiveButton("Open Settings") { _, _ ->
            val settingsIntent = Intent(Settings.ACTION_SETTINGS)
            startActivity(settingsIntent)
        }
        alterDialog.setNegativeButton("Exit") { _, _ ->
            finishAffinity()
        }
        alterDialog.setCancelable(false)
        alterDialog.create()
        alterDialog.show()
    }
}

fun setToolBar() {
    setSupportActionBar(toolbar)
    supportActionBar?.title = "My Cart"
    supportActionBar?.setHomeButtonEnabled(true)
    supportActionBar?.setDisplayHomeAsUpEnabled(true)
    supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_back_arrow)
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {

    when (item.itemId) {
        android.R.id.home -> {
            super.onBackPressed()
        }
    }
    return super.onOptionsItemSelected(item)
}

}

PaymentActivity

 class PaymentActivity : AppCompatActivity() {
    var amountEt: TextView? = null
    var nameEt: TextView? = null
    var upiIdEt: TextView? = null
    var send: Button? = null
    val UPI_PAYMENT = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_payment)
        initializeViews()
        send?.setOnClickListener {
            payUsingUpi("1", "sruthikrithika0@okhdfcbank", "Sruthi")
            }

    }

    fun initializeViews() {
        send = findViewById(R.id.send)
        amountEt = findViewById(R.id.amount_et)
        nameEt = findViewById(R.id.upi_name)
        upiIdEt = findViewById(R.id.upi_id)
    }

    fun payUsingUpi(amount: String?, upiId: String?, name: String?) {
        val uri: Uri = Uri.parse("upi://pay").buildUpon()
            .appendQueryParameter("pa", upiId)
            .appendQueryParameter("pn", name)
            .appendQueryParameter("am", amount)
            .appendQueryParameter("cu", "INR")
            .build()
        val upiPayIntent = Intent(Intent.ACTION_VIEW)
        upiPayIntent.data = uri

        // will always show a dialog to user to choose an app
        val chooser = Intent.createChooser(upiPayIntent, "Pay with")

        // check if intent resolves
        if (null != chooser.resolveActivity(packageManager)) {
            startActivityForResult(chooser, UPI_PAYMENT)
        } else {
            Toast.makeText(
                this@PaymentActivity,
                "No UPI app found, please install one to continue",
                Toast.LENGTH_SHORT
            ).show()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            UPI_PAYMENT -> if (RESULT_OK == resultCode || resultCode == 11) {
                if (data != null) {
                    val trxt = data.getStringExtra("response")
                    Log.d("UPI", "onActivityResult: $trxt")
                    val dataList: ArrayList<String?> = ArrayList()
                    dataList.add(trxt)
                    upiPaymentDataOperation(dataList)
                } else {
                    Log.d("UPI", "onActivityResult: " + "Return data is null")
                    val dataList: ArrayList<String?> = ArrayList()
                    dataList.add("nothing")
                    upiPaymentDataOperation(dataList)
                }
            } else {
                Log.d(
                    "UPI",
                    "onActivityResult: " + "Return data is null"
                ) //when user simply back without payment
                val dataList: ArrayList<String?> = ArrayList()
                dataList.add("nothing")
                upiPaymentDataOperation(dataList)
            }
        }
    }

    private fun upiPaymentDataOperation(data: ArrayList<String?>) {
        if (isConnectionAvailable(this@PaymentActivity)) {
            var str = data[0]
            Log.d("UPIPAY", "upiPaymentDataOperation: $str")
            var paymentCancel = ""
            if (str == null) str = "discard"
            var status = ""
            var approvalRefNo = ""
            val response = str.split("&").toTypedArray()
            for (i in response.indices) {
                val equalStr = response[i].split("=").toTypedArray()
                if (equalStr.size >= 2) {
                    if (equalStr[0].toLowerCase() == "Status".toLowerCase()) {
                        status = equalStr[1].toLowerCase()
                    } else if (equalStr[0].toLowerCase() == "ApprovalRefNo".toLowerCase() || equalStr[0].toLowerCase() == "txnRef".toLowerCase()) {
                        approvalRefNo = equalStr[1]
                    }
                } else {
                    paymentCancel = "Payment cancelled by user."
                }
            }
            if (status == "success") {
                //Code to handle successful transaction here.
                Toast.makeText(this@PaymentActivity, "Transaction successful.", Toast.LENGTH_SHORT)
                    .show()
                Log.d("UPI", "responseStr: $approvalRefNo")
            } else if ("Payment cancelled by user." == paymentCancel) {
                Toast.makeText(this@PaymentActivity, "Payment cancelled by user.", Toast.LENGTH_SHORT)
                    .show()
            } else {
                Toast.makeText(
                    this@PaymentActivity,
                    "Transaction failed.Please try again",
                    Toast.LENGTH_SHORT
                ).show()
            }
        } else {
            Toast.makeText(
                this@PaymentActivity,
                "Internet connection is not available. Please check and try again",
                Toast.LENGTH_SHORT
            ).show()
        }
    }

    companion object {
        fun isConnectionAvailable(context: Context): Boolean {
            val connectivityManager =
                context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            if (connectivityManager != null) {
                val netInfo = connectivityManager.activeNetworkInfo
                if (netInfo != null && netInfo.isConnected
                    && netInfo.isConnectedOrConnecting
                    && netInfo.isAvailable
                ) {
                    return true
                }
            }
            return false
        }
    }

}

Now, when I click back button from PaymentActivity the app crashes because the same state in the cartActivity is not present.How to resolve this ??

Manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.foodly">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:hardwareAccelerated="true"
        android:icon="@drawable/logo"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:resizeableActivity="false"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Foodly">
        <activity android:name=".activity.OrderPlacedActivity"></activity>
        <activity android:name=".activity.CartActivity" />
        <activity android:name=".activity.OrderHistoryActivity" />
        <activity
            android:name=".activity.RestaurantMenuActivity" />
        <activity
            android:name=".activity.RegisterActivity" />
        <activity
            android:name=".activity.LoginActivity" />
        <activity
            android:name=".activity.PaymentActivity"/>
        <activity
            android:name=".activity.SplashActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activity.MainActivity" />

        <meta-data
            android:name="preloaded_fonts"
            android:resource="@array/preloaded_fonts" />

    </application>

</manifest>

2

Answers


  1. Why do you call startActivity() in your OnBackPressed() callback ? You don’t have to, it’s automatic. If you need to retrieve parameters in the CartActivity, you have to launch the PaymentActivity with startActivityForResult()

    Login or Signup to reply.
  2. Problem is with the

    finishAffinity()

    finishAffinity() is used to remove a number of Activitys belonging to a specific application from the current task (which may contain Activitys belonging to multiple applications).

    You shouldn’t be doing any finish on starting payment activity. you should be using finishAffinity() after payment success so the last activities should not come on back press.

    For more info – https://developer.android.com/reference/android/app/Activity#finishAffinity()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search