Android OnActivityResult gave me a NULL value with getStringExtra() - android

I'm trying to get a response inside the onActivityResult from an uri intent. However, it is always -1 as resultCode and null as Intent data.
private fun startMyFunction(call: MethodCall) {
val app: String? = call.argument("app")
val url: String? = call.argument("url")
try {
val uri = Uri.parse(url)
val intent = Intent(Intent.ACTION_VIEW, uri)
intent.setPackage(app)
if (activity?.let { intent.resolveActivity(it.packageManager) } == null) {
this.success("activity_unavailable")
return
}
activity?.startActivityForResult(intent, requestCodeNumber)
} catch (ex: Exception) {
Log.e("my_app", ex.toString())
this.success("failed_to_open_app")
}
}
private fun success(o: String) {
if (!hasResponded) {
hasResponded = true
result?.success(o)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
if (requestCodeNumber == requestCode && result != null) {
Log.d("onActivityResult - response - ", data.toString())
if (data != null) {
try {
val response = data.getStringExtra("response")!!
this.success(response)
} catch (ex: Exception) {
this.success("invalid_response - Exception")
}
} else {
this.success("user_cancelled - Null data")
}
}
return true
}
I have read many of the similar situations here on StackOverflow, as well as on Google, but none of them have helped me in my case
For ref -
https://github.com/GJJ2019/upi_pay/blob/master/android/src/main/kotlin/com/drenther/upi_pay/UpiPayPlugin.kt

Related

Pick file with registerForActivityResult on Androidx

I need to implement the select file option in my webviewActivity and all the tutorials I found have only the example with the startActivityResult, but it is currently deprecated and so I would like some help on how to transform this code to the new templates of a register as in the documentation: https://developer.android.com/training/basics/intents/result.
WebviewActivity.kt
class WebviewActivity: AppCompatActivity() {
val REQUEST_SELECT_FILE = 1
val FILE_CHOOSER_RESULT = 2
var uploadMessage: ValueCallback<Array<Uri>>? = null
var uploaded: ValueCallback<Uri>? = null
private fun launchWebview(url: String): WebView =
webview_id.apply{
loadUrl(url)
webViewClient : object = WebViewClient(){
//...//
}
webChromeClient : object = WebChromeClient(){
override fun onShowFileChooser(
webView: WebView?,
filePathCallback: ValueCallback<Array<Uri>>?,
fileChooserParams: WebChromeClient.FileChooserParams
): Boolean{
if (uploadMessage != null){
uploadMessage!!.onReceiveValue(null)
uploadMessage = null
}
uploadMessage = filePathCallback
val intent = fileChooserParams.createIntent()
startActivityForResult(intent, REQUEST_SELECT_FILE)
return true
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_SELECT_FILE){
uploadMessage!!.onReceiveValue(
WebChromeClient.FileChooserParams.parseResult(
resultCode, data
)
)
uploadMessage = null
} else if (requestCode == FILE_CHOOSER_RESULT){
val result = if (data == null || resultCode != RESULT_OK) null else data.data
uploaded!!.onReceiveValue(result)
uploaded = null
}
super.onActivityResult(requestCode, resultCode, data)
}
}
I used this link to make the code above: Android File Chooser not calling from Android Webview
You have to do sth. like that:
private fun createFile() {
getResult.launch("chartName.pdf")
}
private val getResult = registerForActivityResult(
CreateSpecificTypeDocument("application/pdf")
) { uri ->
if(uri != null){
contentResolver.openFileDescriptor(uri, "w")?.use {
FileOutputStream(it.fileDescriptor).use { fileOutputStream ->
//DO sth. with file
}
}
}
}
with:
class CreateSpecificTypeDocument(private val type: String) :
ActivityResultContracts.CreateDocument() {
override fun createIntent(context: Context, input: String): Intent {
return super.createIntent(context, input).setType(type)
}
}

Object does not exist at location android studio Kotlin

I wanna store an image in firebase storage but i got an warning message when running "Object does not exist at location", I don't know where is my mistake, already trying search old answer but all of them in java not kotlin.
class Activity2 : AppCompatActivity() {
private var curFile: Uri? = null
private val imageRef = Firebase.storage.reference
private val REQUEST_CODE_IMAGE_PICK = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity2)
//an image view to select and image inside phone storage
ivfoto.setOnClickListener {
Intent(Intent.ACTION_GET_CONTENT).also {
it.type = "image/*"
startActivityForResult(it, REQUEST_CODE_IMAGE_PICK)
}
}
//btn for upload image to storage
btnupload.setOnClickListener {
uploadImageToStorage("Myimages")
}
}
//function to upload an image to firebase
private fun uploadImageToStorage(filename: String) = CoroutineScope(Dispatchers.IO).launch {
try {
curFile?.let {
imageRef.child("images/$filename").putFile(it).await()
withContext(Dispatchers.Main) {
Toast.makeText(
this#Activity2, "Foto anda telah dipilih",Toast.LENGTH_LONG).show()
}
}
} catch (e: Exception) {
withContext(Dispatchers.Main) {
Toast.makeText(this#Activity2, e.message, Toast.LENGTH_LONG).show()
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_IMAGE_PICK) {
data?.data?.let {
curFile = it
ivfoto.setImageURI(it)
}
}
}
}
Here is the error message,its on the device,already run in physical device and emulator but the error is the same

Kotlin Fragment : Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

I use Intent.ACTION_PICK to take picture from gallery.
I already success when implement both activity, but found problem when using fragment.
I need some help, please.
Here MainActivity.kt
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
REQUEST_NEW_CHAT -> {
val name: String = data?.getStringExtra(PARAM_NAME) ?: ""
val phone: String = data?.getStringExtra(PARAM_PHONE) ?: ""
checkNewChatUser(name, phone)
}
//TODO: I.5. Update Status Page
REQUEST_CODE_PHOTO -> statusUpdateFragment?.storeImage(data?.data)
}
}
}
Here StatusUpdateFragment.kt
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
lay_progressbar.setOnTouchListener { v, event -> true }
btn_status.setOnClickListener { onUpdate() }
populateImage(context, imageUrl, img_status)
lay_status.setOnClickListener{
if(isAdded){
(activity as MainActivity).startNewActivity(REQUEST_CODE_PHOTO)
}
}
}
fun storeImage(imageUri: Uri?) {
if (imageUri != null && userId != null) {
//error message : Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
try {
Toast.makeText(activity, "Uploading...", Toast.LENGTH_SHORT).show()
lay_progressbar.visibility = View.VISIBLE
}
catch (e:Exception){
e.message
}
/*more code that i hide it...*/
}
}
Alhamdulillah, i already solved by Fahru.
MainActivity.kt : must add this at onActivityResult
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
REQUEST_NEW_CHAT -> {
val name: String = data?.getStringExtra(PARAM_NAME) ?: ""
val phone: String = data?.getStringExtra(PARAM_PHONE) ?: ""
checkNewChatUser(name, phone)
}
//TODO: I.5. Update Status Page
REQUEST_CODE_PHOTO -> statusUpdateFragment?.storeImage(data?.data,this)
}
}
}
StatusUpdateFragment.kt : must add context at storeImage
```
fun storeImage(imageUri: Uri?, context: Context) {
if (imageUri != null && userId != null) {
try {
Toast.makeText(context, "Uploading...", Toast.LENGTH_SHORT).show()
lay_progressbar.visibility = View.VISIBLE
}
catch (e:Exception){
e.message
}
//more code hidden
}
```

