How to convert string to edit text box in android in intent? - android

How to convert a string to EditText , i make a EditText in one activity and then make a second activity and i get this edittext through the intent in the string then
how to assign it to the second activity's edittext , but i don't find it how to assign string to edittext.Here i used a go function that is used when onclick event is occured of button
This is my first activity
class MainActivity : AppCompatActivity() , View.OnClickListener{
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun go(v:View){
val intent=Intent(this#MainActivity,Main2Activity::class.java)
var aa=EditText1.text
intent.putExtra("name",aa)
startActivity(intent)
}
}
This is my second activity
class Main2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
var str=intent.getStringExtra("name").toString()
et21.setText(str)
}
}

In your first activity change go function as below,
fun go(v:View){
val intent=Intent(this#MainActivity,Main2Activity::class.java)
var aa=EditText1.text.toString()
intent.putExtra("name",aa)
startActivity(intent)
}
In your second activity change the last line of onCreate as below, you need to unwrap the value from an nullable type. Which can be done using let block over nullable type. Also I am assuming et21 is reference to the edit text and is properly initialised.
This solution is null safe
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
intent.getStringExtra("name")?.let {
et21.setText(it)
}
}

Its because you was trying to set charSequence to your EditText , just convert to String while getting value from FirstEditText.
inside your Second Activity -
class Main2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
intent.getStringExtra("name")?.let {
et21.setText(it)
}
}
}
Inside your first activity
fun go(v:View){
val intent=Intent(this#MainActivity,Main2Activity::class.java)
var aa=EditText1.text.toString()
intent.putExtra("name",aa)
startActivity(intent)
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
val extras:Bundle =intent.extras
val nn=extras.getString("name")
eT21.setText("${nn}")
}
Or
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
eT21.setText(intent.getStringExtra("name"))
}

Related

How to start another activity in function? Kotlin

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navigate = Intent(this,Activity2::class.java)
startActivity(navigate)
}
}
}
fun switchActivity(){
val navigate = Intent(this,Activity2::class.java)
startActivity(navigate)
}
I want to start an activity from a function and not from the main activity..
I can start an activity from main class but in function, the code doesnt work..
Please help.. I'm new to kotlin android programming..
You can also try like this
class MainActivity : AppCompatActivity() {
#SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
nextActivity(this, MainActivity2())
}
private fun nextActivity(context: Context, activity: Activity) {
startActivity(Intent(context, activity::class.java))
}
}
Just use it
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
switchActivity()
}
}
fun switchActivity(){
val navigate = Intent(this#MainActivity, Activity2::class.java)
startActivity(navigate)
}
Actually i don't get your question clearly. But i'll try to answer your question based on my understanding of yours.
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
switchActivity()
// if you want to pass the class through the paramater,
// can try this
// TODO: Another Way
// switchActivityCustom(Activity2::class.java)
}
}
fun switchActivity(){
val navigate = Intent(this, Activity2::class.java)
startActivity(navigate)
}
// TODO: Another Function
// fun switchActivityCustom(destination: Class<*>,){
// val navigate = Intent(this, destination)
// startActivity(navigate)
// }
}
And the last one is, put your function inside the class (in this case: MainActivity Class)
If your function is declared at the top level, without a reference to this, you'd need to pass an instance of Activity to your function:
fun switchActivity(activity: Activity) {
val navigate = Intent(activity, Activity2::class.java)
activity.startActivity(navigate)
}

passing a string to an intent kolin

Why I'm getting a null string through Intent even after passing the value?
MainActivity
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding=ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btnFirst.setOnClickListener {
val name=binding.etName.text.toString()
Intent(this,SecondActivity::class.java).also{
it.putExtra("EXTRA_NAME",name)
startActivity(it)
}
}
}
}```
SecondActivity
```class SecondActivity:AppCompatActivity() {
private lateinit var binding: ActivitySecondBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= ActivitySecondBinding.inflate(layoutInflater)
setContentView(binding.root)
val name=intent.getStringArrayExtra("EXTRA_NAME")
val toPrint="$name hahahaha"
binding.tvNameIntent.text=toPrint
}
}
toPrint is getting "null hahahaha"
Can someone please rectify my error
You are putting in a String so you should be also reading a String and not StringArray. You can use e.g. getStringExtra() for that.
val name=intent.getStringArrayExtra("EXTRA_NAME") should be changed to
val name=intent.getStringExtra("EXTRA_NAME")

How do I switch image and text back and forth in tapping the button?

The first time I tap the button, both the image1 and text1 changed to image2 & text2. How do I change both the image and text back to 1st set the 2nd time I tap the button and change them to 2nd set the 3rd time I tap the button ?
Here is my current codes:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun eating(view: View?) {
val afterEatingText:String="I am so full!!"
displayMessage(afterEatingText)
displayImage(R.drawable.after_cookie)
}
private fun displayMessage(message: String) {
val afterEatingText = findViewById<View>(R.id.before_eating) as TextView
afterEatingText.text = message
}
private fun displayImage(imagesource: Int){
val afterEatingImage: ImageView = findViewById<View>(R.id.before_cookie) as ImageView
afterEatingImage.setImageResource(imagesource)
}
}
var isClick:Boolean=false
var afterEatingText :TextView?=null
var afterEatingImage:ImageView?=null
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
afterEatingImage= findViewById<ImageView>(R.id.before_cookie) // find your id you can also direct call with its ids in kotlin
afterEatingText = findViewById<ImageView>(R.id.before_eating)
}
fun eating(view: View?) {
if(isClick){
isClick=true
// set your first image and text
}else {
isClick=false
val afterEatingText:String="I am so full!!"
displayMessage(afterEatingText)
displayImage(R.drawable.after_cookie)
}}
private fun displayMessage(message: String) {
afterEatingText.text = message
}
private fun displayImage(imagesource: Int){
afterEatingImage.setImageResource(imagesource)
}
}

