3

I'm trying to finish an activity from another (android) with kotlin. I know the wat to do it with java is with the following code (https://stackoverflow.com/a/10379275/7280257)

at the first activity:

BroadcastReceiver broadcast_reciever = new BroadcastReceiver() {

    @Override
    public void onReceive(Context arg0, Intent intent) {
        String action = intent.getAction();
        if (action.equals("finish_activity")) {
            finish();
            // DO WHATEVER YOU WANT.
        }
    }
};
registerReceiver(broadcast_reciever, new IntentFilter("finish_activity"));

On the other activity:

Intent intent = new Intent("finish_activity");
sendBroadcast(intent);

For some reason converting the java activity to kotlin doesn't give a valid output, if someone could give me the correct syntax to do it properly with kotlin I will appreciate it

kotlin output (first activity) [OK]:

val broadcast_reciever = object : BroadcastReceiver() {

    override fun onReceive(arg0: Context, intent: Intent) {
        val action = intent.action
        if (action == "finish_activity") {
            finish()
            // DO WHATEVER YOU WANT.
        }
    }
}
registerReceiver(broadcast_reciever, IntentFilter("finish_activity"))

kotlin output (2nd activity) [OK]

            val intent = Intent("finish_activity")
            sendBroadcast(intent)

ERROR: https://i.stack.imgur.com/OJvSY.png

FIX: THE CODE SHOWN IS RIGHT, YOU JUST NEED TO PLACE IT INSIDE THE onCreate FUNCTION

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
quiquelhappy
  • 396
  • 2
  • 6
  • 16

2 Answers2

5

Simple code to finish a particular activity from another:

class SplashActivity : AppCompatActivity(), NavigationListner {

  class MyClass{
    companion object{
        var activity: Activity? = null
    }
  }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    MyClass.activity = this@SplashActivity
  }


  override fun navigateFromScreen() {
    val intent = Intent(this,LoginActivity::class.java)
    startActivity(intent)
  }
}

Now call SplashActivity.MyClass.activity?.finish() from another activity to finish above activity.

Marco
  • 120
  • 1
  • 12
Ashish Tyagi
  • 81
  • 1
  • 5
1

The error Expecting member declaration is there because you wrote a statement (the function call) inside a class. In that scope, declarations (functions, inner classes) are expected.

You have to place your statements inside functions (and then call those from somewhere) in order for them to be executed.

zsmb13
  • 85,752
  • 11
  • 221
  • 226