how pass data between more than 2 activities Kotlin - android

I need to pass multiple variables between more than two activities.
I know how to pass between one to another, but not from the first to the third.
Activity One
btnNext.setOnClickListener {
val i = Intent(this, Activity2::class.java)
val variableOne= txtVariableOne.text.toString()
i.putExtra("VARIABLEONE",variableOne)
startActivity(i)
}
Activity TWO
btnNext.setOnClickListener {
val i = Intent(this, Activity3::class.java)
val VariableTwo = txtVariableTwo.text.toString()
i.putExtra("VARIABLETWO",variableTwo)
startActivity(i)
}
Activity THREE (This is what I need)
Log.d("DEBUG ", "Value: " + intent.getStringExtra("VARIABLEONE"))
Log.d("DEBUG ", "Value: " + intent.getStringExtra("VARIABLETWO"))
I need access VariableOne and VariableTwo from activity Three.
Thank

Activity TWO
btnNext.setOnClickListener {
val i = Intent(this, Activity3::class.java)
val VariableTwo = txtVariableTwo.text.toString()
//THIS WHAT YOU NEED:
i.putExtra("VARIABLEONE",intent.getStringExtra("VARIABLEONE"));
i.putExtra("VARIABLETWO",variableTwo)
startActivity(i)
}

Activity Two
override fun viewAllNotes() {
val intent : Intent = Intent(this, ViewAllNotesActivity::class.java)
intent .putExtra("VARIABLEONE",variableOne)
startActivityForResult(intent, VIEW_ALL_REQUEST_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK){
if (requestCode == VIEW_ALL_REQUEST_CODE){
//get data here
}
}
}
}
Activity three
#Override
public void onBackPressed() {
Intent result = new Intent();
result .putExtra("VARIABLEONE",variableOne)
setResult(Activity.RESULT_OK, result);
this.finish();
}
Or else you can store the values using Shared-preference and get values any where in the project

I can say the same as we passing in java
There are many ways
From the one is, You can pass by intent when starting another activity which is proper when you think data at the time of starting the activity like bellow,
val intent = Intent(mActivity, LoginActivity::class.java);
intent.putExtra("keyName", data)
startActivity(intent)
Another way you can use preference or store data in preference and you can use where ever you need.

Related

Android: Fragment is not receiving RESULT_OK in Activity result contract

I am using ActivityResultContract API in my fragment. Fragment A is in Activity A, from where Activity B is called which has Fragment B. Code in Fragment A is as follows:
val makePaymentContract = registerForActivityResult(CustomContract()) { uri: Uri? ->
Log.d("FragmentA", "DATA URI: ${uri.toString()}")
}
This is custom contract:
class CustomContract : ActivityResultContract<DataHolder, Uri>() {
override fun createIntent(context: Context, input: DataHolder?): Intent {
val intent = Intent(context, ActivityB::class.java)
intent.putExtra("data1", input?.data1)
intent.putExtra("data2", input?.data2)
intent.putExtra("data3", input?.data3)
intent.putExtra("data4", input?.data4)
return intent
}
override fun parseResult(resultCode: Int, intent: Intent?): Uri? {
Log.d("CustomContract", "Result Code $resultCode")
when (resultCode) {
Activity.RESULT_OK -> return intent?.data // Return the data
else -> return null
}
}
}
where DataHolder is a simple data class. Below code is in Fragment B(which is in Activity B)
Uri uri = Uri.parse("custom://thank_you?id=" + id + "&amt_paid=" +
totalPaidAmt + "&order_type=" + orderType);
Intent intent = new Intent();
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
requireActivity().finish();
The problem is FragmentA always receives null uri. Upon debugging, found out returned resultCode is always RESULT_CANCELED. What am I doing wrong?
Found out the mistake. I was not setting result from Fragment B
Uri uri = Uri.parse("custom://thank_you?id=" + id + "&amt_paid=" +
totalPaidAmt + "&order_type=" + orderType);
Intent intent = new Intent();
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
requireActivity().setResult(Activity.RESULT_OK, intent);
requireActivity().finish();

startActivityForResult putExtras being recieved as NULL

