Input value not updating in another activity which I pass in Intents - android

Mine Main Activity :-
var sec = second_activity()
var button1: Button? = null
var button2: Button? = null
var button3: Button? = null
var button4: Button? = null
button1 = findViewById<View>(R.id.button1) as Button
button2 = findViewById<View>(R.id.button2) as Button
button3 = findViewById<View>(R.id.button3) as Button
button4 = findViewById<View>(R.id.button4) as Button
button1?.setOnClickListener {
sec.input = "a"
val intent: Intent = Intent(this, second_activity::class.java)
startActivity(intent)
}
button2?.setOnClickListener {
sec.input = "b"
val intent: Intent = Intent(this, second_activity::class.java)
startActivity(intent)
}
Second activity :-
class second_activity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
private lateinit var toolbar: Toolbar
private lateinit var mDrawerLayout: DrawerLayout
var input : String = " "
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
//getting recyclerview from xml
val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
//adding a layoutmanager
recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
//crating an arraylist to store users using the data class user
val users = ArrayList<User>()
//adding some dummy data to the list
//creating our adapter
val adapter = CustomAdapter(this , users)
//now adding the adapter to recyclerview
recyclerView.adapter = adapter
Toast.makeText(this, input , Toast.LENGTH_SHORT).show()
when(input) {
"a" -> {
users.add(User(R.drawable.bc))
}
"b" -> {
users.add(User(R.drawable.bc))
users.add(User(R.drawable.bc))
users.add(User(R.drawable.bc))
users.add(User(R.drawable.bc))
}
}
}
Input value is not updating which I pass from MainActivity. It is always taking the blank value which are present in second activity. I also tried by changing the position of Input. but not worked. please help
Is there any other way to find which button is clicked in MainActivity from Second Activity

Yes, there is another way. Use intent.putExtra("requestCode", requestCode). Then in the second activity you can get that requestCode with getIntent().getExtra().getInt("requestCode").

Yes, you can pass the values from one activity to another activity using the following code,
val intent: Intent = Intent(this, SecondActivity::class.java)
intent.putExtra(name, value)
startActivity(intent)
I have given sample code below, please try this..
In first activity, I send the "language" value.
val intent: Intent = Intent(this, SecondActivity::class.java)
intent.putExtra("language", "tamil")
startActivity(intent)
In second activity, I retrived the "language" value.
Put this code in your second activity onCreate()
val intent: Intent = getIntent()
var language = ""
if (intent != null) {
language = intent.getStringExtra("language")
}
println("Language : $language")

Related

Can't pass data from recyclerview adapter to another kotlin fragment

I'm trying to move from activities to fragments
In old activity app when the user clicks on the item he is going to a new activity with item data
Now i need same thing in fragment
Here's my adapter code
override fun onBindViewHolder(holder: PhotosHolder, position: Int) {
val productPhoto = photosArrayList[position]
val key = productPhoto.key
val name = productPhoto.name
val price = productPhoto.price
val photo = productPhoto.photo
val photo2 = productPhoto.photo2
val photo3 = productPhoto.photo3
val link = "http://suleimanmf.com/Photos/"
holder.key.text = key
holder.name.text = name
holder.price.text = price
holder.photo = photo
holder.photo2 = photo2
holder.photo3 = photo3
holder.container.setOnClickListener {
goToProductInfo(productPhoto)
}
}
private fun goToProductInfo(info: Photo) {
val photosFragment = PhotosFragment()
val bundle = Bundle()
bundle.putString("key", info.key)
bundle.putString("name", info.name)
bundle.putString("price", info.price)
bundle.putString("photo", info.photo)
bundle.putString("photo2", info.photo2)
bundle.putString("photo3", info.photo3)
photosFragment.arguments = bundle
(context.applicationContext as MainActivity).supportFragmentManager.beginTransaction()
.apply {
replace(R.id.nav_host_fragment_content_main, photosFragment).addToBackStack(null)
commit()
}
// Old activity
/**
val intent = Intent(context, ProductInfoActivity::class.java)
intent.putExtra("key", info.key)
intent.putExtra("name", info.name)
intent.putExtra("price", info.price)
intent.putExtra("photo", info.photo)
intent.putExtra("photo2", info.photo2)
intent.putExtra("photo3", info.photo3)
startActivity(context, intent, null)
*/
}
}
When I click on the item I get this error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.suleimanmf.gazarcustomers, PID: 5389
java.lang.ClassCastException: android.app.Application cannot be cast to androidx.appcompat.app.AppCompatActivity
at com.suleimanmf.gazarcustomers.ui.gallery.adapter.PhotosAdapter.goToProductInfo(PhotosAdapter.kt:97)
at com.suleimanmf.gazarcustomers.ui.gallery.adapter.PhotosAdapter.onBindViewHolder$lambda-0(PhotosAdapter.kt:80)
Sorry for my poor English
Thanks in advance
The main problem is that you are getting the application context and casting it to MainActivity which is not possible because as the name declares it's application context only. Actually when you want to work with fragments, the only component which is rrsponsible to hold the fragments inside, is the activity instance.
So, the only thing you need to do is replacing the below code lines:
(context.applicationContext as MainActivity).supportFragmentManager.beginTransaction()
.apply {
replace(R.id.nav_host_fragment_content_main, photosFragment).addToBackStack(null)
commit()
}
With the below lines of code:
(context as MainActivity).supportFragmentManager.beginTransaction()
.apply {
replace(R.id.nav_host_fragment_content_main, photosFragment).addToBackStack(null)
commit()
}
Then your code will work properly.

