John B Gilbert
John B Gilbert

Reputation: 126

Is there a simple way of accessing a function from another Activity in Android Studio

This is a quick question that I hope someone can help me out with. im fairly new to AS and I hope I am not over thinking this, but I'm a big beleiver in studying a topic fully, and have just spent the last few days studying a book in order to find a simple way of acheiving a task;

I am part way through a book and essentially while I read on, in the back of my mind I am trying to do the simple task of calling a function from another activity. I have learned two very lengthy ways to do this:

with the findViewById method: I include a snippet of the app, but in total there were pages and pages of code just to do one tiny task
'''


package com.example.exercise205


import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import com.example.exercise205.RainbowColourPickerActivity

const val PICK_RAINBOW_COLOUR_INTENT = 1
const val RAINBOW_COLOUR_NAME="RAINBOW_COLOUR_NAME"
const val RAINBOW_COLOUR="RAINBOW_COLOUR"
const val DEFAULT_COLOUR="#FFFFFF"
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<Button>(R.id.submit_button).setOnClickListener {

            Intent(this, RainbowColourPickerActivity::class.java)
                .also { rainbowColourPickerIntent ->
                    startActivityForResult(
                        rainbowColourPickerIntent,
                        PICK_RAINBOW_COLOUR_INTENT
                    )
                }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == PICK_RAINBOW_COLOUR_INTENT && resultCode == Activity.RESULT_OK) {

            val backgroundColor =
                data?.getIntExtra(RAINBOW_COLOUR, Color.parseColor(DEFAULT_COLOUR))
                    ?: Color.parseColor(
                        DEFAULT_COLOUR
                    )
            val colorName = data?.getStringExtra(RAINBOW_COLOUR_NAME) ?: ""
            val colorMessage = getString(R.string.colour_chosen_message, colorName)
            val rainbowColor = findViewById<TextView>(R.id.rainbow_color)

            rainbowColor.setBackgroundColor(ContextCompat.getColor(this, backgroundColor))
            rainbowColor.text = colorMessage
            rainbowColor.isVisible = true
        }
    }
}
'''
with a view model, using the 'Factory' method by far this seems more effective with less code and I am glad its been implemented into AS, but I still cant help but feel there is a quicker route. Am I missing something?
'''
class MainActivityViewModelFactory(private val startingTotal : Int) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(MainActivityViewModel::class.java)){
            return MainActivityViewModel(startingTotal) as T
        }
        throw IllegalArgumentException("Unknown View Model Class")
    }
}
'''

Can I not use a similar method to React native/Expo whereby you just import the Activity you want to call and call the function?

Upvotes: 0

Views: 44

Answers (1)

John B Gilbert
John B Gilbert

Reputation: 126

I really hope I can help someone who is in the same boat as me,
It took me quite a while to find the answer to this: essentially it comes in three parts, I had some trouble as I was working with fragments.

In this case I have a text field that I want to update with bluetooth devices from another page.


Part one

At the top of the sending fragment you need a top level declaration as a variable, in this case I am using the term DEVICES to store my data.

const val DEVICES = "DEVICE"

Part two

At the bottom of the sending fragment(include the class definition)

class MainActivity : AppCompatActivity() {
                    override fun onCreate(savedInstanceState: Bundle?) {
                        super.onCreate(savedInstanceState)

                        Intent(this, StyleFragment::class.java)
                            .also { styleFragment ->
                                styleFragment.putExtra(DEVICES, device.name)
                                startActivity(styleFragment)

Part three
At the bottom of the receiving fragment (include the class definition)

class MainActivity : AppCompatActivity() {

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

        intent?.let {
            val devices = it.getStringExtra(DEVICES)
            findViewById<TextView>(R.id.tt_conf_label)
                .text = getString(R.string.tt_confirmation_label, devices)
        }
    }
}

Upvotes: 0

Related Questions