ViewGroup will be null when came back from another fragment that we call from a current fragment in navigation component android

I used Navigation Component in my app. in one of my fragments (let's call it FragmentA) I have many fields. and in this fragment, I define a Radio Group for Visible/Gone in some fields. everything works perfectly when I came from HomeFragment into FragmentA, but when I go from FragmentA to another destination that is fragment too (and let's call it, for example, FragmentB) and handle all this with Navigation Component and then try back into again FragmentA, I got Null Pointer for view group as unknown Source with this message: Parameter specified as non-null is null. and this is my code for handle Visible/Gone fields.
private fun showChildren(v: View, isShow: Boolean) {
val viewGroup = v as ViewGroup
for (i in 0 until viewGroup.childCount) {
val v1 = viewGroup.getChildAt(i)
(v1 as? ViewGroup)?.let { showChildren(it, isShow) }
if (v1.tag == "check_for_visibility" && isShow) {
v1.visibility = View.VISIBLE
} else if (v1.tag == "check_for_visibility" && !isShow) {
v1.visibility = View.GONE
}
}
}
may please guide me on how I can handle this null pointer exception with ViewGroup when came back from FragmentB to FragmentA?
edit:
import android.content.Intent
import android.speech.RecognizerIntent
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
class AddPickupContinuousParentFragment :
BaseFragment<FragmentAddPickupContinuousParentBinding, AddPickupContinuousParentViewModel>(
R.layout.fragment_add_pickup_continuous_parent,
AddPickupContinuousParentViewModel()
) {
private var kindOfRentList: ArrayList<String> = arrayListOf()
private var selectedRent = ""
override fun initVariables() {
binding.addPickupContinuousParentViewModel = vModel
}
override fun initObserves() {
}
override fun initViews() {
val receivedWaybill =
arguments?.let { AddPickupContinuousParentFragmentArgs.fromBundle(it).waybill }
val receivedClosedArray =
arguments?.let { AddPickupContinuousParentFragmentArgs.fromBundle(it).closedArray }
if (receivedWaybill != null && receivedWaybill != "0") {
if (receivedWaybill.isNotEmpty()) {
binding.layoutCargo.etNewPickupWaybill.isEnabled = false
binding.layoutCargo.etNewPickupWaybill.setText(receivedWaybill)
}
}
if (receivedClosedArray != null) {
if (receivedClosedArray.isNotEmpty()) {
binding.layoutCargo.etNewPickupClosedCount.isEnabled = false
binding.layoutCargo.etNewPickupClosedCount.setText(receivedClosedArray.size.toString())
}
}
val countries: Array<out String> = resources.getStringArray(R.array.countries_array)
ArrayAdapter(
requireContext(),
android.R.layout.simple_list_item_1,
countries
).also {
binding.layoutSender.autoAddSenderStateCity.setAdapter(it)
binding.layoutReceiver.autoAddReceiverStateCity.setAdapter(it)
// spinner init
kindOfRentList.add("test1")
kindOfRentList.add("test2")
val kindOfRentAdapter =
ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, kindOfRentList)
kindOfRentAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
binding.layoutCargo.spinnerNewPickupKindRent.adapter =
kindOfRentAdapter
selectedRent = kindOfRentList[0]
binding.layoutCargo.spinnerNewPickupKindRent.onItemSelectedListener =
object : OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>,
view: View,
position: Int,
id: Long
) {
selectedRent =
binding.layoutCargo.spinnerNewPickupKindRent.selectedItem.toString()
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
// visible or gone fields
vModel.editTextVisibility.observe(
viewLifecycleOwner,
Observer {
if (it == true) {
binding.radioNewPickupNo.setTextColor(
ContextCompat.getColor(
requireContext(),
R.color.red
)
)
binding.radioNewPickupYes.setTextColor(
ContextCompat.getColor(
requireContext(),
R.color.lightGray
)
)
activity?.window?.decorView?.let { it1 ->
showChildren(it1, true)
}
} else {
binding.radioNewPickupNo.setTextColor(
ContextCompat.getColor(
requireContext(),
R.color.lightGray
)
)
binding.radioNewPickupYes.setTextColor(
ContextCompat.getColor(
requireContext(),
R.color.green
)
)
activity?.window?.decorView?.let { it1 -> showChildren(it1, false) }
}
})
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "fa");
binding.layoutSender.imgAddSenderName.setOnClickListener {
startActivityForResult(intent, 700)
}
binding.layoutSender.imgAddSenderAddress.setOnClickListener {
startActivityForResult(intent, 701)
}
binding.layoutSender.imgAddSenderCompany.setOnClickListener {
startActivityForResult(intent, 702)
}
binding.layoutReceiver.imgAddReceiverName.setOnClickListener {
startActivityForResult(intent, 703)
}
binding.layoutReceiver.imgAddReceiverAddress.setOnClickListener {
startActivityForResult(intent, 704)
}
binding.layoutReceiver.imgAddReceiverCompany.setOnClickListener {
startActivityForResult(intent, 705)
}
binding.btnAddPickupRegister.setOnClickListener {
findNavController().navigate(R.id.action_addPickupContinuousParentFragment_to_finalizeCargoFragment)
}
}
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
when (requestCode) {
700 -> {
try {
if (data != null) {
val result: String? = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS
)[0]
binding.layoutSender.etAddSenderName.setText(result)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
701 -> {
try {
if (data != null) {
val result: String? = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS
)[0]
binding.layoutSender.etAddSenderAddress.setText(result)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
702 -> {
try {
if (data != null) {
val result: String? = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS
)[0]
binding.layoutSender.etAddSenderCompany.setText(result)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
703 -> {
try {
if (data != null) {
val result: String? = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS
)[0]
binding.layoutReceiver.etAddReceiverName.setText(result)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
704 -> {
try {
if (data != null) {
val result: String? = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS
)[0]
binding.layoutReceiver.etAddReceiverAddress.setText(result)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
705 -> {
try {
if (data != null) {
val result: String? = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS
)[0]
binding.layoutReceiver.etAddReceiverCompany.setText(result)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
private fun showChildren(v: View, isShow: Boolean) {
try {
val viewGroup = v as ViewGroup
for (i in 0 until viewGroup.childCount) {
val v1 = viewGroup.getChildAt(i)
(v1 as? ViewGroup)?.let { showChildren(it, isShow) }
if (v1.tag == "check_for_visibility" && isShow) {
v1.visibility = View.VISIBLE
} else if (v1.tag == "check_for_visibility" && !isShow) {
v1.visibility = View.GONE
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}

Turn based multiplayer: createMatch() returns false task

When I call createMatch() on TurnBasedMultiplayerClient the task that it returns is false(task.isSuccessful) and the exception I get is com.google.android.gms.common.api.ApiException: 26502: CLIENT_RECONNECT_REQUIRED.
The documentation says that the GoogleApiClient is is in an inconsistent state but how do I reconnect it? I don't have a GoogleAPiClient object so I can't just call GoogleAPiClient.reconnect().
I'm using the default ui for selecting players:
private fun onStartMatchClicked() {
val allowAutoMatch = true
mTurnBasedMultiplayerClient = Games.getTurnBasedMultiplayerClient(this#MultiplayerActivity, clientAccount!!)
mTurnBasedMultiplayerClient!!.getSelectOpponentsIntent(1, 1, allowAutoMatch)
.addOnSuccessListener { intent -> startActivityForResult(intent, RC_SELECT_PLAYERS) }
}
Here's the onActivityResult method:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SELECT_PLAYERS) {
if (resultCode != Activity.RESULT_OK) {
finish()
return
}
val invitees = data!!.getStringArrayListExtra(Games.EXTRA_PLAYER_IDS)
// Get automatch criteria
var autoMatchCriteria: Bundle? = null
val minAutoPlayers = data.getIntExtra(Multiplayer.EXTRA_MIN_AUTOMATCH_PLAYERS, 0)
val maxAutoPlayers = data.getIntExtra(Multiplayer.EXTRA_MAX_AUTOMATCH_PLAYERS, 0)
autoMatchCriteria = RoomConfig.createAutoMatchCriteria(minAutoPlayers,
maxAutoPlayers, 0)
val tbmc = TurnBasedMatchConfig.builder()
.addInvitedPlayers(invitees)
.setAutoMatchCriteria(autoMatchCriteria).build()
mTurnBasedMultiplayerClient!!.createMatch(tbmc).addOnCompleteListener { task ->
if (task.isSuccessful) { //this is where I get the exception
match = task.result
} else {
// There was an error. Show the error.
var status = CommonStatusCodes.DEVELOPER_ERROR
val exception = task.exception
if (exception is ApiException) {
val apiException = exception as ApiException?
status = apiException!!.statusCode
}
handleError(status, exception)
}
}
}
}

Categories

Resources