How do I store a String for later use in Kotlin?

I am trying to store the String from the Hours and Number for use in a new activity. I have found ways of doing it with intent but do not want the strings sent through to the next activity. Is there any way of me saving my String data and being able to call it to a different activity?
class ChecksStartUp : AppCompatActivity() {
lateinit var hours: EditText
lateinit var number: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
getSupportActionBar()?.hide()
setContentView(R.layout.activity_Checks_pg1)
val number = findViewById(R.id.machineFleetNumberId)
val hours = findViewById(R.id.machineHoursId)
val dButton = findViewById<RadioButton>(R.id.dButtonId)
val eButton = findViewById<RadioButton>(R.id.eButtonId)
val hButton = findViewById<RadioButton>(R.id.hButtonId)
val proceedButton = findViewById<Button>(R.id.proceedButtonId)
proceedButton.setOnClickListener {
if (dButton.isChecked()) {
val intent = Intent(this, DPage::class.java)
startActivity(intent)
}
if (eButton.isChecked()) {
val intent = Intent(this, EPage::class.java)
startActivity(intent)
}
if (hButton.isChecked()) {
val intent = Intent(this, HPage::class.java)
}
}
}
}
Alot of different ways to store data. Simplest way is to create singleton class - object.
In Android studio create new Kotlin file/class, choose Object.
this is short example:
object GlobalVariables { var hourses:String?="" var number:Int?= null }
access:
GlobalVariables.number=3 - set
val number =GlobalVariables.number - get
You can access this data everywhere you want in your classes, fragments and activites , but remember - when app is terminated data is immediately lost.

To enable different pages to be opened according to the selection of the radio buttons on the registration page

