I'm trying to upload a image to a server as taken from camera with FAN. I've tried to convert into PNG and JPEG and encoded to image but adding multipart file it always shows me errors
Here's a fragent of my code while trying.
After taken the photo:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
bitmap = data!!.extras!!["data"] as Bitmap?
encodeBitmap(bitmap)
}
super.onActivityResult(requestCode, resultCode, data)
}
The function to encode bitmap
private fun encodeBitmap(bitmap: Bitmap?){
val byteArrayOutputStream = ByteArrayOutputStream()
bitmap!!.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream)
val byteofimages = byteArrayOutputStream.toByteArray()
encodedimage = Base64.encodeToString(byteofimages, Base64.DEFAULT)
confirmarEntrega()
}
And the atempt to upload with FAN
private fun confirmarEntrega(){
val uploadURL ="http://192.168.1.229/sistema.com/API/upload.php"
val requestQueue = Volley.newRequestQueue(this)
val txtNombre = findViewById<TextView>(R.id.txtClientName)
val txtDireccion= findViewById<TextView>(R.id.txtDireccion)
val txtProducto = findViewById<TextView>(R.id.txtProducto)
val txtTelefono = findViewById<TextView>(R.id.txtTelefono)
val scannerTextview = findViewById<TextView>(R.id.scannerTextView)
val btnConfirmar = findViewById<Button>(R.id.btnConfirmar)
progressDialog!!.setMessage("Espere un segundo")
progressDialog!!.show()
AndroidNetworking.upload(uploadURL)
.addMultipartFile("image", encodedimage) //Here's where im lost
.setPriority(Priority.HIGH)
.build()
.setUploadProgressListener(object : UploadProgressListener{
override fun onProgress(bytesUploaded: Long, totalBytes: Long) {
}
})
.getAsJSONObject(object : JSONObjectRequestListener{
override fun onResponse(response: JSONObject?) {
}
override fun onError(anError: ANError?) {
}
})
}
Related
Using Kotlin in Android Studio, I created a form where user can fill in necessary details AND click an imageButton to launch the camera, take picture and submit the form. I want to add a validation where the user is prevented from submitting the form if they did not take a photo.
I have tried to validate by using imageButton.drawable == null but it did not display the error toast.
Here are the relevant parts of my codes:
class FormActivity : AppCompatActivity() {
var selectedPhotoUri : Uri? = null
companion object {
const val REQUEST_FROM_CAMERA = 1001
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_artactivity)
...
val imageButton = findViewById<ImageButton>(R.id.imageButton)
// launch camera
imageButton.setOnClickListener {
takePhotoUsingCamera()
}
val submitButton = findViewById<Button>(R.id.submitButton)
submitButton.setOnClickListener {
submitForm(userId.toString(), HRWAnswer, ResultAnswer)
}
}
private fun takePhotoUsingCamera(){
ImagePicker.with(this).cameraOnly()
.crop()
.start(REQUEST_FROM_CAMERA)
}
// to access the image captured
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
when (requestCode){
REQUEST_FROM_CAMERA -> {
selectedPhotoUri = data!!.data
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, selectedPhotoUri)
val bitmapDrawable = BitmapDrawable(bitmap)
val imageButton = findViewById<ImageButton>(R.id.imageButton)
imageButton.setImageDrawable(bitmapDrawable)
}
}
}
}
fun submitForm(userId : String, TestOption: String, ResultOption: String){
...
val imageButton = findViewById<ImageButton>(R.id.imageButton)
if (imageButton.drawable == null) {
Toast.makeText(this, "Image of your Test result is required!", Toast.LENGTH_LONG).show()
imageButton.requestFocus()
}
...
}
}
Check this may it helps you.
class FormActivity : AppCompatActivity() {
lateinit var imageButton : ImageButton//HERE YOU NEED TO ADD BUTTON.Dont add buttons initialization multiple time in once class.
var selectedPhotoUri : Uri? = null
companion object {
const val REQUEST_FROM_CAMERA = 1001
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_artactivity)
...
imageButton = findViewById<ImageButton>(R.id.imageButton)
// launch camera
imageButton.setOnClickListener {
takePhotoUsingCamera()
}
val submitButton = findViewById<Button>(R.id.submitButton)
submitButton.setOnClickListener {
submitForm(userId.toString(), HRWAnswer, ResultAnswer)
}
}
private fun takePhotoUsingCamera(){
ImagePicker.with(this).cameraOnly()
.crop()
.start(REQUEST_FROM_CAMERA)
}
// to access the image captured
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
when (requestCode){
REQUEST_FROM_CAMERA -> {
selectedPhotoUri = data!!.data
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, selectedPhotoUri)
val bitmapDrawable = BitmapDrawable(bitmap)
val imageButton = findViewById<ImageButton>(R.id.imageButton)
imageButton.setImageDrawable(bitmapDrawable)
}
}
}
}
fun submitForm(userId : String, TestOption: String, ResultOption: String){
...
if (imageButton.drawable == null) {
Toast.makeText(this, "Image of your Test result is required!", Toast.LENGTH_LONG).show()
imageButton.requestFocus()
}
...
}
}
as stated by Mike M. in the comment above, it will never be null due to its drawable set layout. i have changed my approach to achieve my target outcome.
Complete beginner, trying this on kotlin. I am trying to capture a photo and save it and then load it on room database. I also need tag the photo and load it according to that. But there is an error like "Caused by: java.lang.NullPointerException: findViewById(R.id.metin) must not be null". How I can solve it? Thanks in advance.
class MainActivity : AppCompatActivity() {
private val cameraRequest = 1888
lateinit var imageView: ImageView
lateinit var textbox : EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var dao_object = ImageDatabase.getInstance(application).MyDao()
textbox = findViewById(R.id.metin)
setContentView(R.layout.activity_main)
if (ContextCompat.checkSelfPermission(applicationContext, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED
)
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.CAMERA),
cameraRequest
)
imageView = findViewById(R.id.imageView)
// var textbox: EditText = findViewById(R.id.text)
val photoButton: Button = findViewById(R.id.capture_button)
photoButton.setOnClickListener {
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(cameraIntent, cameraRequest)
}
val saveButton: Button= findViewById(R.id.save_button)
saveButton.setOnClickListener{
val takenPhoto: ByteArray = DbBitmapUtility.getBytes(imageView.drawingCache)
dao_object.insertImage(MyDatabase(takenPhoto, textbox.text.toString()))
}
val loadButton: Button= findViewById(R.id.load_button)
loadButton.setOnClickListener {
var displayPhoto: ByteArray = dao_object.getImageByTag(textbox.text.toString())
imageView.setImageBitmap(DbBitmapUtility.getImage(displayPhoto))
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == cameraRequest) {
val photo: Bitmap = data?.extras?.get("data") as Bitmap
imageView.setImageBitmap(photo)
}
}
object DbBitmapUtility {
// convert from bitmap to byte array
fun getBytes(bitmap: Bitmap): ByteArray {
val stream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream)
return stream.toByteArray()
}
// convert from byte array to bitmap
fun getImage(image: ByteArray): Bitmap {
return BitmapFactory.decodeByteArray(image, 0, image.size)
}
}
}
Change the arrangement of the code. Rather than doing the following
textbox = findViewById(R.id.metin)
setContentView(R.layout.activity_main)
do:
setContentView(R.layout.activity_main)
textbox = findViewById(R.id.metin)
setContentView must first be called before you can attempt any manipulation on the activity's view.
You can't use findViewById before you've called setContentView(). There is no View to search in for your view yet at that point.
in my project i have to send a picture to a Rest Api, am using Retrofit 2.0.9 with kotlin coroutine
the problem when i send the request i get 201 as response code that mean is Successful but the server i
cant find the picture, i find only : file name , file id .
take picture code in my fragment
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
updatePagesAppBarrTitle()
if (ActivityCompat.checkSelfPermission(
requireActivity(),
android.Manifest.permission.CAMERA
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
requireActivity(),
arrayOf(android.Manifest.permission.CAMERA),
111
)
} else {
val i = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(i, 101)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Log.d("sara1997", "$requestCode")
if (requestCode == 101) {
try {
val picture: Bitmap? = data?.getParcelableExtra("data")
if (picture != null) {
saveImageState(picture)
val file = convertBitmapToFile("imageName", picture)
val requestBody = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
val image =
MultipartBody.Part.createFormData("userImage", file.name, requestBody)
Picasso.get().load(file.toURL().toString()).into(Takeimageview)
_Takepicturebinding.ShowAlertDialogbtn.setOnClickListener {
takePictureViewModel.uploadPhoto(
image,
ImageUploadModel(
"page",
"ImageCreated",
"dfdd0daf-87ae-4cb3-9181-5cb1e240c3e7",
"478c60dc-329d-475b-81a3-fbe1a5a118b4",) )
} }
my repository Code
suspend fun uploadPhoto(
image: MultipartBody.Part,
imageUploadModel: ImageUploadModel
): Response<ImageUploadModel> {
val name: RequestBody =
imageUploadModel.name.toRequestBody("multipart/form-data".toMediaTypeOrNull())
val corpus: RequestBody = imageUploadModel.corpus.toString()
.toRequestBody("multipart/form-data".toMediaTypeOrNull())
val parent: RequestBody = imageUploadModel.parent.toString()
.toRequestBody("multipart/form-data".toMediaTypeOrNull())
val type: RequestBody =
imageUploadModel.type.toRequestBody("multipart/form-data".toMediaTypeOrNull())
return ApiService.APIBody.uploadPhoto(type, name, corpus, parent, image)
}
my request call code :
#Multipart
#POST("elements/create/")
suspend fun uploadPhoto(
#Part("type") type: RequestBody,
#Part("name") name: RequestBody,
#Part("corpus") corpus: RequestBody,
#Part("parent") parent: RequestBody,
#Part image: MultipartBody.Part
): Response<ImageUploadModel>
To post / put MultiPart.Parts we need to do this
Make sure the WebService / method is annotated correctly
#Multipart
#PUT("/api/profile-picture")
fun putProfilePicture(#Part imagePart: MultipartBody.Part): Single<Response<ResponseBody>>
Create the form data
val imagePart = MultipartBody.Part.createFormData(
name = "file",
filename = image.name,
body = image.asRequestBody("image/*".toMediaTypeOrNull())
)
Send the request
return webService.putProfilePicture(imagePart)
at First store your image
private fun saveToInternalStorage(bitmapImage: Bitmap, imageName: String): String? {
val cw = ContextWrapper(context)
// path to /data/data/yourapp/app_data/imageDir
val directory: File = cw.getDir("profile_image", Context.MODE_PRIVATE)
// Create imageDir
val mypath = File(directory, imageName)
var fos: FileOutputStream? = null
try {
fos = FileOutputStream(mypath)
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos)
} catch (e: java.lang.Exception) {
e.printStackTrace()
} finally {
try {
fos?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
return directory.getAbsolutePath()}
then use OkHttpClient
saveToInternalStorage(imageView.drawable.toBitmap(), "profile.png")
val cw = ContextWrapper(context)
// path to /data/data/yourapp/app_data/imageDir
val path: File = cw.getDir("profile_image", Context.MODE_PRIVATE)
val file = File(path, "profile.png")
val requestBody =
MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("id", ID)
// Upload parameters
.addFormDataPart(
"user_image",
file?.name,
file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
) // Upload files
.build()
var request = Request.Builder().url("https://www.yoururl.com").post(requestBody).build()
var client = OkHttpClient()
client
.newCall(request)
.enqueue(
object : Callback {
override fun onFailure(call: Call, e: IOException) {}
override fun onResponse(call: Call, response: Response) {}
}
)
https://gist.github.com/samiullahazizi/e2f6e01253ec0a9fe998d4d4b32d67e4
My application checks whether the new selected image is the same as the previous one so that I don't need to update the cloud data, but newBitmap.sameAs(oldBitmap) always return false even though I pick the same photo.
Piece of my code:
private lateinit var oldBitmap: Bitmap
private lateinit var newBitmap: Bitmap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_my_profile)
myProfilePictureUrl = intent.getStringExtra("myProfilePictureUrl")!!
if (myProfilePictureUrl.isNotEmpty()) {
Picasso.get().load(myProfilePictureUrl).into(my_profile_imageView)
}
oldBitmap = (my_profile_imageView.drawable as BitmapDrawable).bitmap //for later comparison
my_profile_imageView.setOnClickListener {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, RESULT_CODE_PICK_IMAGE)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RESULT_CODE_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
val inputStream = contentResolver.openInputStream(data!!.data!!)
val bitmap = BitmapFactory.decodeStream(inputStream)
newBitmap = bitmap //for comparison
my_profile_imageView.setImageBitmap(bitmap)
}
}
And when the user click on the "save" button on the action bar will it first check whether they are the same photo:
private fun updateProfile(nickname: String) {
if (this::newBitmap.isInitialized && !newBitmap.sameAs(oldBitmap)) { //here
//upload task code
}
}
THE PROBLEM IS:
!newBitmap.sameAs(oldBitmap) always return false even they are the same photo, may be the problem of PICASSO? Or the way I used to compare is not right. Any help would be appreciated.
I want to get some info like artist, duration and title from a selected mp3 file.But I seem to get something wrong. I just get some random numbers and that is not what I hoped for. I am thankful for every help I get.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_music)
SelectTrack()
}
private fun SelectTrack() {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "audio/mpeg"
startActivityForResult(intent, 0)
}
var selectedTrackUri: Uri? = null
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 0 && resultCode == Activity.RESULT_OK && data !=null) {
selectedTrackUri = data.data
val title = MediaMetadataRetriever.METADATA_KEY_TITLE.toString()
val duration = MediaMetadataRetriever.METADATA_KEY_DURATION.toString()
val artist = MediaMetadataRetriever.METADATA_KEY_ARTIST.toString()
AddTrackName_txt.text = title
AddArtistName_txt.text = artist
AddTrackLength_txt.text = duration
//Picasso.get().load(album).into(AddTrackPic_View)
}
}
}
The problem is in the way you retrieve the metadata of the file, you are assigning the values of the keys used to extract the metadata, not reading the actual data from the MediaMetadataRetriever.
Example
private fun selectTrack() {
val intent = Intent(Intent.ACTION_GET_CONTENT).apply { type = "audio/mpeg" }
startActivityForResult(intent, RC_MEDIA_FILE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
super.onActivityResult(requestCode, resultCode, intent)
if (requestCode == RC_MEDIA_FILE && resultCode == Activity.RESULT_OK && intent != null) {
val mmr = MediaMetadataRetriever()
mmr.setDataSource(this, intent.data)
val title = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE)
val artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST)
val duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
Log.d("MP3", "title=$title, artist=$artist, duration=$duration")
}
}
companion object {
const val RC_MEDIA_FILE = 100
}
Output
D/MP3: title=Sweet Child O´Mine, artist=Guns N' Roses, duration=356444