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()
Related
I am trying to learn Kotlin and I'm building a simple example as I go. I have 3 image buttons that open the camera and take a photo. The thumbnail is then set into an ImageView. I've used the examples from https://developer.android.com/training/camera/photobasics?hl=en to get the basics working (figuring if I can make it work for one, it'll work for all. It does indeed work for one, but I can't figure out how to make it one function that drops the thumbnail into the correct ImageView.
Inside my onCreate I have the listener for each of the buttons that will invoke the camera:
camRead1.setOnClickListener {dispatchTakePictureIntent() }
camRead2.setOnClickListener {dispatchTakePictureIntent() }
camRead3.setOnClickListener {dispatchTakePictureIntent() }
And I took the sample from the url above:
val REQUEST_IMAGE_CAPTURE = 1
private fun dispatchTakePictureIntent() {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
try {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
} catch (e: ActivityNotFoundException) {
// display error state to the user
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val thumb: ImageView = findViewById(R.id.thumbRead1)
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
val imageBitmap = data.extras.get("data") as Bitmap
thumb.setImageBitmap(imageBitmap)
}
}
and pasted it into my class MainActivity, and after I replaced imageView in the override function with a variable (thumb) and added the super, it worked perfectly for the first one.
However, I am trying to get 3 photos, read1, read2, and read3 which each need to display the thumb in thumbRead1, thumbRead2 and thumbRead3. I can't figure out how the onActivityResult is executed since the call inside dispatchTakePictureIntent is calling startActivityForResult (especially as Android Studio says that startActivityForResult is deprecated).
Obviously, once onActivityResult executes, I can see that thumb defines R.id.thumbRead1 and receives imageBitmap but I don't understand how I can make it aware of the button that was clicked.
Without understanding how onActivityResult is called, I'm thinking that if I can do something like:
findViewById(R.id("thumbRead" + imgID))
to define the specific ImageView that I want the photo pasted into. Am I on the right track here? If not, what is the recommended way of doing this?
Note they've recently added what's supposed to be a cleaner way of starting other activities for results and getting the results, explained here. But since you're already doing it the traditional way, I'll explain how to get that working.
I think the easiest thing to do in this situation is just make more request codes, so you can check which request it was.
val REQUEST_IMAGE_CAPTURE_SOURCE_1 = 1
val REQUEST_IMAGE_CAPTURE_SOURCE_2 = 2
val REQUEST_IMAGE_CAPTURE_SOURCE_3 = 3
//...
camRead1.setOnClickListener { dispatchTakePictureIntent(REQUEST_IMAGE_CAPTURE_SOURCE_1) }
camRead2.setOnClickListener { dispatchTakePictureIntent(REQUEST_IMAGE_CAPTURE_SOURCE_2) }
camRead3.setOnClickListener { dispatchTakePictureIntent(REQUEST_IMAGE_CAPTURE_SOURCE_3) }
//...
private fun dispatchTakePictureIntent(requestCode: Int) {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
try {
startActivityForResult(takePictureIntent, requestCode)
} catch (e: ActivityNotFoundException) {
// display error state to the user
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode != RESULT_OK) {
// possibly show message to user
return
}
val imageViewId = when (requestCode) {
REQUEST_IMAGE_CAPTURE_SOURCE_1 -> R.id.thumbRead1
REQUEST_IMAGE_CAPTURE_SOURCE_2 -> R.id.thumbRead2
REQUEST_IMAGE_CAPTURE_SOURCE_3 -> R.id.thumbRead3
}
val imageView = findViewById<ImageView>(imageViewId)
imageView.imageBitmap = data.extras.get("data") as Bitmap
}
By the way, if you want to get an ID for a view using the String like you were showing you were trying, you would do it like this:
val viewId = resources.getIdentifier("thumbRead$imgId", "id", packageName)
val imageView = findViewById<ImageView>(viewId)
You need to pass different request code for each call and pass it to the dispatchTakePictureIntent function. You do not need to get id by findviewbyid. You simply can add the image on the basis of the request code.
val REQUEST_IMAGE_CAPTURE_ONE = 1
val REQUEST_IMAGE_CAPTURE_TWO = 2
val REQUEST_IMAGE_CAPTURE_THREE = 3
private fun dispatchTakePictureIntent(requestCode: Int) {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
try {
startActivityForResult(takePictureIntent, requestCode)
} catch (e: ActivityNotFoundException) {
// display error state to the user
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
val imageBitmap = data.extras.get("data") as Bitmap
if (requestCode == REQUEST_IMAGE_CAPTURE_ONE ) {
thumbRead1.setImageBitmap(imageBitmap)
}else if (requestCode == REQUEST_IMAGE_CAPTURE_TWO ) {
thumbRead2.setImageBitmap(imageBitmap)
}else if (requestCode == REQUEST_IMAGE_CAPTURE_THREE ) {
thumbRead3.setImageBitmap(imageBitmap)
}
}
}
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()
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();
I'm trying to get the result of intent between 2 activities but something is wrong because I always get a resultCode = 0 in initial activity:
Code inside CarsFragment.kt
private fun startAddCarActivity() {
val intent = Intent(context, AddCarActivity::class.java)
startActivityForResult(intent, 1)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// ALWAYS GET requestCode = 1, resultCode = 0 and data = null !!
}
AddCarActivity.kt:
private fun startCarsNavigationActivity() {
intent.putExtra("car", car)
setResult(1, intent)
finish()
}
Problem:
I always get requestCode = 1, resultCode = 0 and data = null in CarsFragment.kt
Where is the problem ?
Result code of 0 means RESULT_CANCELED. This can happen if the Activity you are launching is launched into a different task, or if the user presses the BACK key, or if the launched Activity decides to return RESULT_CANCELED.
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