I would like to ask about why run app, avatar of FirebaseUser's profilePhoto will disappear?
But if just login or logout, avatar of FirebaseUser's profilePhoto can retain status.
If I picked one photo from mobile storage to avatar, then logout and login, avatar still the same. But run app, avatar will disappear, why?
class ProfileFragment : Fragment() {
companion object {
val TAG = ProfileFragment::class.java.simpleName
val instance by lazy {
ProfileFragment()
}
var user:FirebaseUser? = null
private val REQUEST_CODE_CHOOSE_AVATAR: Int = 200
// var userPhotoUrl:Uri? = null
}
private lateinit var viewModel: ProfileViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.profile_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
retainInstance = true
viewModel = ViewModelProviders.of(this).get(ProfileViewModel::class.java)
// TODO: Use the ViewModel
user = FirebaseAuth.getInstance().currentUser
// userPhotoUrl = user?.photoUrl
Picasso.get()
.load(user?.photoUrl)
.placeholder(R.mipmap.ic_launcher)
.transform(CropCircleTransformation())
.into(avatar_url)
name.text = user?.displayName
avatar_url.setOnClickListener {
val intent = Intent().apply {
type = "image/*"
action = Intent.ACTION_GET_CONTENT
action = Intent.ACTION_PICK
}
startActivityForResult(Intent.createChooser(intent,"Choose avatar"),REQUEST_CODE_CHOOSE_AVATAR)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_CHOOSE_AVATAR) {
if (resultCode == RESULT_OK) {
if (data != null) {
// val user = FirebaseAuth.getInstance().currentUser
val uri = data.data
val userProfileChangeRequest = UserProfileChangeRequest.Builder()
.setPhotoUri(uri)
.build()
user?.updateProfile(userProfileChangeRequest)
?.addOnCompleteListener {
if (it.isSuccessful) {
Picasso.get()
.load(user?.photoUrl)
.transform(CropCircleTransformation())
.into(avatar_url)
FirebaseFirestore.getInstance()
.collection("uploadedImages")
.whereEqualTo("uid",user?.uid)
.addSnapshotListener { querySnapshot, firebaseFirestoreException ->
if (querySnapshot != null && !querySnapshot.isEmpty) {
for (doc in querySnapshot.documents) {
Log.d(TAG, "uploadedImages's doc: ${doc.data}");
doc.data?.set("avatarUrl", user?.photoUrl.toString())
}
} else {
firebaseFirestoreException.toString()
}
}
FirebaseFirestore.getInstance()
.collection("userData")
.document(user!!.uid)
.update("avatarUrl", user!!.photoUrl.toString())
}
}
}
}
}
}
}
Login and logout, avatar still retain
Why re-run app avatar will disappear?
Have solved the problem.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_CHOOSE_AVATAR) {
if (resultCode == RESULT_OK) {
if (data != null) {
// val user = FirebaseAuth.getInstance().currentUser
val uri = data.data
val avatarRef = FirebaseStorage.getInstance().reference
.child("userAvatar")
.child(user!!.uid)
.child(uri.toString())
avatarRef.putFile(uri!!)
.continueWithTask {
if (!it.isSuccessful) {
it.exception?.let {
throw it
}
}
avatarRef.downloadUrl
}.addOnCompleteListener {
if (it.isSuccessful) {
val avatarDownloadUrl = it.result
val userProfileChangeRequest = UserProfileChangeRequest.Builder()
.setPhotoUri(avatarDownloadUrl)
.build()
user?.updateProfile(userProfileChangeRequest)
?.addOnCompleteListener { it1 ->
if (it1.isSuccessful) {
Picasso.get()
.load(user?.photoUrl)
.transform(CropCircleTransformation())
.into(avatar_url)
Related
basically i have a fragment and in this fragment user can pick a image or use camera to take photo and i am taking the photo as uri and save to the local DB as string . And show the photo in this fragment.
This code works fine until i destroy my app in my xiaomi device. After i try to reach the uri from db and show in the fragment, app crashes. Btw this is not happening in emulator, everything is fine. I read some blogs and this could be happen in Mi devices but did not find a solution. The code;
class ProfilePageFragment : Fragment() {
private var _binding : FragmentProfilePageBinding? = null
private val binding get() = _binding!!
private lateinit var routineTasksViewModel: RoutineTasksViewModel
private var userName : String? = null
private var userProfilePhotoUri : String? = null
private lateinit var cameraPermissions : Array<String>
private lateinit var storagePermissions : Array<String>
private var imageUri : Uri? = null
private companion object {
private const val CAMERA_REQUEST_CODE = 100
private const val STORAGE_REQUEST_CODE = 101
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentProfilePageBinding.inflate(layoutInflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
routineTasksViewModel = (activity as MainActivity).routineTasksViewModel
cameraPermissions = arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
storagePermissions = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)
getUserProfileInformations()
binding.apply {
profilePhotoIV.setOnClickListener{
showInputImageDialog()
}
}
}
//popUp menu and item click funcs
private fun showInputImageDialog() {
val popUpMenu = PopupMenu(requireContext(),binding.profilePhotoIV)
popUpMenu.menu.add(Menu.NONE,1,1, R.string.camera)
popUpMenu.menu.add(Menu.NONE,2,2, R.string.gallery)
popUpMenu.show()
popUpMenu.setOnMenuItemClickListener { menuItem ->
val id = menuItem.itemId
if (id ==1){
if (checkCameraPermission()){
pickImageCamera()
}else{
requestCameraPermission()
}
}else if(id == 2){
if (checkStoragePermission()){
pickImageGallery()
}else{
requestStoragePermission()
}
}
return#setOnMenuItemClickListener true
}
}
//two funcs check the permissions
private fun checkStoragePermission() : Boolean { //permissionGranted -> true
return ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
}
private fun checkCameraPermission() : Boolean{ //permissionGranted -> true
val cameraResult = ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
val storageResult = ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
return cameraResult && storageResult
}
//
private fun pickImageGallery(){
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
galleryActivityResultLauncher.launch(intent)
}
private fun pickImageCamera(){
val values = ContentValues()
values.put(MediaStore.Images.Media.TITLE, "Sample Title")
values.put(MediaStore.Images.Media.DESCRIPTION, "Sample Description")
imageUri = activity?.contentResolver?.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
cameraActivityResultLauncher.launch(intent)
}
//launcher to camera
private val cameraActivityResultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result ->
if ( result.resultCode == Activity.RESULT_OK){
//image came from camera
binding.profilePhotoIV.setImageURI(imageUri)
updateProfilePhotoToDB(imageUri)
}else{
//Toast.makeText(requireContext(), R.string.permissions_required, Toast.LENGTH_SHORT).show()
}
}
//launcher to gallery
private val galleryActivityResultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result ->
if ( result.resultCode == Activity.RESULT_OK){
val data = result.data
imageUri = data!!.data
binding.profilePhotoIV.setImageURI(imageUri)
updateProfilePhotoToDB(imageUri)
}else{
//Toast.makeText(requireContext(), R.string.permissions_required, Toast.LENGTH_SHORT).show()
}
}
private fun requestStoragePermission() {
ActivityCompat.requestPermissions(requireActivity(),storagePermissions, STORAGE_REQUEST_CODE)
}
private fun requestCameraPermission() {
ActivityCompat.requestPermissions(requireActivity(),cameraPermissions, CAMERA_REQUEST_CODE)
}
//when we request to take permission, according to request code pickImageCamera or pickImageGallery will work.
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode){
CAMERA_REQUEST_CODE -> {
if (grantResults.isNotEmpty()){
val cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED
val storageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED
if (cameraAccepted && storageAccepted){
pickImageCamera()
}
}
}
STORAGE_REQUEST_CODE -> {
if (grantResults.isNotEmpty()){
val storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED
if (storageAccepted){
pickImageGallery()
}
}
}
}
}
}
I've recently started programming in Kotlin and cannot seem to add a profile picture to a user when registering it.
According to the code here, I can access to the gallery and retrieve the image information. The picture will appear on screen, but after registering the user the image url will not appear anywhere.
class RegisterUser : AppCompatActivity() {
private val database = FirebaseDatabase.getInstance()
private val auth: FirebaseAuth = FirebaseAuth.getInstance()
private val UserCreation = database.getReference("Usuarios")
private val pickImage = 100
private var imageUri: Uri? = null
lateinit var imageView: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register_user)
Goback.setOnClickListener {
val Gobackou = Intent(this, MainActivity::class.java)
startActivity(Gobackou)
}
RegisterConfirm.setOnClickListener {
val SetUser = SetUser.text.toString()
val SetPass = setPass.text.toString()
val SetEmail = SetEmail.text.toString()
if (SetUser.isEmpty() && SetPass.isEmpty() && SetEmail.isEmpty()) {
Toast.makeText(this, "Faltan Campos", Toast.LENGTH_SHORT).show()
} else {
RegisterUserv2(SetEmail, SetPass, SetUser)
}
}
selectPP.setOnClickListener {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, pickImage)
}
}
var selectedPhotoUri: Uri? = null
//guardar la foto de perfil
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK && requestCode == pickImage) {
val selectedPhotoUri = data?.data
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, selectedPhotoUri)
val bitmapDrawable = BitmapDrawable(bitmap)
userimg.setBackgroundDrawable(bitmapDrawable)
}
}
private fun RegisterUserv2(email: String, password: String, user: String) {
auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
uploadimage()
UltrasaveUsuario(Usuarios(auth.currentUser!!.uid, user, password, email))
val Gobackou = Intent(this, MainActivity::class.java)
startActivity(Gobackou)
} else {
Toast.makeText(this, "Registro ERROR", Toast.LENGTH_LONG).show()
}
}
}
private fun UltrasaveUsuario(usuario: Usuarios) {
val mensajeFirebase = UserCreation.push()
usuario.id = mensajeFirebase.key ?: ""
mensajeFirebase.setValue(usuario)
}
private fun uploadimage(imageurl: String){
if (selectedPhotoUri == null) return
val filename = UUID.randomUUID().toString()
val ref = FirebaseStorage.getInstance().getReference("/images/$filename/")
ref.putFile(selectedPhotoUri!!)
.addOnSuccessListener {
ref.downloadUrl.addOnSuccessListener{
}
}
}
}
Since you are using firebase I will show you how to save firebase storage.
private fun uploadImage() {
if (mSelectedImageFileUri != null) {
val sRef: StorageReference = FirebaseStorage.getInstance().reference.child(
"users/ $uid/profile.jpg"
)
sRef.putFile(mSelectedImageFileUri!!)
.addOnSuccessListener { taskSnapshot ->
taskSnapshot.metadata!!.reference!!.downloadUrl
.addOnSuccessListener { url ->
}
}.addOnFailureListener {
//error
}
} else {
}
}
then you will take this picture using the user id to take .
firebase>storage to view the image
getImage
val sRef: StorageReference = FirebaseStorage.getInstance().reference.child(
"users/ $uid/profile.jpg"
)
sRef.downloadUrl.addOnSuccessListener {
Picasso.get().load(it).into(globalprofileImage)
}
Build.gradle
implementation 'com.squareup.picasso:picasso:2.71828'
https://www.youtube.com/watch?v=nNYLQcmB7AU&t=449s&ab_channel=SmallAcademy
excuse me, in this code I want to send data into the database through registerReseller API. when I run this code with the virtual device, it works perfectly. while I run this code with real device, it works as well but some real device doesn't work. when it doesn't work on some device, the app does not crash or force close but stays on that page. Is anybody know how to fix this? Thank you
class RegisterFotoResellerActivity : AppCompatActivity() {
companion object {
val IMAGE_REQUEST_CODE = 1000
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register_foto_reseller)
iv_addimage.setOnClickListener{
ImageChooser()
}
}
private fun getRealPathFromURIPath(contentURI: Uri, activity: Activity): String? {
val cursor: Cursor? = activity.contentResolver.query(contentURI, null, null, null, null)
return if (cursor == null) {
contentURI.path
} else {
cursor.moveToFirst()
val idx: Int = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
cursor.getString(idx)
}
}
private fun ImageChooser() {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, IMAGE_REQUEST_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == IMAGE_REQUEST_CODE && resultCode == RESULT_OK) {
val uri = data?.data
Glide.with(this)
.load(data?.data)
.apply(RequestOptions.circleCropTransform())
.into(iv_imageperson)
/*val uriPathHelper = URIPathHelper()
val filePath = uriPathHelper.getPath(this, uri!!)*/
//tv.setText(filePath)
btn_Verifikasi.setOnClickListener {
val filePath = uri?.let { getRealPathFromURIPath(it, this#RegisterFotoResellerActivity) }
val file = File(filePath!!)
val mFile: RequestBody = file.asRequestBody("image/*".toMediaTypeOrNull()) //membungkus file ke dalam request body
val body = MultipartBody.Part.createFormData("file", file.name, mFile)
val sharedPreferences = getSharedPreferences("sharedPrefs", android.content.Context.MODE_PRIVATE)
val savednohp = sharedPreferences.getString("nohp", null)
val savedpin = sharedPreferences.getString("pin", null)
val savednama = sharedPreferences.getString("namaReseller", null)
val alamatReseller = sharedPreferences.getString("alamatReseller", null)
val apiService = ApiService.getInstance().create(ApiEndpoint::class.java)
apiService.uploadimgreseller(body).enqueue(object : Callback<UploadImgResponse> {
override fun onResponse(call: Call<UploadImgResponse>, response: Response<UploadImgResponse>) {
val responseUpload = response.body()?.link.toString()
val apiService2 = ApiService.getInstance().create(ApiEndpoint::class.java)
apiService2.registerReseller( savednohp!!, savednama!!, responseUpload, alamatReseller!!, savedpin!!, 0)
.enqueue(object : Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
val sharedPreferencesLogin = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE)
val editor = sharedPreferencesLogin.edit()
editor.apply {
putString("login_nohp", savednohp)
putString("login_pin", savedpin)
putString("login_nama", savednama)
putString("login_alamat", alamatReseller)
putString("login_resplink", responseUpload)
putString("login_verified", 0.toString())
putString("login_key", "reseller")
}.apply()
val intent = Intent(this#RegisterFotoResellerActivity, Dashboard_user::class.java)
startActivity(intent)
finishAffinity()
}
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
Toast.makeText(this#RegisterFotoResellerActivity, "belum bisa", Toast.LENGTH_SHORT).show()
}
})
}
override fun onFailure(call: Call<UploadImgResponse>, t: Throwable) {
Log.d("TAG", "durung bisa kyeeehhh")
}
})
}
}
}
}
I make a mobile application using the "io fotoapparat" library and I want to create a document with a random id and in the document in the id field, add the document id, the photo we will take was updated in the firebase store and in the previously made about the same id in the receipt collection when taking a photo
link from which I took "io fotoapparat"
EDIT
add to firestore document
binding.button.setOnClickListener {
// Inflate the layout for this fragment
val biedronka = "biedronka"
val price = "20"
val img = " "
val identificator = " "
val from = biedronka
val value = price
val image = img
val idd = identificator
val db = Firebase.firestore
val data = hashMapOf(
"from" to from,
"value" to value,
"image" to image,
"id" to idd
)
db.collection("receipts")
.add(data)
.addOnSuccessListener { documentReference ->
Log.d(SCAN_DEBUG, "DocumentSnapshot written with ID: ${documentReference.id}")
db.collection("receipts")
.document(documentReference.id)
.update("id", documentReference.id)
.addOnSuccessListener {
}
}
.addOnFailureListener { e ->
Log.w(SCAN_DEBUG, "Error adding document", e)
}
}
2 add to storage and to document (doesnt work)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CAPTURE_IMAGE && resultCode == RESULT_OK) {
val uid = profileVm.user.value?.uid!!
val imageBitmap = data?.extras?.get("data") as Bitmap
val userImage = binding.userImg
val stream = ByteArrayOutputStream()
val result = imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)
val byteArray = stream.toByteArray()
if (result) profileVm.uploadUserPhoto(byteArray, "$uid.jpg")
}
}
repository to 2
fun uploadReceiptPhoto(bytes: ByteArray) {
storage.getReference("receipts")
.child("${docId}.jpg")
.putBytes(bytes)
.addOnCompleteListener{
Log.d(REPO_DEBUG, "COMPLETE UPLOAD PHOTO")
}
.addOnSuccessListener {
getReceiptPhotoDownloadUrl(it.storage)
}
.addOnFailureListener {
Log.d(REPO_DEBUG, it.message.toString())
}
}
private fun getReceiptPhotoDownloadUrl(storage: StorageReference) {
storage.downloadUrl
.addOnSuccessListener {
updateReceiptPhoto(it.toString())
}
.addOnFailureListener {
Log.d(REPO_DEBUG, it.message.toString())
}
}
private fun updateReceiptPhoto(url: String) {
cloud.collection("receipts")
.document(docId)
.update("image", url)
.addOnSuccessListener {
Log.d(REPO_DEBUG, "UPDATE USER PHOTO")
}
.addOnFailureListener {
Log.d(REPO_DEBUG, it.message.toString())
}
}
THE REST OF THE CODE (camera code "io fotoapparat" and take pictures)
class ScanFragment : Fragment(), OnReceiptsItemAdd {
private var _binding: FragmentScanBinding? = null
private val binding get() = _binding!!
private val scanVm by viewModels<ScanViewModel>()
private val SCAN_DEBUG = "SCAN_DEBUG"
private var fotoapparat: Fotoapparat? = null
private var fotoapparatState: FotoapparatState? = null
private var cameraStatus: CameraState? = null
private var flashState: FlashState? = null
private val permissions = arrayOf(Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = FragmentScanBinding.inflate(inflater, container, false)
createFotoapparat()
cameraStatus = CameraState.BACK
flashState = FlashState.OFF
fotoapparatState = FotoapparatState.OFF
binding.fabSwitchCamera.setOnClickListener {
switchCamera()
}
binding.fabFlash.setOnClickListener {
changeFlashState()
}
return binding.root
}
private fun createFotoapparat(){
val cameraView = binding.cameraView
fotoapparat = Fotoapparat(
context = requireContext(),
view = cameraView,
scaleType = ScaleType.CenterCrop,
lensPosition = back(),
logger = loggers(
logcat()
),
cameraErrorCallback = { error ->
println("Recorder errors: $error")
}
)
}
private fun changeFlashState() {
fotoapparat?.updateConfiguration(
CameraConfiguration(
flashMode = if(flashState == FlashState.TORCH) off() else torch()
)
)
flashState = if(flashState == FlashState.TORCH) FlashState.OFF
else FlashState.TORCH
}
private fun switchCamera() {
fotoapparat?.switchTo(
lensPosition = if (cameraStatus == CameraState.BACK) front() else back(),
cameraConfiguration = CameraConfiguration()
)
cameraStatus = if(cameraStatus == CameraState.BACK) CameraState.FRONT
else CameraState.BACK
}
private fun takePhoto() {
if (hasNoPermissions()) {
requestPermission()
}else{
fotoapparat
?.takePicture()
?.toBitmap()
}
}
override fun onStart() {
super.onStart()
if (hasNoPermissions()) {
requestPermission()
}else{
fotoapparat?.start()
fotoapparatState = FotoapparatState.ON
}
}
private fun hasNoPermissions(): Boolean{
return ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
}
private fun requestPermission(){
ActivityCompat.requestPermissions(requireActivity(), permissions,0)
}
override fun onStop() {
super.onStop()
fotoapparat?.stop()
FotoapparatState.OFF
}
}
enum class CameraState{
FRONT, BACK
}
enum class FlashState{
TORCH, OFF
}
enum class FotoapparatState{
ON, OFF
}
I can select a videos and images but i could not upload in my webview ,kotlin program.
webview.setWebChromeClient(object:WebChromeClient() {
override fun onShowFileChooser(webView:WebView, filePathCallback:ValueCallback<Array<Uri>>, fileChooserParams:FileChooserParams):Boolean {
var mFilePathCallback = filePathCallback
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.setType("*/*")
val PICKFILE_REQUEST_CODE = 100
startActivityForResult(intent, PICKFILE_REQUEST_CODE)
return true
}
})
fun onActivityResult(requestCode: Int, resultCode: Int,
intent: Intent,
mFilePathCallback: Any): Boolean {
var PICKFILE_REQUEST_CODE = null
if (requestCode == PICKFILE_REQUEST_CODE)
{
val result = if (intent == null || resultCode != RESULT_OK)
null
else
intent.getData()
val resultsArray = arrayOfNulls<Uri>(1)
resultsArray[0] = result
mFilePathCallback.onReceiveValue(resultsArray)
}
return true
}
You need add to your #Override onActivityResult
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_SELECT_FILE) {
if (null == uploadMessage) {
return
}
uploadMessage?.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode,data))
uploadMessage = null
}
}
but not inside of your "webview.setWebChromeClient(object:WebChromeClient()" hier doesnt override.
class MainActivity : AppCompatActivity() {
val TAG = "hellow web view"
val webURL: String = "https://www.google.com"
override fun onCreate(savedInstanceState: Bundle?): Unit {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) {
webview.restoreState(savedInstanceState)
// Log.i(TAG,"onCreate")
webview.webViewClient = WebViewClient()
webview.loadUrl(webURL)
webview.settings.javaScriptEnabled = true
webview.settings.builtInZoomControls = true
webview.settings.displayZoomControls = true
webview.settings.allowFileAccess = true
webview.settings.allowFileAccessFromFileURLs = true
webview.setWebChromeClient(object:WebChromeClient() {
override fun onShowFileChooser(webView:WebView, filePathCallback:ValueCallback<Array<Uri>>, fileChooserParams:FileChooserParams):Boolean {
var mFilePathCallback = filePathCallback
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.setType("*/*")
val PICKFILE_REQUEST_CODE = 100
startActivityForResult(intent, PICKFILE_REQUEST_CODE)
return true
}
})
fun onActivityResult(requestCode: Int, resultCode: Int,
intent: Intent,
mFilePathCallback: Any): Boolean {
var PICKFILE_REQUEST_CODE = null
if (requestCode == PICKFILE_REQUEST_CODE)
{
val result = if (intent == null || resultCode != RESULT_OK)
null
else
intent.getData()
val resultsArray = arrayOfNulls<Uri>(1)
resultsArray[0] = result
mFilePathCallback.onReceiveValue(resultsArray)
}
return true
}
webview.setDownloadListener(object : DownloadListener {
override fun onDownloadStart(url: String, userAgent: String,
contentDisposition: String, mimetype: String,
contentLength: Long) {
val request = DownloadManager.Request(Uri.parse(url))
request.allowScanningByMediaScanner()
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) //Notify client once download is completed!
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, mimetype)
val webview = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
webview.enqueue(request)
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show()
}
})
class webviewclient : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
webview.loadUrl("http://google.com")
return true
}
}
searchbtn.setOnClickListener({ (webview.loadUrl("https://www.google.com")) })
btn1.setOnClickListener({ (webview.goBack()) })
btn3.setOnClickListener({ (webview.goForward()) })
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
webview.goBack()
return true
}
return super.onKeyDown(keyCode, event)
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
webview.saveState(outState)
Log.i(TAG, "onSaveInstanceState")
}
override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
super.onRestoreInstanceState(savedInstanceState)
webview.restoreState(savedInstanceState)
Log.i(TAG, "onRestoreInstanceState")
}
private fun Any.onReceiveValue(resultsArray: Array<Uri?>) {}
}