I have already tried invalidating caches. Clean build and rebuild project also done.
But I still keep getting unresolved reference: with
I'm using the Picasso library and my other activities are working fine. Picasso library has been implemented in the gradle.
The language version is 1.2 Android Studio
Code:
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import chatonapp.project.com.chatonapp.R
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.*
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import com.google.firebase.storage.UploadTask
import com.squareup.picasso.Picasso
import com.theartofdev.edmodo.cropper.CropImage
import id.zelory.compressor.Compressor
import kotlinx.android.synthetic.main.activity_settings.*
import java.io.ByteArrayOutputStream
import java.io.File
class SettingsActivity : AppCompatActivity() {
var mDatabase: DatabaseReference? = null
var mCurrentUser: FirebaseUser? = null
var mStorageRef: StorageReference? = null
var GALLERY_ID: Int = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
mCurrentUser = FirebaseAuth.getInstance().currentUser
mStorageRef = FirebaseStorage.getInstance().reference
var userId = mCurrentUser!!.uid
mDatabase = FirebaseDatabase.getInstance().reference
.child("Users")
.child(userId)
mDatabase!!.addValueEventListener(object : ValueEventListener{
override fun onDataChange(dataSnapshot: DataSnapshot?) {
var displayName = dataSnapshot!!.child("display_name").value
var image = dataSnapshot!!.child("image").value.toString()
var userStatus = dataSnapshot!!.child("status").value
var thumbnail = dataSnapshot!!.child("thumb_image").value
settinsDisplayName.text = displayName.toString()
settingsStatusText.text = userStatus.toString()
if (!image!!.equals("default")) {
Picasso.with(applicationContext)
.load(image)
.placeholder(R.drawable.profile_img)
.into(settingsProfileID)
}
}
override fun onCancelled(databaseErrorSnapshot: DatabaseError?) {
}
})
settingsChangeStatus.setOnClickListener {
var intent = Intent(this, StatusActivity::class.java)
intent.putExtra("status", settingsStatusText.text.toString().trim())
startActivity(intent)
}
settingsChangeImgBtn.setOnClickListener {
var galleryIntent = Intent()
galleryIntent.type = "image/*"
galleryIntent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(Intent.createChooser(galleryIntent, "SELECT_IMAGE"), GALLERY_ID)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == GALLERY_ID
&& resultCode == Activity.RESULT_OK) {
var image: Uri = data!!.data
CropImage.activity(image)
.setAspectRatio(1, 1)
.start(this)
}
if (requestCode === CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
val result = CropImage.getActivityResult(data)
if (resultCode === Activity.RESULT_OK) {
val resultUri = result.uri
var userId = mCurrentUser!!.uid
var thumbFile = File(resultUri.path)
var thumbBitmap = Compressor(this)
.setMaxWidth(200)
.setMaxHeight(200)
.setQuality(65)
.compressToBitmap(thumbFile)
var byteArray = ByteArrayOutputStream()
thumbBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
byteArray)
var thumbByteArray: ByteArray
thumbByteArray = byteArray.toByteArray()
var filePath = mStorageRef!!.child("chat_profile_images")
.child(userId + ".jpg")
//Create another directory for thumbimages ( smaller, compressed images)
var thumbFilePath = mStorageRef!!.child("chat_profile_images")
.child("thumbs")
.child(userId + ".jpg")
filePath.putFile(resultUri)
.addOnCompleteListener{
task: Task<UploadTask.TaskSnapshot> ->
if (task.isSuccessful) {
var donwloadUrl = task.result.downloadUrl.toString()
var uploadTask: UploadTask = thumbFilePath
.putBytes(thumbByteArray)
uploadTask.addOnCompleteListener{
task: Task<UploadTask.TaskSnapshot> ->
var thumbUrl = task.result.downloadUrl.toString()
if (task.isSuccessful) {
var updateObj = HashMap<String, Any>()
updateObj.put("image", donwloadUrl)
updateObj.put("thumb_image", thumbUrl)
mDatabase!!.updateChildren(updateObj)
.addOnCompleteListener {
task: Task<Void> ->
if (task.isSuccessful) {
Toast.makeText(this, "Profile Image Saved!",
Toast.LENGTH_LONG)
.show()
}else {
}
}
}else {
}
}
}
}
}else if (resultCode === CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
val error = result.error
Log.d("Error", error.toString())
}
}
}
}
The problem happens here: Picasso.with
if (!image!!.equals("default")) {
Picasso.with(applicationContext)
.load(image)
.placeholder(R.drawable.profile_img)
.into(settingsProfileID)
}
How can I resolve this?
I had the same problem tonight, After looking at the Picasso site I noticed that .with is not used anymore. .get() works fine. Try something like this.
Picasso.get()
.load(url)
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.user_placeholder_error)
.into(imageView);
My code looked like this
val thumbnailImage = holder.view.imageView_Video_Thumbnail
Picasso.get().load(movieTitle.imageUrl).into(thumbnailImage)
Hope that helps someone.
Related
I am getting the following error as show in the screenshot,please help me to solve the error related to the tensorflow lite.
[i was following this tutorial on youtube][1]
Iam not getting why the error is occurring as the code in the tutorial runs well.
thankyou
Below is the code where I am getting the following error.
package com.example.machineleaarningapp
import android.app.Activity
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.example.machineleaarningapp.databinding.ActivityMainBinding
import com.example.machineleaarningapp.ml.Birdmodel2
import java.io.IOException
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var imageView: ImageView
private lateinit var button: Button
private lateinit var tvOutput: TextView
private val GALLERY_REQUEST_CODE = 123
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
imageView = binding.imageView
button = binding.btnCaptureImage
tvOutput = binding.tvOutput
val buttonLoad = binding.btnLoadImage
button.setOnClickListener {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED
) {
takePicturePreview.launch(null)
}
else {
requestPermission.launch(android.Manifest.permission.CAMERA)
}
}
buttonLoad.setOnClickListener {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED){
val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
intent.type = "image/*"
val mimeTypes = arrayOf("image/jpeg","image/png","image/jpg")
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
onresult.launch(intent)
}else {
requestPermission.launch(android.Manifest.permission.READ_EXTERNAL_STORAGE)
}
}
//to redirct user to google search for the scientific name
tvOutput.setOnClickListener {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com/search?q=${tvOutput.text}"))
startActivity(intent)
}
// to download image when longPress on ImageView
imageView.setOnLongClickListener {
requestPermissionLauncher.launch(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
return#setOnLongClickListener true
}
}
//request camera permission
private val requestPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()){granted->
if (granted){
takePicturePreview.launch(null)
}else {
Toast.makeText(this, "Permission Denied !! Try again", Toast.LENGTH_SHORT).show()
}
}
//launch camera and take picture
private val takePicturePreview = registerForActivityResult(ActivityResultContracts.TakePicturePreview()){bitmap->
if(bitmap != null){
imageView.setImageBitmap(bitmap)
outputGenerator(bitmap)
}
}
//to get image from gallery
private val onresult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){result->
Log.i("TAG", "This is the result: ${result.data} ${result.resultCode}")
onResultReceived(GALLERY_REQUEST_CODE,result)
}
private fun onResultReceived(requestCode: Int, result: ActivityResult?){
when(requestCode){
GALLERY_REQUEST_CODE ->{
if (result?.resultCode == Activity.RESULT_OK){
result.data?.data?.let{uri ->
Log.i("TAG", "onResultReceived: $uri")
val bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(uri))
imageView.setImageBitmap(bitmap)
outputGenerator(bitmap)
}
}else {
Log.e("TAG", "onActivityResult: error in selecting image")
}
}
}
}
private fun outputGenerator(bitmap: Bitmap){
//declearing tensor flow lite model variable
val birdsModel = Birdmodel2.newInstance(this)
// converting bitmap into tensor flow image
val newBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true)
val tfimage = TensorImage.fromBitmap(newBitmap)
//process the image using trained model and sort it in descending order
val outputs = birdsModel.process(tfimage)
.probabilityAsCategoryList.apply {
sortByDescending { it.score }
}
//getting result having high probability
val highProbabilityOutput = outputs[0]
//setting ouput text
tvOutput.text = highProbabilityOutput.label
Log.i("TAG", "outputGenerator: $highProbabilityOutput")
}
// to download image to device
private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()){
isGranted: Boolean ->
if (isGranted){
AlertDialog.Builder(this).setTitle("Download Image?")
.setMessage("Do you want to download this image to your device?")
.setPositiveButton("Yes"){_, _ ->
val drawable:BitmapDrawable = imageView.drawable as BitmapDrawable
val bitmap = drawable.bitmap
downloadImage(bitmap)
}
.setNegativeButton("No") {dialog, _ ->
dialog.dismiss()
}
.show()
}else {
Toast.makeText(this, "Please allow permission to download image", Toast.LENGTH_LONG).show()
}
}
//fun that takes a bitmap and store to user's device
private fun downloadImage(mBitmap: Bitmap):Uri? {
val contentValues = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME,"Birds_Images"+ System.currentTimeMillis()/1000)
put(MediaStore.Images.Media.MIME_TYPE,"image/png")
}
val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
if (uri != null){
contentResolver.insert(uri, contentValues)?.also {
contentResolver.openOutputStream(it).use { outputStream ->
if (!mBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)){
throw IOException("Couldn't save the bitmap")
}
else{
Toast.makeText(applicationContext, "Image Saved", Toast.LENGTH_LONG).show()
}
}
return it
}
}
return null
}
}
```[These are the errors I am getting][2]
[1]: https://www.youtube.com/watch?v=hsSPb6V84zc&t=1034s
[2]: https://i.stack.imgur.com/GsmBW.png
I am trying to get a users profile pic to be displayed beside their booking on a card in my recyclerview. The profile pic is displaying in my nav drawer, a default one for non-google users, or the profile pic of the Google user. However imageUri appears empty when I call it and the images are not being stored in my firebase storage bucket. I have linked my firebase and implemented the relevant SDK.
Here is my model.
#Parcelize
data class BookModel(
// var id : Long = 0,
var uid: String? = "",
var name: String = "N/A",
var phoneNumber: String = "N/A",
var email: String? = "N/A",
var date: String = "",
var bike: Int = 0,
var profilepic: String = "",
/*var lat: Double = 0.0,
var longitude: Double = 0.0,
var zoom: Float = 0f,*/
var pickup: String = "",
var dropoff: String = "",
var price: Double = 20.0,
/*var amount: Int = 0*/
) : Parcelable
{
#Exclude
fun toMap(): Map<String, Any?> {
return mapOf(
// "id" to id,
"uid" to uid,
"name" to name,
"phoneNumber" to phoneNumber,
"email" to email,
"date" to date,
"bike" to bike,
"profilepic" to profilepic,
"pickup" to pickup,
"dropoff" to dropoff,
"price" to price
)
}
}
#Parcelize
data class Location(
var lat: Double = 0.0,
var longitude: Double = 0.0,
var zoom: Float = 0f,
var depot: String = "Waterford"
) : Parcelable
Here is my FirebaseImageManager
package com.wit.mad2bikeshop.firebase
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import android.widget.ImageView
import androidx.lifecycle.MutableLiveData
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.UploadTask
import com.squareup.picasso.MemoryPolicy
import com.squareup.picasso.Picasso
import com.wit.mad2bikeshop.utils.customTransformation
import timber.log.Timber
import java.io.ByteArrayOutputStream
import com.squareup.picasso.Target
object FirebaseImageManager {
var storage = FirebaseStorage.getInstance().reference
var imageUri = MutableLiveData<Uri>()
fun checkStorageForExistingProfilePic(userid: String) {
val imageRef = storage.child("photos").child("${userid}.jpg")
val defaultImageRef = storage.child("ic_book_nav_header.png")
imageRef.metadata.addOnSuccessListener { //File Exists
imageRef.downloadUrl.addOnCompleteListener { task ->
imageUri.value = task.result!!
}
//File Doesn't Exist
}.addOnFailureListener {
imageUri.value = Uri.EMPTY
}
}
fun uploadImageToFirebase(userid: String, bitmap: Bitmap, updating : Boolean) {
// Get the data from an ImageView as bytes
val imageRef = storage.child("photos").child("${userid}.jpg")
//val bitmap = (imageView as BitmapDrawable).bitmap
val baos = ByteArrayOutputStream()
lateinit var uploadTask: UploadTask
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val data = baos.toByteArray()
imageRef.metadata.addOnSuccessListener { //File Exists
if(updating) // Update existing Image
{
uploadTask = imageRef.putBytes(data)
uploadTask.addOnSuccessListener { ut ->
ut.metadata!!.reference!!.downloadUrl.addOnCompleteListener { task ->
imageUri.value = task.result!!
}
}
}
}.addOnFailureListener { //File Doesn't Exist
uploadTask = imageRef.putBytes(data)
uploadTask.addOnSuccessListener { ut ->
ut.metadata!!.reference!!.downloadUrl.addOnCompleteListener { task ->
imageUri.value = task.result!!
}
}
}
}
fun updateUserImage(userid: String, imageUri : Uri?, imageView: ImageView, updating : Boolean) {
Picasso.get().load(imageUri)
.resize(200, 200)
.transform(customTransformation())
.memoryPolicy(MemoryPolicy.NO_CACHE)
.centerCrop()
.into(object : Target {
override fun onBitmapLoaded(bitmap: Bitmap?,
from: Picasso.LoadedFrom?
) {
Timber.i("DX onBitmapLoaded $bitmap")
uploadImageToFirebase(userid, bitmap!!,updating)
imageView.setImageBitmap(bitmap)
}
override fun onBitmapFailed(e: java.lang.Exception?,
errorDrawable: Drawable?) {
Timber.i("DX onBitmapFailed $e")
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {}
})
}
fun updateDefaultImage(userid: String, resource: Int, imageView: ImageView) {
Picasso.get().load(resource)
.into(object : Target {
override fun onBitmapLoaded(bitmap: Bitmap?,
from: Picasso.LoadedFrom?
) {
Timber.i("DX onBitmapLoaded $bitmap")
uploadImageToFirebase(userid, bitmap!!,false)
imageView.setImageBitmap(bitmap)
}
override fun onBitmapFailed(e: java.lang.Exception?,
errorDrawable: Drawable?) {
Timber.i("DX onBitmapFailed $e")
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {}
})
}
}
My FirebaseAuthManager...
package com.wit.mad2bikeshop.firebase
import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.GoogleAuthProvider
import com.wit.mad2bikeshop.R
import timber.log.Timber
class FirebaseAuthManager(application: Application) {
private var application: Application? = null
var firebaseAuth: FirebaseAuth? = null
var liveFirebaseUser = MutableLiveData<FirebaseUser>()
var loggedOut = MutableLiveData<Boolean>()
var errorStatus = MutableLiveData<Boolean>()
var googleSignInClient = MutableLiveData<GoogleSignInClient>()
init {
this.application = application
firebaseAuth = FirebaseAuth.getInstance()
if (firebaseAuth!!.currentUser != null) {
liveFirebaseUser.postValue(firebaseAuth!!.currentUser)
loggedOut.postValue(false)
errorStatus.postValue(false)
FirebaseImageManager.checkStorageForExistingProfilePic(
firebaseAuth!!.currentUser!!.uid)
}
configureGoogleSignIn()
}
fun login(email: String?, password: String?) {
firebaseAuth!!.signInWithEmailAndPassword(email!!, password!!)
.addOnCompleteListener(application!!.mainExecutor, { task ->
if (task.isSuccessful) {
liveFirebaseUser.postValue(firebaseAuth!!.currentUser)
errorStatus.postValue(false)
} else {
Timber.i("Login Failure: $task.exception!!.message")
errorStatus.postValue(true)
}
})
}
fun register(email: String?, password: String?) {
firebaseAuth!!.createUserWithEmailAndPassword(email!!, password!!)
.addOnCompleteListener(application!!.mainExecutor, { task ->
if (task.isSuccessful) {
liveFirebaseUser.postValue(firebaseAuth!!.currentUser)
errorStatus.postValue(false)
} else {
Timber.i("Registration Failure: $task.exception!!.message")
errorStatus.postValue(true)
}
})
}
fun logOut() {
firebaseAuth!!.signOut()
Timber.i( "firebaseAuth Signed out")
googleSignInClient.value!!.signOut()
Timber.i( "googleSignInClient Signed out")
loggedOut.postValue(true)
errorStatus.postValue(false)
}
private fun configureGoogleSignIn() {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(application!!.getString(R.string.default_web_client_id))
.requestEmail()
.build()
googleSignInClient.value = GoogleSignIn.getClient(application!!.applicationContext,gso)
}
fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) {
Timber.i( "DonationX firebaseAuthWithGoogle:" + acct.id!!)
val credential = GoogleAuthProvider.getCredential(acct.idToken, null)
firebaseAuth!!.signInWithCredential(credential)
.addOnCompleteListener(application!!.mainExecutor) { task ->
if (task.isSuccessful) {
// Sign in success, update with the signed-in user's information
Timber.i( "signInWithCredential:success")
liveFirebaseUser.postValue(firebaseAuth!!.currentUser)
} else {
// If sign in fails, display a message to the user.
Timber.i( "signInWithCredential:failure $task.exception")
errorStatus.postValue(true)
}
}
}
}
My Home activity
package com.wit.mad2bikeshop.ui.home
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.*
import com.google.firebase.auth.FirebaseUser
import com.squareup.picasso.Picasso
import com.wit.mad2bikeshop.R
import com.wit.mad2bikeshop.databinding.HomeBinding
import com.wit.mad2bikeshop.databinding.NavHeaderBinding
import com.wit.mad2bikeshop.firebase.FirebaseImageManager
import com.wit.mad2bikeshop.ui.auth.LoggedInViewModel
import com.wit.mad2bikeshop.ui.auth.Login
import com.wit.mad2bikeshop.utils.customTransformation
import timber.log.Timber
class Home : AppCompatActivity() {
private lateinit var drawerLayout: DrawerLayout
private lateinit var homeBinding: HomeBinding
private lateinit var navHeaderBinding: NavHeaderBinding
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var loggedInViewModel: LoggedInViewModel
private lateinit var headerView : View
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
homeBinding = HomeBinding.inflate(layoutInflater)
setContentView(homeBinding.root)
drawerLayout = homeBinding.drawerLayout
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val navHostFragment =
supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = AppBarConfiguration(
setOf(
R.id.bookFragment, R.id.bookingListFragment
), drawerLayout
)
setupActionBarWithNavController(navController, appBarConfiguration)
val navView = homeBinding.navView
navView.setupWithNavController(navController)
initNavHeader()
}
public override fun onStart() {
super.onStart()
loggedInViewModel = ViewModelProvider(this).get(LoggedInViewModel::class.java)
loggedInViewModel.liveFirebaseUser.observe(this, Observer { firebaseUser ->
if (firebaseUser != null)
updateNavHeader(firebaseUser)
})
loggedInViewModel.loggedOut.observe(this, Observer { loggedout ->
if (loggedout) {
startActivity(Intent(this, Login::class.java))
}
})
}
private fun initNavHeader() {
Timber.i("DX Init Nav Header")
headerView = homeBinding.navView.getHeaderView(0)
navHeaderBinding = NavHeaderBinding.bind(headerView)
}
private fun updateNavHeader(currentUser: FirebaseUser) {
FirebaseImageManager.imageUri.observe(this, { result ->
if(result == Uri.EMPTY) {
Timber.i("DX NO Existing imageUri")
if (currentUser.photoUrl != null) {
//if you're a google user
FirebaseImageManager.updateUserImage(
currentUser.uid,
currentUser.photoUrl,
navHeaderBinding.navHeaderImage,
false)
}
else
{
Timber.i("DX Loading Existing Default imageUri")
FirebaseImageManager.updateDefaultImage(
currentUser.uid,
R.drawable.ic_book_nav_header,
navHeaderBinding.navHeaderImage)
}
}
else // load existing image from firebase
{
Timber.i("DX Loading Existing imageUri")
FirebaseImageManager.updateUserImage(
currentUser.uid,
FirebaseImageManager.imageUri.value,
navHeaderBinding.navHeaderImage, false)
}
})
navHeaderBinding.navHeaderEmail.text = currentUser.email
if(currentUser.displayName != null)
navHeaderBinding.navHeaderName.text = currentUser.displayName
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment)
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
fun signOut(item: MenuItem) {
loggedInViewModel.logOut()
//Launch Login activity and clear the back stack to stop navigating back to the Home activity
val intent = Intent(this, Login::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
}
My BookViewModel
package com.wit.mad2bikeshop.ui.book
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.google.firebase.auth.FirebaseUser
import com.wit.mad2bikeshop.firebase.FirebaseDBManager
import com.wit.mad2bikeshop.firebase.FirebaseImageManager
import com.wit.mad2bikeshop.model.BookManager
import com.wit.mad2bikeshop.model.BookModel
class BookViewModel : ViewModel() {
private val status = MutableLiveData<Boolean>()
val observableStatus: LiveData<Boolean>
get() = status
fun addBook(firebaseUser: MutableLiveData<FirebaseUser>,
booking: BookModel) {
status.value = try {
booking.profilepic = FirebaseImageManager.imageUri.value.toString()
FirebaseDBManager.create(firebaseUser,booking)
true
} catch (e: IllegalArgumentException) {
false
}
}
// fun updateBook(booking: BookModel){
// status.value = try {
// BookManager.update(booking)
// true
// } catch (e: IllegalArgumentException) {
// false
// }
// }
}
My BookAdapter
package com.wit.mad2bikeshop.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.net.toUri
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.MemoryPolicy
import com.squareup.picasso.Picasso
import com.wit.mad2bikeshop.R
import com.wit.mad2bikeshop.databinding.CardBookBinding
import com.wit.mad2bikeshop.model.BookModel
import com.wit.mad2bikeshop.utils.customTransformation
interface BookListener {
// fun onDeleteBooking(booking: BookModel)
// fun onUpdateBooking(booking: BookModel)
fun onBookingClick(booking: BookModel)
}
class BookAdapter constructor(
private var bookings: ArrayList<BookModel>,
private val listener: BookListener,
private val readOnly: Boolean)
: RecyclerView.Adapter<BookAdapter.MainHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainHolder {
val binding = CardBookBinding
.inflate(LayoutInflater.from(parent.context), parent, false)
return MainHolder(binding, readOnly)
}
override fun onBindViewHolder(holder: MainHolder, position: Int) {
val booking = bookings[holder.adapterPosition]
holder.bind(booking, listener)
}
fun removeAt(position: Int) {
bookings.removeAt(position)
notifyItemRemoved(position)
}
override fun getItemCount(): Int = bookings.size
inner class MainHolder(val binding: CardBookBinding,private val readOnly : Boolean) :
RecyclerView.ViewHolder(binding.root) {
val readOnlyRow = readOnly
fun bind(booking: BookModel, listener: BookListener) {
binding.root.tag = booking
binding.booking = booking
binding.imageIcon.setImageResource(R.mipmap.ic_launcher_round)
Picasso.get().load(booking.profilepic.toUri())
.resize(200, 200)
.transform(customTransformation())
.centerCrop()
.into(binding.imageIcon)
//
// binding.name.text = booking.name
// binding.phoneNumber.text = booking.phoneNumber
// binding.date.text = booking.date
binding.root.setOnClickListener { listener.onBookingClick(booking) }
// binding.buttonDelete.setOnClickListener { listener.onDeleteBooking(booking) }
// binding.buttonUpdate.setOnClickListener { listener.onUpdateBooking(booking) }
binding.executePendingBindings()
/* binding.imageIcon.setImageResource(R.mipmap.ic_launcher_round)*/
}
}
}
I believe the problem stems from the (FirebaseImageManager.imageUri.value.toString()) on my BookAdapter, as if I run a Timber.I statement it doesn't return anything at all. If I run Timber.i(FirebaseImageManager.imageUri.value.toString()+ "test"), it only returns test.
Here is a link to the full project https://github.com/foxxxxxxx7/MAD2bikeshop
Apologies if I wasn't clear enough, I am a novice.
I figured it out, I had to modify my rules on the firebase storage.
Here I'm trying to upload an image from the local storage to the firebase storage.
I'm uploading the image using its URI
package com.example.demochat
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.storage.FirebaseStorage
import java.util.*
class RegisterActivity : AppCompatActivity() {
private lateinit var username: EditText
private lateinit var email: EditText
private lateinit var password: EditText
private lateinit var register: Button
private lateinit var haveAccount: TextView
private lateinit var imageInsert: Button
private lateinit var imageView: ImageView
private val tag: String = "RegisterActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
username = findViewById(R.id.editTextUsername)
email = findViewById(R.id.editTextTextEmailAddress)
password = findViewById(R.id.editTextTextPassword)
register = findViewById(R.id.buttonRegister)
haveAccount = findViewById(R.id.textViewAlready_have_an_account)
imageInsert = findViewById(R.id.buttonInsertImage)
imageView = findViewById(R.id.imageViewImageInsert)
imageInsert.setOnClickListener {
selectImage()
}
register.setOnClickListener {
performRegister()
}
haveAccount.setOnClickListener {
val intent = Intent(this#RegisterActivity, LoginActivity::class.java)
startActivity(intent)
}
}
private var selectedPhotoUri: Uri? = null
private fun selectImage() {
Log.d(tag, "clicked image button")
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(intent, 100)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 100 && resultCode == RESULT_OK && data != null && data.data != null) {
Toast.makeText(this#RegisterActivity, "clicked image selected", Toast.LENGTH_SHORT)
.show()
val selectedPhotoUri = data.data
Toast.makeText(this#RegisterActivity, "$selectedPhotoUri", Toast.LENGTH_SHORT).show()
imageView.setImageURI(selectedPhotoUri)
}
}
private fun performRegister() {
if (email.text.isEmpty() || password.text.isEmpty()) {
Toast.makeText(this, "Fill the above details", Toast.LENGTH_SHORT).show()
return
}
FirebaseAuth.getInstance()
.createUserWithEmailAndPassword(email.text.toString(), password.text.toString())
.addOnCompleteListener {
if (!it.isSuccessful) return#addOnCompleteListener
Log.d(tag, "uid = ${it.result?.user?.uid}")
uploadImageToFirebase()
}
.addOnFailureListener {
Toast.makeText(this, "${it.message}", Toast.LENGTH_SHORT).show()
Log.d(tag, "${it.message}")
}
}
private fun uploadImageToFirebase() {
if (selectedPhotoUri == null) return
val fileName = UUID.randomUUID().toString() + ".jpg"
val refStorage = FirebaseStorage.getInstance().reference.child("/images/$fileName")
refStorage.putFile(selectedPhotoUri!!)
.addOnSuccessListener {
Log.d(tag, "image uploaded")
}
.addOnFailureListener {
Log.d("RegisterActivity", "${it.message}")
}
}
}
following is the rules for the firebase stroage
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
firebase authentication part is working fine, users are added successfully. But I'm unable to upload an image. I have included internet permissions in the manifest file.
And I'm not getting any error message
So, please help
Here:
val selectedPhotoUri = data.data
you are not reassigning the global property selectedPhotoUri, but creating a new one.
Then, here:
if (selectedPhotoUri == null) return
you are checking with the global property which is always null.
I'm having a hard time getting an image URL from firebase storage, I got the photo URL from the database, but as I know, Glide can't get a picture from the link like this: com.google.firebase.storage.UploadTask#62873ce
Here are my Storage and database references:
private fun StorageReference.uploadUserPhoto(uid: String, photo: Uri,
onSuccess: (UploadTask.TaskSnapshot) -> Unit) {
child("users/$uid/photo").putFile(mImageUri).addOnCompleteListener {
if (it.isSuccessful) {
mStorage.child("users/$uid/photo").downloadUrl.addOnCompleteListener { task ->
if (it.isSuccessful) {
onSuccess(it.result!!)
} else {
showToast(it.exception!!.message!!)
}
}
}
}
}
private fun DatabaseReference.updateUserPhoto(uid: String, photoUrl: String,
onSuccess: () -> Unit){
child("users/$uid/photo").setValue(photoUrl)
.addOnCompleteListener {
if (it.isSuccessful) {
onSuccess()
} else {
showToast(it.exception!!.message!!)
}
}
}
here is the function:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == TAKE_PICTURE_REQUEST_CODE && resultCode == RESULT_OK) {
val uid = mAuth.currentUser!!.uid
mStorage.uploadUserPhoto(uid, mImageUri) {
val photoUrl = it.task.toString()
mDatabase.updateUserPhoto(uid, photoUrl) {
mUser = mUser.copy(photo = photoUrl)
profile_image.loadUserPhoto(mUser.photo)
}
}
}
}
I tried changing
val photoUrl = it.task.toString()
to
val photoUrl = it.downloadUrl.toString()
but it highlights 'downloadUrl' as unresolved reference
Full code:
package com.example.homeactivity.activities
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.text.Editable
import android.util.Log
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.example.homeactivity.R
import com.example.homeactivity.models.User
import com.example.homeactivity.views.PasswordDialog
import com.google.firebase.auth.AuthCredential
import com.google.firebase.auth.EmailAuthProvider
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import com.google.firebase.storage.UploadTask
import kotlinx.android.synthetic.main.activity_edit_profile.*
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
class EditProfileActivity : AppCompatActivity(), PasswordDialog.Listener {
private lateinit var mImageUri: Uri
private lateinit var mStorage: StorageReference
private val TAG = "EditProfileActivity"
private lateinit var mUser: com.example.homeactivity.models.User
private lateinit var mAuth: FirebaseAuth
private lateinit var mDatabase: DatabaseReference
private lateinit var mPendingUser: com.example.homeactivity.models.User
private val TAKE_PICTURE_REQUEST_CODE = 1
val simpleDateFormat = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_edit_profile)
Log.d(TAG, "onCreate")
close_image.setOnClickListener { finish() }
save_image.setOnClickListener { updateProfile() }
change_photo_text.setOnClickListener { takeCameraPicture() }
mAuth = FirebaseAuth.getInstance()
mDatabase = FirebaseDatabase.getInstance().reference
mStorage = FirebaseStorage.getInstance().reference
mDatabase.child("users").child(mAuth.currentUser!!.uid)
.addListenerForSingleValueEvent(ValueEventListenerAdapter {
mUser = it.getValue(com.example.homeactivity.models.User::class.java)!!
name_input.setText(mUser.name, TextView.BufferType.EDITABLE)
username_input.setText(mUser.username, TextView.BufferType.EDITABLE)
website_input.setText(mUser.website, TextView.BufferType.EDITABLE)
bio_input.setText(mUser.bio, TextView.BufferType.EDITABLE)
email_input.setText(mUser.email, TextView.BufferType.EDITABLE)
phone_input.setText(mUser.phone?.toString(), TextView.BufferType.EDITABLE)
profile_image.loadUserPhoto(mUser.photo)
})
}
private fun takeCameraPicture() {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (intent.resolveActivity(packageManager) != null) {
val imageFile = createImageFile()
mImageUri = FileProvider.getUriForFile(
this,
"com.example.homeactivity.fileprovider",
imageFile
)
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri)
startActivityForResult(intent, TAKE_PICTURE_REQUEST_CODE)
}
}
private fun createImageFile(): File {
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
"JPEG_${simpleDateFormat.format(Date())}_",
".jpg",
storageDir
)
}
#SuppressLint("MissingSuperCall")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == TAKE_PICTURE_REQUEST_CODE && resultCode == RESULT_OK) {
val uid = mAuth.currentUser!!.uid
mStorage.uploadUserPhoto(uid, mImageUri) {
val photoUrl = it.task.toString()
mDatabase.updateUserPhoto(uid, photoUrl) {
mUser = mUser.copy(photo = photoUrl)
profile_image.loadUserPhoto(mUser.photo)
}
}
}
}
private fun updateProfile() {
mPendingUser = readInputs()
val error = validate(mPendingUser)
if (error == null) {
if (mPendingUser.email == mUser.email) {
updateUser(mPendingUser)
} else {
PasswordDialog().show(supportFragmentManager, "password_dialog")
}
} else {
showToast(error)
}
}
private fun readInputs(): User {
return User(
name = name_input.text.toString(),
username = username_input.text.toString(),
email = email_input.text.toString(),
website = website_input.text.toStringOrNull(),
bio = bio_input.text.toStringOrNull(),
phone = phone_input.text.toStringOrNull()
)
}
override fun onPasswordConfirm(password: String) {
if (password.isNotEmpty()) {
val credential = EmailAuthProvider.getCredential(mUser.email, password)
mAuth.currentUser!!.reauthenticate(credential) {
mAuth.currentUser!!.updateEmail(mPendingUser.email) {
updateUser(mPendingUser)
}
}
} else {
showToast("You must enter your password")
}
}
private fun updateUser(user: com.example.homeactivity.models.User) {
val updatesMap = mutableMapOf<String, Any?>()
if (user.name != mUser.name) updatesMap["name"] = user.name
if (user.username != mUser.username) updatesMap["username"] = user.username
if (user.website != mUser.website) updatesMap["website"] = user.website
if (user.bio != mUser.bio) updatesMap["bio"] = user.bio
if (user.email != mUser.email) updatesMap["email"] = user.email
if (user.phone != mUser.phone) updatesMap["phone"] = user.phone
mDatabase.updateUser(mAuth.currentUser!!.uid, updatesMap) {
showToast("Profile saved")
finish()
}
}
private fun validate(user: com.example.homeactivity.models.User): String? =
when {
user.name.isEmpty() -> "Please enter name"
user.username.isEmpty() -> "Please enter username"
user.email.isEmpty() -> "Please enter email"
else -> null
}
private fun FirebaseUser.updateEmail(email: String, onSuccess: () -> Unit) {
updateEmail(email).addOnCompleteListener {
if (it.isSuccessful) {
onSuccess()
} else {
showToast(it.exception!!.message!!)
}
}
}
private fun StorageReference.uploadUserPhoto(uid: String, photo: Uri,
onSuccess: (UploadTask.TaskSnapshot) -> Unit) {
child("users/$uid/photo").putFile(mImageUri).addOnCompleteListener {
if (it.isSuccessful) {
mStorage.child("users/$uid/photo").downloadUrl.addOnCompleteListener { task ->
if (it.isSuccessful) {
onSuccess(it.result!!)
} else {
showToast(it.exception!!.message!!)
}
}
}
}
}
private fun DatabaseReference.updateUserPhoto(uid: String, photoUrl: String,
onSuccess: () -> Unit){
child("users/$uid/photo").setValue(photoUrl)
.addOnCompleteListener {
if (it.isSuccessful) {
onSuccess()
} else {
showToast(it.exception!!.message!!)
}
}
}
private fun DatabaseReference.updateUser(
uid: String, updates: Map<String, Any?>,
onSuccess: () -> Unit
) {
child("users").child(uid).updateChildren(updates)
.addOnCompleteListener {
if (it.isSuccessful) {
onSuccess()
} else {
showToast(it.exception!!.message!!)
}
}
}
private fun FirebaseUser.reauthenticate(credential: AuthCredential, onSuccess: () -> Unit) {
reauthenticate(credential).addOnCompleteListener {
if (it.isSuccessful) {
onSuccess()
} else {
showToast(it.exception!!.message!!)
}
}
}
}
Change your uploadUserPhoto method like this
private fun StorageReference.uploadUserPhoto(uid: String, photo: Uri,
onSuccess: (String) -> Unit) {
val uTask = mStorage.child("users/$uid/photo").putFile(mImageUri)
child("users/$uid/photo").putFile(mImageUri).addOnCompleteListener {
if (it.isSuccessful) {
uTask.continueWithTask { task ->
mStorage.child("users/$uid/photo").downloadUrl
}.addOnCompleteListener{
if (it.isSuccessful && it.result != null) {
onSuccess(it.result!!.toString)
} else {
showToast(it.exception!!.message!!)
}
}
}
}
}
In your onActivityResult use url like
val photoUrl = it
I have a problem using the method notifyDataSetChanged for a BaseAdapter. I think i don't really understand who it works. I want to add a new Item to the list of view to show a loading screen while an image is uploading. Once the image is uploaded, I remove the item and call the method but im receiving and error and I don't understand why.
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.support.v4.app.ActivityCompat
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Toast
import com.google.android.gms.tasks.OnSuccessListener
import com.google.android.gms.tasks.Task
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.google.firebase.storage.FirebaseStorage
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.add_ticket.*
import kotlinx.android.synthetic.main.add_ticket.view.*
import kotlinx.android.synthetic.main.tweets_ticket.view.*
import java.io.ByteArrayOutputStream
import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
class MainActivity : AppCompatActivity() {
private var listofTweets = ArrayList<Ticket>()
var adapter:TweetsAdapter? = null
private val PICK_IMG_CODE:Int = 123
var myEmail:String? = null
var downloadUrl:String? = null
private var database = FirebaseDatabase.getInstance()
private var myRef = database.reference
var userID:String? = null
private val READIMAGE:Int = 253
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var b:Bundle = intent.extras
myEmail = b.getString("email")
userID = b.getString("uid")
listofTweets.add(Ticket("1", "My first tweet", "", "add"))
listofTweets.add(Ticket("2", "My third tweet", "https://firebasestorage.googleapis.com/v0/b/fir-demoapp-8edf3.appspot.com/o/imagesPost%2F160819173436.jpg?alt=media&token=29ac687e-0936-49d8-a42f-50ab0e751208", "normal"))
//listofTweets.add(Ticket("3", "My fourth tweet", "gs://fir-demoapp-8edf3.appspot.com/imagesPost/160819173436.jpg", "normal"))
//listofTweets.add(Ticket("4", "My fifth tweet", "http://i.imgur.com/DvpvklR.png", "normal"))
var adapter = TweetsAdapter(this, listofTweets)
lvTweets.adapter = adapter
loadPost()
}
inner class TweetsAdapter:BaseAdapter{
var listOfTweetsAdapter = ArrayList<Ticket>()
var context:Context? = null
constructor(context:Context, listOfTweetsAdapter:ArrayList<Ticket>):super(){
this.context = context
this.listOfTweetsAdapter = listOfTweetsAdapter
}
override fun getCount(): Int {
return listofTweets.size
}
override fun getItem(p0: Int): Any {
return listofTweets[p0]
}
override fun getItemId(p0: Int): Long {
return p0.toLong()
}
override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
var tweet = listOfTweetsAdapter[p0]
if(tweet.tweetPersonUid.equals("add")) {
//Load add ticket
var myView = layoutInflater.inflate(R.layout.add_ticket, null)
myView.ivAttach.setOnClickListener {
//loadImage()
checkPermission()
}
myView.ivPost.setOnClickListener {
//Upload to the server
myRef.child("posts").push().setValue(
PostInfo(
userID.toString(), myView.etPost.text.toString(), downloadUrl.toString()
)
)
myView.etPost.setText("")
}
return myView
} else if (tweet.tweetPersonUid.equals("loading")) {
var myView = layoutInflater.inflate(R.layout.loading_ticket, null)
return myView
} else {
//Load tweet ticket
var myView = layoutInflater.inflate(R.layout.tweets_ticket, null)
myView.txt_tweet.setText(tweet.tweetText)
myView.txtUserName.setText(tweet.tweetPersonUid)
Picasso.get().load(tweet.tweetImageUrl).into(myView.tweet_picture)
myRef.child("Users").child(tweet.tweetPersonUid!!)
.addValueEventListener(object:ValueEventListener{
override fun onDataChange(p0: DataSnapshot) {
try {
var td = p0!!.value as HashMap<String, Any>
for (key in td.keys) {
var userInfo = td[key] as String
if(key.equals("profileImage")) {
Picasso.get().load(userInfo).into(myView.picture_path)
} else {
myView.txtUserName.setText(userInfo)
}
}
} catch (ex:Exception) {
}
}
override fun onCancelled(p0: DatabaseError) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
})
return myView
}
}
}
fun loadImage() {
var intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(intent, PICK_IMG_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == PICK_IMG_CODE && resultCode == Activity.RESULT_OK && data != null) {
val selectedImage = data.data
val filePathColumn = arrayOf(MediaStore.Images.Media.DATA)
val cursor = contentResolver.query(selectedImage, filePathColumn, null, null, null)
cursor.moveToFirst()
val columnIndex = cursor.getColumnIndex(filePathColumn[0])
val picturePath = cursor.getString(columnIndex)
cursor.close()
uploadImage(BitmapFactory.decodeFile(picturePath))
}
}
fun uploadImage(bitmap:Bitmap){
listofTweets.add(0, Ticket("0","him","url", "loading"))
adapter!!.notifyDataSetChanged()
val storage = FirebaseStorage.getInstance()
var storageRef = storage.getReferenceFromUrl("gs://fir-demoapp-8edf3.appspot.com/")
val df = SimpleDateFormat("ddMMyyHHmmss")
val dataObj = Date()
val imgPath = df.format(dataObj) + ".jpg"
val imgRef = storageRef.child("imagesPost/" + imgPath)
val baos = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val data = baos.toByteArray()
val uploadTask = imgRef.putBytes(data)
uploadTask.addOnFailureListener{
Toast.makeText(applicationContext, it.toString(), Toast.LENGTH_LONG).show()
}.addOnSuccessListener { taskSnapshot ->
imgRef.downloadUrl.addOnCompleteListener() {taskSnapshot ->
downloadUrl = taskSnapshot.result.toString()
//listofTweets.removeAt(0)
//adapter!!.notifyDataSetChanged()
}
}
}
fun loadPost(){
myRef.child("posts")
.addValueEventListener(object:ValueEventListener{
override fun onDataChange(p0: DataSnapshot) {
try {
listofTweets.clear()
listofTweets.add(Ticket("1", "My first tweet", "", "add"))
var td = p0!!.value as HashMap<String, Any>
for (key in td.keys) {
var post = td[key] as HashMap<String, Any>
listofTweets.add(
Ticket(key,
post["text"] as String,
post["img"] as String,
post["userUID"] as String)
)
}
adapter!!.notifyDataSetChanged()
} catch (ex:Exception) {
}
}
override fun onCancelled(p0: DatabaseError) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
})
}
fun checkPermission() {
if(Build.VERSION.SDK_INT >= 23) {
if(ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE), READIMAGE)
return
}
}
loadImage()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when(requestCode) {
READIMAGE -> {
if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {loadImage()}
else {Toast.makeText(this, "Cannot acces your images", Toast.LENGTH_LONG).show()}
} else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
}
And the error log is (line 172 is adapter!!.notifyDataSetChanged()):
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=123, result=-1, data=Intent { dat=content://com.google.android.apps.photos.contentprovider/-1/1/content://media/external/images/media/113490/ORIGINAL/NONE/549404385 flg=0x1 clip={text/uri-list U:content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F113490/ORIGINAL/NONE/549404385} }} to activity {com.example.twitter/com.example.startup.MainActivity}: kotlin.KotlinNullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:4363)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4405)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1811)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6694)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: kotlin.KotlinNullPointerException
at com.example.startup.MainActivity.uploadImage(MainActivity.kt:172)
at com.example.startup.MainActivity.onActivityResult(MainActivity.kt:165)
at android.app.Activity.dispatchActivityResult(Activity.java:7454)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4356)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4405)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1811)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6694)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Thanks in advance.
Your are getting a null pointer exception.
// You have this class member
var adapter:TweetsAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
// During on create, you are creating the adapter
// However, you are holding the adapter in a local variable
var adapter = TweetsAdapter(this, listofTweets)
}
fun uploadImage(bitmap:Bitmap){
// Then, here, when you try to read the adapter, you are reading
// the class member adapter (which is still null)
adapter!!.notifyDataSetChanged()
}
In order to fix the null pointer, update your onCreate method:
From:
var adapter = TweetsAdapter(this, listofTweets)
To:
this.adapter = TweetsAdapter(this, listofTweets)