I have 2 radio buttons on my user registration page. If the user has registered by clicking the first radio button, I want to open the page according to him when he opens the application again, and if he has registered by clicking the second radio button, I want to show the page accordingly. How can I do that ?
class SignUpPage : AppCompatActivity() {
private lateinit var binding: ActivitySignUpPageBinding
private lateinit var auth : FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySignUpPageBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
auth = Firebase.auth
}
fun loginSignUp (view: View){
val name = binding.nameText.text.toString()
val surname = binding.surnameText.text.toString()
val email = binding.emailText.text.toString()
val password = binding.PasswordText.text.toString()
val button = binding.radioButton4.isChecked
val button2 = binding.radioButton5.isChecked
if(name.equals("")|| surname.equals("")|| email.equals("") || password.equals("") || button.equals("") || button2.equals("")) {
Toast.makeText(this,"Lütfen Tüm Alanları Doldurun.",Toast.LENGTH_SHORT).show()
}
else if (radioButton4.isChecked){
auth.createUserWithEmailAndPassword(email,password).addOnSuccessListener {
val intent = Intent(this#SignUpPage,AccetpActivity::class.java)
startActivity(intent)
finish()
}
}
else if(radioButton5.isChecked){
auth.createUserWithEmailAndPassword(email, password).addOnSuccessListener {
val intent = Intent(this#SignUpPage,MainActivity::class.java)
startActivity(intent)
finish()
}.addOnFailureListener {
Toast.makeText(this#SignUpPage,it.localizedMessage,Toast.LENGTH_SHORT).show()
}
}
}
}
You can store value of radio button which selected by user in Android Shared preferences.
When user reopen the app, check the value from preference in splash activity of your app and open activity as per value.
Shared pref ref: https://developer.android.com/training/data-storage/shared-preferences

view binding isn't working on Button setOnClickListner... [*ERROR = Variable 'getOTPButton' is never used] (KOTLIN)

please check out this error. I have used view binding on this activity to save data in Firebase. I have used the If... else statement on setOnClickListner.
Code for the Activity:
class RegisterSelection : AppCompatActivity() {
private lateinit var binding: ActivityRegisterSelectionBinding
private lateinit var database: DatabaseReference
#SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityRegisterSelectionBinding.inflate(layoutInflater)
setContentView(binding.root)
setContentView(R.layout.activity_register_selection)
val checkPasswordTwo = findViewById<CheckBox>(R.id.checkPasswordTwo)
val passwordText = findViewById<EditText>(R.id.passwordText)
val confirmPassText = findViewById<EditText>(R.id.confirmPassText)
val fullName=findViewById<EditText>(R.id.fullName).text.toString()
val phoneNumberEdit=findViewById<EditText>(R.id.phoneNumberEdit).text.toString()
val getOTPButton = findViewById<Button>(R.id.getOTPButton)
binding.getOTPButton.setOnClickListener {
if(fullName.isEmpty() && phoneNumberEdit.isEmpty()){
Toast.makeText(applicationContext,"Fill all the Fields!",Toast.LENGTH_LONG).show()
}
else{
database = FirebaseDatabase.getInstance().getReference("UserDataClass")
val users = UserDataClass(fullName, phoneNumberEdit)
database.child(fullName).setValue(users).addOnSuccessListener {
binding.fullName.text.clear()
binding.phoneNumberEdit.text.clear()
Toast.makeText(applicationContext,"Success!",Toast.LENGTH_SHORT).show()
}.addOnFailureListener {
Toast.makeText(applicationContext,"Failed to Save!",Toast.LENGTH_SHORT).show()
}
val intent = Intent(this, getOTP::class.java)
startActivity(intent)
}
}
checkPasswordTwo.setOnClickListener {
if (checkPasswordTwo.text.toString() == "Show Password"){
passwordText.transformationMethod = HideReturnsTransformationMethod.getInstance()
confirmPassText.transformationMethod = HideReturnsTransformationMethod.getInstance()
checkPasswordTwo.text = "Hide Password"
} else{
passwordText.transformationMethod = PasswordTransformationMethod.getInstance()
confirmPassText.transformationMethod = PasswordTransformationMethod.getInstance()
checkPasswordTwo.text = "Show Password"
}
}
}
}
build.gradle
buildFeatures{ viewBinding true }
UserDataClass
data class UserDataClass(val fullName: String? = null, val phoneNumberEdit: String? = null)
Output only shows the Toast "fill all the fields."
Any suggestions would be grateful.
I recommend,if(fullName.isEmpty() && phoneNumberEdit.isEmpty()) change this to if(fullName.isEmpty() || phoneNumberEdit.isEmpty()){ - you want to ensure that both are filled I assume.
Secondly, since you are using binding, I would also recommend that you check for null this way: binding.<edit text id>.text.isNullOrEmpty().
Lastly, it looks like you are initialising your text values by reading the text value in the edit text post inflation and not reading the values you have entered on button click. In your onClickListener, read the values from your editText and then check for null.

setting language before setContentView results in unending loop

I have a fragment with settings of an app that saves the user selected mode and language
( a bit of code:
binding.languageButton.setOnClickListener{
builder = AlertDialog.Builder(requireContext())
builder.setTitle(getString(R.string.setLanguage))
builder.setItems(langArray) { _, which ->
val sharedPref = requireActivity().getSharedPreferences("Settings", Context.MODE_PRIVATE).edit()
sharedPref.putString("LANGUAGE", langArray[which]).apply()
checkUserPreferences()
changeLanguage(langArray[which])
binding.languageButton.text = langArray[which]
}
builder.create()
builder.show()
}
}
private fun changeLanguage(language: String) {
if(language != binding.languageButton.text.toString()){
val local = Locale(language)
val dm = resources.displayMetrics
val con = resources.configuration
con.locale = local
resources.updateConfiguration(con, dm)
val refresh = Intent(
requireContext(),
MainActivity::class.java
)
refresh.putExtra(binding.languageButton.text.toString(), language)
startActivity(refresh)
}
}
and that part (as mentioned) saves mode and selected language to sharedPreferences that I later want to use in mainActivity and other fragments, and I've put in MainActivity:
private fun loadPreferences(){
val preferences = getSharedPreferences("Settings", Activity.MODE_PRIVATE)
Log.i(TAG, preferences.getString("LANGUAGE", "eng").toString())
Log.i(TAG, preferences.getInt("MODE", 1).toString())
val local = Locale(preferences.getString("LANGUAGE", "eng").toString())
val dm = resources.displayMetrics
val con = resources.configuration
con.locale = local
resources.updateConfiguration(con, dm)
val refresh = Intent(
this.baseContext,
MainActivity::class.java
)
refresh.putExtra(preferences.getString("LANGUAGE", "eng").toString(),
preferences.getString("LANGUAGE", "eng"))
startActivity(refresh)
}
and this is referenced in:
class MainActivity : AppCompatActivity() {
// TODO: IT'S THE ONE
companion object {
private const val TAG = "MainActivity"
private const val CHANNEL_ID = "plantz_app_channel_01"
private const val notificationId = 909
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
loadPreferences()
setContentView(R.layout.activity_main)
// ...
and after running the app It only shows the app logo and logs sharedPreferences but the app doesn't go any further, I've tried to tweak with it for a bit but It hasn't done much, any ideas what should I change to make it work?
Thanks in advance :)
This infinity loop happens because when the MainActivity is going to be opened you call loadPreferences() in onCreate method where you open a new instance of MainActivity from there.
So the infinity loop goes like below:
onCreate() method of MainActivity is called
loadPreferences() method is called
in loadPreferences() after you have set the language from SharedPreferences you start a new instance of your MainActivity which redirects you back to step 1.
To avoid this infinity loop remove the below lines from your loadPreferences() method:
val refresh = Intent(this.baseContext,MainActivity::class.java)
refresh.putExtra(preferences.getString("LANGUAGE", "eng").toString(), preferences.getString("LANGUAGE", "eng"))
startActivity(refresh)

Categories

Resources