0

I develop an aplication that reads a QR Barcode then parses JSON from the result of the barcode (Using AsyncTask).

If the result is true then the app moves to another activity (I achieve this). But if the result false I want to restart the activity executed before from onPostExecute.

What should I do in my app to restart an activity from onPostExecute?

Here is my code

override fun onPostExecute(result: String?) {
    super.onPostExecute(result)

    // parse json
    val parsJson = JSONObject (result)
    var result = parsJson.get("status")

    if (result == Izin.SUKSES){
        Toast.makeText(context,"Berhasil intent ke activity lain",Toast.LENGTH_LONG).show()
        val intent = Intent(context,MainActivity::class.java)
        context.startActivity(intent)
    }
    else {
        Toast.makeText(context,"Gagal Scan Ulang",Toast.LENGTH_LONG).show()

        // What should i do to restart activity
    }
}

2 Answers2

1

You just need to call recreate on your activity instance-

override fun onPostExecute(result: String?) {
    super.onPostExecute(result)

    ....

    if (result == Izin.SUKSES) {
        ....
    } else {
        activity.recreate()
    }
}

This already has a mention here: Programmatically relaunch/recreate an activity?

Quanta
  • 594
  • 3
  • 24
0

You can Simply use

startActivity(getIntent());
finish();

to refresh an Activity from within itself.

Alternatively you can call recreate() to refresh the activity.

kelvin
  • 1,480
  • 1
  • 14
  • 28