I am a beginner in Android. I have two layout resource files as shown above.
I want to type a word in the first one and click the button, then it is suppose to go to the 2nd layout resource file and display the word on the text view box. I keep getting an error whenever I try.
Below is the code I wrote
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
button.setOnClickListener {
startActivity(Intent(this, NewLayoutActivity::class.java))
}
}
for the new layout activity
class NewLayoutActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.new_layout)
textView.text = ${editText.text}
}
you should try `intent
var data2 = editText.text.toString
val intent = Intent(applicationContext,secondActivity::class.java)
intent.putExtra("name",data2)
startActivity(intent)
in the second
val data = intent.getStringExtra("name")
you should learn navigation its better and easier
pass data with intent while open new activity:
val intent = Intent(this, NewLayoutActivity::class.java)
intent.putExtra("value", "value you want to pass")
startActivity(intent)
And get in second activity as:
var bundle :Bundle ?=intent.extras
var message = bundle!!.getString("value") // if the value is type of String
change your code from this
button.setOnClickListener {
startActivity(Intent(this, NewLayoutActivity::class.java))
}
to this
val value = edit_text_id.text
button.setOnClickListener {
startActivity(Intent(this, NewLayoutActivity::class.java)
.putExtra("key", value))
}
then, get your value on second activity with this
val value = Intent().getStringExtra("key")
text_view_id.text = value
Related
MainActivity.kt
PutExtra(String!.String?) is givng error (in android Kotlin), what could be the problem?
class MainActivity : AppCompatActivity()
{
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
var name:EditText? = null
fun createBirthdayCard(view: View) {
name = findViewById(R.id.NameInput)
val intent = Intent(this,BirthdayGreetActivity::class.java)
intent.putExtra(BirthdayGreetActivity.NAME_EXTRA,name)
startActivity(intent)
}
}
when sending data
intent.putExtra("name",name)
when receiving data
val name= intent.getStringExtra("name").toString()
intent.putExtra(BirthdayGreetActivity.NAME_EXTRA,name)
this line of yours adds NameInput to intent not string. I dont know what your NameInput is but you may try name.text. Maybe if you gave the code of NameInput I might help better.
I am making an app (ehealth portal) in Android Studio using Kotlin language and in that app, the user should be able to book an appointment choosing date/time/doctor's name from a dropdown list, and once they push the "book a date" button a confirmation screen appears that has the values of the dropdown lists (date/time/doctor's name) passed into a confirmation text confirmation activity instance booking a dated interface.
CalendarFragment.kt
package com.example.mydoctor
import...
class CalendarFragment : Fragment() {
private lateinit var binding: FragmentCalendarBinding1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreate(savedInstanceState)
binding = FragmentCalendarBinding1.inflate(layoutInflater)
val itemsDates = resources.getStringArray(R.array.dates)
val adapterDate = ArrayAdapter(requireContext(), list_dates, itemsDates)
binding.autocompleteTextViewDateDropdown.setAdapter(adapterDate)
val itemsTimes = resources.getStringArray(R.array.times)
val adapterTime = ArrayAdapter(requireContext(), list_times, itemsTimes)
binding.autocompleteTextViewTimeDropdown.setAdapter(adapterTime)
binding.bookADateButton.setOnClickListener {
val intent = Intent(requireContext(),ConfirmationActivity::class.java)
intent.putExtra("Confirmation","Confirmation Value")
startActivity(intent)
}
return binding.root
}
}
ConfirmationActivity.kt
package com.example.mydoctor
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
class ConfirmationActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_confirmation)
val value = intent.getStringExtra("Confirmation").toString()
Log.d("conf","Values is: ${value}")
}
}
How can I go about that? I know I have to use getExtra() or getStringExtra() but how should I actually get the value from the calendar fragment?
EDIT:
I tried changing the setOnClickListener in the CalendarFragment.kt as follows but it does not seem to work storing the value:
binding.bookADateButton.setOnClickListener {
(date_dropdown.getEditText() as AutoCompleteTextView).onItemClickListener =
OnItemClickListener {
adapterView, view, position, _ ->
val selectedValue: String? = adapterDate.getItem(position)
}
val intent = Intent(requireContext(),ConfirmationActivity::class.java)
intent.putExtra("Confirmation","Confirmation Value")
startActivity(intent)
}
You have to setup your date_dropdown listener outside of the setOnClickListener, otherwise you only start listening to date_dropdown changes after the first click is made, which is already too late.
So change the order in your code
// have a variable to track the last selected value with a larger
// scope somewhere inside your Fragment
var selectedValue: String? = null
(date_dropdown.getEditText() as AutoCompleteTextView).onItemClickListener =
OnItemClickListener { adapterView, view, position, _ ->
// this code block is called every time an item is clicked
selectedValue = adapterDate.getItem(position)
}
binding.bookADateButton.setOnClickListener {
// this code block is called every time the 'bookADateButton' is clicked
val intent = Intent(requireContext(), ConfirmationActivity::class.java)
intent.putExtra("Confirmation", selectedValue ?: "No value was selected.")
startActivity(intent)
}
There is also the setOnItemSelectedListener available, if you don't want to rely on clicks/taps.
I'm getting an error stating that I have an unresolved reference in both places where I try a findViewById though both login_button and username are present in my xml file
class LoginPage : AppCompatActivity() {
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityLoginPageBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLoginPageBinding.inflate(layoutInflater)
setContentView(binding.root)
val button = findViewById<Button>(R.id.login_button)
button.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
val name = findViewById<EditText>(R.id.username)
val value: String = name.text.toString()
File("current_users.txt").appendText(value)
}
}
When you use view binding, you don't need to call findViewById(). Instead, use the fields that are generated in the ActivityLoginPageBinding class. For example, you can do binding.login_button if there is an id:+login_button and <Button android:id=#+id/username> in your XML layout. See the View Binding guide for more details.
I'm writing an Android app in Android Studio with Kotlin. As I'm new to this, I had a wrong perception that every new 'shot' needs a new activity. I'm writing a story game with multiple shots.
So, my activities differ only by data.
There 2 types of repeating parts:
1st: only picture on the screen is changing with next-button press.
Code:
class Kadr1Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_kadr01)
}
fun nextClick(view: View) {
val intentKadr2 = Intent(this, Kadr2Activity::class.java) //every next button intents next shot
startActivity(intentKadr2)
this.finish()
}
fun backClick(view: View){
val intentKadr0 = Intent(this, MainActivity::class.java) //every back button intents previous shot
startActivity(intentKadr0)
this.finish()
}
}
2nd: user should solve the task by clicking the correct answer.
Code:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_kadr13)
}
var flag = false
fun nextClick(view: View) {
val intentKadr14 = Intent(this, Kadr14Activity::class.java)
startActivity(intentKadr14)
this.finish()
}
fun backClick(view: View){
val intentKadr12 = Intent(this, Kadr12Activity::class.java)
startActivity(intentKadr12)
this.finish()
}
fun btn1Click(view: View){
ans131Btn.setImageResource(R.drawable.btn_13_1_chosen) //picture of chosen button is changed every time it is pressed
ans132Btn.setImageResource(R.drawable.btn_13_2)
ans133Btn.setImageResource(R.drawable.btn_13_3)
flag = false
}
fun btn2Click(view: View){
ans132Btn.setImageResource(R.drawable.btn_13_2_chosen)
ans131Btn.setImageResource(R.drawable.btn_13_1)
ans133Btn.setImageResource(R.drawable.btn_13_3)
flag = true
}
fun btn3Click(view: View){
ans133Btn.setImageResource(R.drawable.btn_13_3_chosen)
ans131Btn.setImageResource(R.drawable.btn_13_1)
ans132Btn.setImageResource(R.drawable.btn_13_2)
flag = false
}
}
I've read that it would be better to get rid of repeating parts of code and refactor it somehow.
Could anyone give me a hint where I can actually find how to refactor my code? Would be very grateful.
my aplication
I have 2 activity, the first is CategoryActivity and the second is QuestionActivity.
in CategoryActivity i have a recyclerview which lists categories, and also in Category Activity, i have an array. When i click eksterior, it will go to questionActivity, and when i click submit, it will back to CategoryActivity and send data to CategotyActivity. the data sent was entered into the array, so the array will be like this: array [] = {“1”}; then i click the second item in recyclerview which is interior, then it will go to QuestionActivity again, when i click submit, it will send data to CategoryActivity and add it into the previous array, so the array will be like this : array [] = {“1”,”1”}; and so on until the items on the recyclerview run out. I have tried like this :
QuestionActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_result)
button_save.setOnClickListener(){
val intent = Intent(this#ResultActivity, KategoriActivity::class.java)
intent.putExtra(KategoriActivity.Companion.ARRAY, "1")
startActivity(intent)
}
}
CategoryActivity.kt
var list = arrayOf(intent.getStringExtra(ARRAY))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_category)
Toast.makeText(this#KategoriActivity, ""+ list, Toast.LENGTH_SHORT).show()
}
companion object {
val ARRAY = "array"
}
override fun onBackPressed() {
Toast.makeText(this#KategoriActivity, ""+ list, Toast.LENGTH_SHORT).show()
if (list.size == kategoriDatas!!.size){
onBackPressed()
} else {
val builder = AlertDialog.Builder(this)
builder.setMessage("You Must Finish All The Category")
// add a button
builder.setPositiveButton("OK", null)
// create and show the alert dialog
val dialog = builder.create()
dialog.show()
}
}
and the problem is when i open category activity the app is stopped, and the log is say Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
and the data can not push to the array, please help me
You can only get the intent after the activity has been created. In order to make sure of it it's best if you place the code that's gonna get the extras from Intents inside your onCreate.
Like this:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_category)
Toast.makeText(this#KategoriActivity, ""+ list, Toast.LENGTH_SHORT).show()
var list = arrayOf(intent.getStringExtra(ARRAY))
}
If you want to have an Application class that holds information:
class MyApplication : Application(){
var list = emptyArray<String>()
override fun onCreate() {
super.onCreate()
}
}
To use it in your activity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_category)
Toast.makeText(this#KategoriActivity, ""+ list, Toast.LENGTH_SHORT).show()
var list = (application as MyApplication).list
// you can than use it to update or retrieve values from it
}