Home > Back-end >  I'm trying to put extra data in an intent. But can't get this extra in another activity
I'm trying to put extra data in an intent. But can't get this extra in another activity

Time:12-12

Tried to create another activity and put same code in it but still had "null" in result.Had problem only with one specific kotlin Activity. Also google it and cant find answer. with rest activities no such problem with same Intent put extra code.

**Noticed that if I set activity startActivity from 'A' to 'C' I can get Intent with same code. But If A>B>C than on 'C' activity I get null from 'A' activity **

class GenderActivity : AppCompatActivity() {

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

        val btn: Button = findViewById(R.id.btnNextGender)
        val radioG: RadioGroup = findViewById(R.id.radioGroupD)




        btn.setOnClickListener {
            val i = Intent(this, GoalsActivity::class.java)
            i.putExtra("sex", "some text")
            startActivity(i)
           

        }
    }


private lateinit var database: DatabaseReference

class QuizActivity2 : AppCompatActivity() {

@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_quiz2)





    val btnAddUser = findViewById<Button>(R.id.buttonAddUser)

    val muscles = intent.getStringExtra("muscles").toString()
    val gender:String = intent.getStringExtra("sex").toString()

    val goal = intent.getStringExtra("goal")


    val textOn:TextView = findViewById(R.id.textViewQst2)


    btnAddUser.setOnClickListener{
        val userName = findViewById<EditText>(R.id.inputUserName).text.toString()
        val userAge = findViewById<EditText>(R.id.inputUserAge).text.toString()



        if(userAge.isEmpty()||userName.isEmpty()){
            Toast.makeText(
                this,
                "заповни всі поля",
                Toast.LENGTH_SHORT
            ).show()
        }
        if(userAge.isNotEmpty()&&userName.isNotEmpty()){
        database = FirebaseDatabase.getInstance().getReference("Users")


        val userId = database.push().key!!
        data class User(val firstName:String? = null,val userGender:String? = null,val age:String? = null,val uId:String? = null,val muscles:String? = null,val goals:String? = null)
        val user = User(userName,gender,userAge,userId,muscles,goal)
            textOn.text = user.toString()

        database.child(userName).setValue(user).addOnSuccessListener {
            findViewById<EditText>(R.id.inputUserName).text.clear()
            findViewById<EditText>(R.id.inputUserAge).text.clear()
        }
    }



}


}

}


CodePudding user response:

Try this intent.extras?.getString("sex")if this does not work then, clean your build or do the invalidate cache and restart Android studio, Looks like there is no issue with the code. refer this thread if you need to. here

CodePudding user response:

**Noticed that if I set activity startActivity from 'A' to 'C' I can get Intent with the same code. But If A>B>C then on the 'C' activity I get null from the 'A' activity **

if this is your issue then yes it is normal intent behavior when you send data from A to B it works fine but when you send it from B to C you get null cuz also you need to store/send it from B to C, Also duplicate your A's code to B ,,, the idea here is what I am trying to explain when you go from A>B>C the data(the data you saved in A) will be removed, You need to store/send data in every activity, Your activities code will get really messy so there is an even better solution is to use Shared preference, shared preference will save your data in a file, For example, you can save data in A then get it in C/D/E/F/G freely without store/send data in every activity even if you went A>B>C>D>E

You can use Shared preference simply but depending on the type of data don't worry I got you with both

this is for primitive data types Store in SharedPreference(your A activity) :

val preference=getSharedPreferences(your_preference_name, Context.MODE_PRIVATE)

        val editor=preference.edit()
        editor.putBoolean("isLoggedIn",true)
        editor.putInt("id",1)
        editor.putString("name","Alex")
        editor.commit()
        
    
 

Retrieve the data from SharedPreference (in your B,C,D,E or F activity)

          val preference=getSharedPreferences(your_preference_name, Context.MODE_PRIVATE)
          if(preference != null){
            val name = preference.getString("name", "")
            val id = preference.getInt("id", 0)
            val isLoggedIn = preference.getBoolean("isLoggedIn", false)
        }

and this is for clearing the values of the shared preference:

this.getSharedPreferences(your_preference_name, Context.MODE_PRIVATE).edit().clear().apply();
        

the second type of data is your custom object in other words your created class and you have to use the Gson library to do so which is going to convert your POJO to a string and then convert the string to JSON, when receiving your object it will reverse the algorithm :

this is GSON dependency for the converting:

 //Gson
implementation 'com.google.code.gson:gson:2.8.9'

Store in Gson SharedPreference :

val sharedPreferencesToJson =
                getSharedPreferences(
                    your_preference_name, Context.MODE_PRIVATE
                )

            val object = Customer() // your object what ever it is
            object.cMobile = mobile
            object.cImage = imageUri.toString()
            val edit = sharedPreferencesToJson.edit()

            val gsonCustomer = Gson()
            val json = gsonCustomer.toJson(object)
            edit.putString(/*your object lable*/, json)
            edit.apply()

Retrieve from Gson SharedPreference:

val sharedPreferences =
            getSharedPreferences(
                your_preference_name, MODE_PRIVATE
            )
        val gson = Gson()
        if (sharedPreferences != null)
        {
            val json: String = sharedPreferences.getString(/*your object lable*/, "")!!
            object = gson.fromJson(json, Customer::class.java)
        }

Clear Gson SharedPreference :

 this.getSharedPreferences(your_preference_name, Context.MODE_PRIVATE).edit().clear().apply();

That's it !!

  • Related