How to call recreate from another class in Kotlin?

190 Views Asked by At

How do I call recreate() from another class in Kotlin? I am used to Java and did it like in the code shown below for some UI changes.

public class MainActivity extends AppCompatActivity {

    private static MainActivity instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        instance = this;
    }

    public static MainActivity getInstance() {
        return instance;
    }
}

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }

    private void onClick(View view) {
        MainActivity.getInstance().recreate();
    }
}

Would be great if somebody knows how to achieve that in Kotlin, I am pretty much stuck with this. Beste regards, Markus

2

There are 2 best solutions below

0
Rahul Rawat On BEST ANSWER

What @broot answered above is right for a 1:1 port but the practice is entirely wrong. What you are doing here is essentially creating a strong reference to an activity that isn't even shown to a user anymore.

What you should do however is something like the following:-

Inside Second Activity

 val intent = Intent(BROADCAST_RECREATE_MAIN)
 LocalBroadcastManager.getInstance(this@ SecondActivity).sendBroadcast(intent)

Inside Main Activity

private val localBroadcastReceiver by lazy {
  object : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
      \\Recreate main here
    }
  }
}

Inside MainActivity's onCreate

val intentFilter = IntentFilter()
intentFilter.addAction(BROADCAST_RECREATE_MAIN)
LocalBroadcastManager.getInstance(context)
        .registerReceiver(localBroadcastReceiver, localBroadcastIntentFilter)

And inside onDestroy

LocalBroadcastManager.getInstance(requireContext())
        .unregisterReceiver(localBroadcastReceiver)

   
2
broot On

A 1:1 port to Kotlin would be something like:

class MainActivity {
    protected fun onCreate() {
        instance = this
    }

    companion object {
        lateinit var instance : MainActivity
    }
}

class SecondActivity {
    private fun onClick() {
        MainActivity.instance.recreate()
    }
}

But it really looks like a bad idea. You should use one of available ways to communicate between activities, not recreate it like this. I guess this is not what you asked though :-)