Why do I get an UninitializedPropertyAccessException? Android Kotlin

So I'm trying to send a text data from text entered in edit text through another activity with intent. I'm trying to send the text data from HomeActivity to SearchResultActivity. However, when I clicked the button that calls the startActivity(intent), my application forced closed and I get this exception:
2021-04-27 02:46:30.622 13861-13861/com.dicoding.movieapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.dicoding.movieapp, PID: 13861
kotlin.UninitializedPropertyAccessException: lateinit property activityHomeBinding has not been initialized
at com.dicoding.movieapp.home.HomeActivity.onClick(HomeActivity.kt:39)
at android.view.View.performClick(View.java:7500)
at android.view.View.performClickInternal(View.java:7472)
at android.view.View.access$3600(View.java:824)
at android.view.View$PerformClick.run(View.java:28657)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:239)
at android.app.ActivityThread.main(ActivityThread.java:8107)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1015)
I'm quite confused what I did wrong here. This is my code for the home activity. I have already initialized the binding in the onCreate function but why is it still saying that its uninitialized?
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val activityHomeBinding = ActivityHomeBinding.inflate(layoutInflater)
setContentView(activityHomeBinding.root)
activityHomeBinding.btnSearch.setOnClickListener(this)
}
override fun onClick(v: View?) {
when (v?.id){
R.id.btn_search -> {
val searchText = activityHomeBinding.editTextSearch.text.toString().trim()
if (searchText == null){
activityHomeBinding.editTextSearch.error = "Field cannot be empty"
} else {
val intent = Intent(this#HomeActivity, SearchResultActivity::class.java)
intent.putExtra(SearchResultActivity.EXTRA_SEARCH,searchText)
startActivity(intent)
}
}
}
And this is the code inside my SearchResultActivity:
private lateinit var searchResultActivity: ActivitySearchResultBinding
companion object {
const val EXTRA_SEARCH = "extra_search"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
searchResultActivity = ActivitySearchResultBinding.inflate(layoutInflater)
setContentView(searchResultActivity.root)
searchResultActivity.testIntent.text = intent.getStringExtra(EXTRA_SEARCH)
}
The error message points that on line 39 of your HomeActivity class, you're pointing at an uninitialized property. This is because you have defined 2 activityHomeBindings with different scopes
class HomeActivity : AppCompatActivity(), View.OnClickListener {
...
lateinit var activityHomeBinding: ActivityHomeBinding <-- 1st one, globally scoped
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val activityHomeBinding = ActivityHomeBinding.inflate(layoutInflater) <-- 2nd one, function-scoped (to onCreate)
setContentView(activityHomeBinding.root)
activityHomeBinding.btnSearch.setOnClickListener(this)
}
override fun onClick(v: View?) {
when (v?.id){
R.id.btn_search -> {
val searchText = activityHomeBinding.editTextSearch.text.toString().trim() <-- this points at 1st one, (i.e. globally scoped)
if (searchText == null){
activityHomeBinding.editTextSearch.error = "Field cannot be empty"
}
...
}
}
}
}
The solution is to simply remove val from the line where you're inflating the binding. This way, instead of creating a new variable, you're assigning the inflated binding to globally scoped lateinit var activityHomeBinding which then can be used by your onClick callback.
So make the change from
override fun onCreate(savedInstanceState: Bundle?) {
...
val activityHomeBinding = ActivityHomeBinding.inflate(layoutInflater)
...
}
to
override fun onCreate(savedInstanceState: Bundle?) {
...
activityHomeBinding = ActivityHomeBinding.inflate(layoutInflater)
...
}

Android access view binding val outside onCreate activity

I have an activity that has a button. On the button click I want to update text in text view.
I want to use ViewBinding instead of the normal findViewById
This is how I created the val binding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater);
setContentView(binding.root)
binding.btnRoll.setOnClickListener {
rollDice()
}
}
Now in rollDice I want to update the text view but I'm not able to access binding which make sense because its scope is limited to onCreate() , so what is the best practice for this?
private fun rollDice() {
val random = Random().nextInt(6) + 1
binding.txt_random.setText("random")
}
You have two options.
1. Store in a property
Since the inflated content of Activity is fully bound to it's lifecycle, it's safe to keep the reference as a property
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater);
setContentView(binding.root)
binding.btnRoll.setOnClickListener {
rollDice()
}
}
private fun rollDice() {
val random = Random().nextInt(6) + 1
binding.txt_random.setText("random")
}
}
2. Pass the binding to the methods
That's what I usually do, it avoids creating a property where it's not really a necessity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater);
setContentView(binding.root)
binding.btnRoll.setOnClickListener {
rollDice(binding)
}
}
private fun rollDice(binding: ActivityMainBinding) {
val random = Random().nextInt(6) + 1
binding.txt_random.setText("random")
}
}
Both options are valid ways to make the binding visible to Activities methods.
Store the binding in an instance variable on the Activity. Then you have access to it from all the methods in the Activity.
As the question has accepted answer and it is already addressed but here is my approach to the viewBinding
class MainActivity : AppCompatActivity() {
private val binding by lazy{
ActivityMainBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.btnRoll.setOnClickListener {
rollDice()
}
}
private fun rollDice() {
val random = Random().nextInt(6) + 1
binding.txt_random.setText("random")
}
}
I go with lazy initialization of binding so that way it is only intitialized if it is required.
More you can read about lazy initialization here
https://www.baeldung.com/kotlin/lazy-initialization

Categories

Resources