Hi I am creating a SideActivity to gather some results and pass them back to Main Activity. However, the two strings value from the putextra are NULL rather than the string "20" and the jamSize "medium". Is there a way of passing the data properly?
Here in my Main Activity I have a setOnClickListener and a onActivityResult function.
jamButton.setOnClickListener {
var intent = Intent(this#MainActivity, SideActivity::class.java)
intent.putExtra("jamName", "raspberry")
intent.putExtra("jamPrice", "12.00")
startActivityForResult(intent, 1) // passing request code value 1
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(resultCode == RESULT_OK) {
val jamPrice:String = intent.getStringExtra("jamPrice").toString()
val jamSize:String = intent.getStringExtra("jamSize").toString()
val newJam = DataModel("Jam", "$jamSize", "$jamPrice")
list.add(0, newJam)
jamAdapter.notifyItemInserted(0)
}
}
Here is my Second Activity
completeBtn.setOnClickListener {
val jamPrice: String = textView2.text.toString()
val jamSize: String = textView3.text.toString()
val intent = Intent(this#SideActivity, MainActivity::class.java)
intent.putExtra("jamPrice", "20.00")
intent.putExtra("jamSize", jamSize)
setResult(Activity.RESULT_OK, intent)
finish()
}
In your onActivityResult don't use this :
val jamPrice:String = intent.getStringExtra("jamPrice").toString()
because the intent variable is the Intent of the activity instead use :
val jamPrice: String = data?.getStringExtra("jamPrice").toString()

Get Result - Kotlin startActivityForResult does not deliver any result

Halllo, my BarcodeActivity is called by startActivityForResult through my PCActivity. The value of the scanned barcode should then be returned back to the PCActivity and inserted in a text field there. Unfortunately, I do not get a value back. However, the app does not crash either. Here is my code.
PCActivity:
sn_mb.setDrawableRightTouch {
val intent = Intent(this#PCActivity, BarcodeActivity::class.java)
startActivityForResult(intent, 1)
}
[...]
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null) {
val returnedSN = intent.getStringExtra("return_sn")
sn_mb.setText(returnedSN)
} else {
sn_mb.setText("FEHLER!")
}
}
BarcodeActivity
saveBtn.setOnClickListener {
val sn = editTextBarcode.text.toString()
sn.toString()
if (sn!= "") {
val returnIntent:Intent = Intent()
returnIntent.putExtra("return_sn", sn)
setResult(Activity.RESULT_OK, returnIntent)
finish()
} else {
Toast.makeText(
applicationContext,
"Das ist keine gültige Seriennummer",
Toast.LENGTH_SHORT
).show()
}
}
I hope someone can explain or help me with this problem. Thank you very much.
You are extracting your data from the wrong place.
Replace
val returnedSN = intent.getStringExtra("return_sn")
with
val returnedSN = data.getStringExtra("return_sn")
The problem is you are not passing the scanned bar code value (sn) to the intent(returnIntent) in your BarCodeActivity.
First make sure sn is String since you want to pass a StringExtra, therefore:
val sn = editTextBarcode.text.toString()
And then pass sn to your return intent:
returnIntent.putExtra("return_sn", sn)
Notice that in your code you are passing integer 1 instead of sn.
EDIT:
One more minor fix to your code, didn't notice it:
val returnIntent:Intent = getIntent()
Notice that it's getIntent() instead of Intent()

How can I set a request code under different conditions for my activity to bypass onActivityResult?

I have a program that allows me to store data(pictures and metadata with the taken picture) during the execution of a picture being taking with the android system camera activity... but I have code in place to make sure that the user enters data into a popup activity before the camera activity is displayed by using the OnActivityResult function(this way the user's photo has information that is stored as metadata in my firebase database). I was wondering If I can set a request code that wouldn't be equal to the REQUESTCODE2 so that under the condition that my back button is pressed(which will still result in the REQUESTCODE2 being returned for the com.example.myapplication.nameofphoto activity, which then will trigger takepic()) I can purposely make sure that the request code is faulty so that takepic() does not trigger and I don't store null data into my database.
for your information: nameofpersonvar , and nameofphotovar are both in a different class and is the information from the popup activity
private const val REQUESTCODE = 2
private const val REQUESTCODE2 = 3
fun take_pic(){
val takephotoIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (takephotoIntent.resolveActivity(this.packageManager) != null) {
startActivityForResult(takephotoIntent, REQUESTCODE)
} else {
Toast.makeText(this, "Unable To access Camera... ", Toast.LENGTH_LONG)
.show()
}
}
photoButton.setOnClickListener {
val action3 = Intent(this , com.example.myapplication.nameofphoto::class.java)
startActivityForResult(action3, REQUESTCODE2 )
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (REQUESTCODE == requestCode && resultCode == Activity.RESULT_OK) {
//Compressing the bitmap(image) into a byte[] to match the input of the .putbytes method
val userimage = data?.extras?.get("data") as Bitmap
val byteoutput = ByteArrayOutputStream()
userimage.compress(Bitmap.CompressFormat.JPEG,100 , byteoutput)
val data = byteoutput.toByteArray()
//ref to the firebase "bucket" database
val storageinfo = FirebaseStorage.getInstance().getReference("/Images" )
//extra data that shows who the images belong to (users)
val metadatastoreage = storageMetadata {
setCustomMetadata("Name of person" , nameofpersonvar)
setCustomMetadata("Name of photo" , nameofphotovar)}
storageinfo.putBytes(data, metadatastoreage)
}else if (requestCode ==REQUESTCODE2) {
take_pic()
}
else {
super.onActivityResult(requestCode, resultCode, data)
}
}
Then why don't you send some result code different from the back press method of the current activity opened and check if the result is successful then take pick otherwise do something.
send this as result code from back press method. RESULT_CANCELED
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (REQUESTCODE == requestCode && resultCode == Activity.RESULT_OK) {
//Compressing the bitmap(image) into a byte[] to match the input of the .putbytes method
val userimage = data?.extras?.get("data") as Bitmap
val byteoutput = ByteArrayOutputStream()
userimage.compress(Bitmap.CompressFormat.JPEG,100 , byteoutput)
val data = byteoutput.toByteArray()
//ref to the firebase "bucket" database
val storageinfo = FirebaseStorage.getInstance().getReference("/Images" )
//extra data that shows who the images belong to (users)
val metadatastoreage = storageMetadata {
setCustomMetadata("Name of person" , nameofpersonvar)
setCustomMetadata("Name of photo" , nameofphotovar)}
storageinfo.putBytes(data, metadatastoreage)
return
}
if (requestCode ==REQUESTCODE2 && resultcode == Activity.RESULT_OK) {
take_pic()
} else {
//back pressed do something.
//finish etc
}
}
Edit: You can override the onBackPressed() in the popup activity and send some data using intent to the parent activity. for ex.
Intent resultIntent = new Intent();
// TODO Add extras or a data URI to this intent as appropriate.
resultIntent.putExtra("user_pic_click", "some data");
setResult(Activity.RESULT_OK, resultIntent);
finish();

onActivityResult return null data

I've just been coding in kotlin for a while. I've got some problems.
It always return null data in after I click item in second activity.
first activity
btnClick.setOnClickListener { v ->
val intent = Intent(applicationContext, NumberPickerActivity::class.java)
startActivityForResult(intent, 777)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
try {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 777 && resultCode == Activity.RESULT_OK) {
val result = data?.getStringExtra("picked_product").toString()
Toast.makeText(applicationContext, result, Toast.LENGTH_SHORT).show()
}
} catch (e: Exception) {
Toast.makeText(applicationContext, e.message, Toast.LENGTH_LONG).show()
}
}
second activity
override fun onItemClick(item: Product) {
val intent = Intent()
intent.putExtra("picked_product", item.price)
setResult(Activity.RESULT_OK, intent)
finish()
}
Because you are expecting an Int, do this instead:
val result = data?.getIntExtra("picked_product", 0) //0 will be used in case no value in data and result is now Integer.
The extra you put in your intent is an Integer (item.price). But you are trying to retrive a String data?.getStringExtra("picked_product").
Sinc the intent does not contain a String at the key "picked_product", it returns null.
You should try to get an Int extra :
val result = data?.getIntExtra("picked_product")
Nothing to do with your problem but it's useless to do
data?.getStringExtra("picked_product").toString()
Since it return you a String the use of toString() is useless

Categories

Resources