On Button Click code under Switch Button is not Working - android

On Button Click, I want to get data on second activity from edit text only if the Switch button is ON but unable to do this anyone can help me to resolve this issue. Thanks
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val nextButton = findViewById<Button>(R.id.nextButton)
nextButton.setOnClickListener {
nextPage()
}
}
private fun nextPage(){
val etName = findViewById<EditText>(R.id.name)
val etEmail = findViewById<EditText>(R.id.email)
val etPhone = findViewById<EditText>(R.id.phone)
val etPassPort = findViewById<CheckBox>(R.id.checkbox)
var passport = ""
if (etPassPort.isChecked) { passport = etPassPort.text.toString() }
val mName = etName.text.toString()
val mEmail = etEmail.text.toString()
val mPhone = etPhone.text.toString()
val intent = Intent(this#MainActivity, ViewActivity::class.java)
intent.putExtra("Name", mName)
intent.putExtra("Email", mEmail)
intent.putExtra("Phone", mPhone)
intent.putExtra("CHECKBOX", passport)
val mySwitch = findViewById<SwitchCompat>(R.id.mySwitch)
mySwitch.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
val et = findViewById<EditText>(R.id.sponsorName)
val mEt = et.text.toString()
intent.putExtra("SPONSOR", mEt)
}
}
startActivity(intent)
}
}
SecondActivity.kt
class ViewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_view)
val intent = intent
val mName = intent.getStringExtra("Name")
val mEmail = intent.getStringExtra("Email")
val mPhone = intent.getStringExtra("Phone")
val checkbox = intent.getStringExtra("CHECKBOX")
val mEt = intent.getStringExtra("SPONSOR")
//textview
val resultTv = findViewById<View>(R.id.resultTV) as TextView
//setText
resultTv.text = mName+"\n"+mEmail+"\n"+mPhone+"\n"+checkbox+"\n"+mEt
}
}
Switch button code is working fine when i release it from the Button Click. Under the Button Click only null value is showing in Output.

I resolved the issue of Switch Button by declaring it globally here is my working code.
MainActivity.kt
class MainActivity : AppCompatActivity() {
var sponsor : Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val mySwitch = findViewById<SwitchCompat>(R.id.mySwitch)
mySwitch.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
sponsor = true
}
}
val nextButton = findViewById<Button>(R.id.nextButton)
nextButton.setOnClickListener {
nextPage()
}
}
private fun nextPage(){
val etName = findViewById<EditText>(R.id.name)
val etEmail = findViewById<EditText>(R.id.email)
val etPhone = findViewById<EditText>(R.id.phone)
val etPassPort = findViewById<CheckBox>(R.id.checkbox)
var passport = ""
if (etPassPort.isChecked) { passport = etPassPort.text.toString() }
val mName = etName.text.toString()
val mEmail = etEmail.text.toString()
val mPhone = etPhone.text.toString()
val intent = Intent(this#MainActivity, ViewActivity::class.java)
val et = findViewById<EditText>(R.id.sponsorName)
val mEt = et.text.toString()
intent.putExtra("SPONSOR", mEt)
intent.putExtra("Name", mName)
intent.putExtra("Email", mEmail)
intent.putExtra("Phone", mPhone)
intent.putExtra("CHECKBOX", passport)
intent.putExtra("Switch",sponsor.toString())
startActivity(intent)}}
SecondActivity.kt
class ViewActivity : AppCompatActivity() {
private lateinit var pdfButton: Button
private var permissionCode = 101
private val STORAGE_CODE: Int = 100
val resultTv = findViewById<View>(R.id.resultTV) as TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_view)
val intent = intent
val mName = intent.getStringExtra("Name")
val mEmail = intent.getStringExtra("Email")
val mPhone = intent.getStringExtra("Phone")
val checkbox = intent.getStringExtra("CHECKBOX")
val mEt = intent.getStringExtra("SPONSOR")
val sponsor1 = intent.getStringExtra("Switch")
//textview
//setText
resultTv.text =
mName + "\n" + mEmail + "\n" + mPhone + "\n" + checkbox + "\n" + mEt + "\n" + sponsor1
if (sponsor1 == "true") {
resultTv.text = mName + "\n" + mEmail + "\n" + mPhone + "\n" + checkbox + "\n" + mEt
} else {
resultTv.text = mName + "\n" + mEmail + "\n" + mPhone + "\n" + checkbox
}

I know where is the problem, first of all you call the buttonCLick, and inside it you call the method nextPage(), if we look closely, this block of code
val mySwitch = findViewById<SwitchCompat>(R.id.mySwitch)
mySwitch.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
val et = findViewById<EditText>(R.id.sponsorName)
val mEt = et.text.toString()
intent.putExtra("SPONSOR", mEt)
}
}
is inside your click button, and by default your switch is not checked, so you pass all data, but intent.putExtra("SPONSOR", mEt) is not executed, so when the second activity receive the data is show a null error because val mEt = intent.getStringExtra("SPONSOR") is null.
You have two solution, either you write the block of the switch code outside the click button, or in the second activity you check with a conditionif all your data are not null.

Related

How to do calculations on fields Focus change in Koltin

Good Morning brothers. I am working on an android form in Koltin which will save the data into MySQL. The problem I am facing is how can I save calculated data to an EditText field while entering data. I tried to add the calculation in oCreate instance but the intent crashes cause there is null point Exception as the form created is empty values. My code is appended below. Any help will be appreciated. Thanks.
I am trying to calculate value of project cost * ITRation / 100 and set the value to editTextITAMount but I am unable to do so.
class ProjectActivity : AppCompatActivity() {
//edittext and spinner
private var editTextProjectName: EditText? = null
private var spinnerProjectType: Spinner? = null
private var editTextDepartment: EditText? = null
private var editTextDateAwarded: EditText? = null
private var editTextProjectLocation: EditText? = null
private var editTextProjectCity: EditText? = null
private var editTextProjectDistrict: EditText? = null
private var spinnerJointVenture: Spinner? = null
private var editTextJointVentureCoy: EditText? = null
private var spinnerProjectStatus: Spinner? = null
private var editTextProjectCost: EditText? = null
private var spinnerITRatio: Spinner? = null
private var editTextITAmount: EditText? = null
private var spinnerGSTBST: Spinner? = null
private var editTextGSTBSTAmount: EditText? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_project)
//getting it from xml
editTextProjectName = findViewById(R.id.editTextProjectName) as EditText
spinnerProjectType = findViewById(R.id.spinnerProjectType) as Spinner
editTextDepartment = findViewById(R.id.editTextDepartment) as EditText
val mPickTimeBtn = findViewById<ImageButton>(R.id.imageButton)
editTextDateAwarded = findViewById(R.id.editTextDateAwarded) as EditText
editTextProjectLocation = findViewById(R.id.editTextProjectLocation) as EditText
editTextProjectCity = findViewById(R.id.editTextProjectCity) as EditText
editTextProjectDistrict = findViewById(R.id.editTextProjectDistrict) as EditText
spinnerJointVenture = findViewById(R.id.spinnerJointVenture) as Spinner
editTextJointVentureCoy = findViewById(R.id.editTextJointVentureCoy) as EditText
spinnerProjectStatus = findViewById(R.id.spinnerProjectStatus) as Spinner
editTextProjectCost = findViewById(R.id.editTextProjectCost) as EditText
spinnerITRatio = findViewById(R.id.spinnerITRatio) as Spinner
editTextITAmount = findViewById(R.id.editTextITAmount) as EditText
spinnerGSTBST = findViewById(R.id.spinnerGSTBST) as Spinner
editTextGSTBSTAmount = findViewById(R.id.editTextGSBSTAmount) as EditText
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
mPickTimeBtn.setOnClickListener {
val dpd = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
// Display Selected date in TextView
editTextDateAwarded!!.setText("" + dayOfMonth + "/" + month + "/" + year)
}, year, month, day)
dpd.show()
}
//adding a click listener to button
this.findViewById<Button>(R.id.buttonAddProject).setOnClickListener { addProject() }
//in the second button click
//opening the activity to display all the artist
//it will give error as we dont have this activity so remove this part for now to run the app
}
private fun calculation() {
}
//adding a new record to database
private fun addProject() {
//getting the record values
val projectName = editTextProjectName?.text.toString()
val projectType = spinnerProjectType?.selectedItem.toString()
val department = editTextDepartment?.text.toString()
val dateAwarded = editTextDateAwarded?.text.toString()
val projectLocation = editTextProjectLocation?.text.toString()
val projectCity = editTextProjectCity?.text.toString()
val projectDistrict = editTextProjectDistrict?.text.toString()
val jointVenture = spinnerJointVenture?.selectedItem.toString()
val jointVentureWith = editTextJointVentureCoy?.text.toString()
val projectStatus = spinnerProjectStatus?.selectedItem.toString()
val projectCost= editTextProjectCost?.text.toString()
val ITRatio = spinnerITRatio?.selectedItem.toString()
val ITAmount= editTextITAmount?.text.toString()
val GSTBST = spinnerGSTBST?.selectedItem.toString()
val GSTBSTAmount= editTextGSTBSTAmount?.text.toString()
val a: Int = findViewById<TextView>(R.id.editTextProjectCost).getText().toString().toInt()
val b: Int = findViewById<Spinner>(R.id.spinnerITRatio).getSelectedItem().toString().toInt()
val multiplication = a * b / 100
editTextITAmount!!.setText("" + multiplication)
//creating volley string request
val stringRequest = object : StringRequest(
Request.Method.POST, EndPoints.URL_ADD_PROJECT,
Response.Listener<String> { response ->
try {
val obj = JSONObject(response)
Toast.makeText(applicationContext, obj.getString("message"), Toast.LENGTH_LONG)
.show()
val intent = Intent(applicationContext, ProjectsViewActivity::class.java)
startActivity(intent)
} catch (e: JSONException) {
e.printStackTrace()
}
},
object : Response.ErrorListener {
override fun onErrorResponse(volleyError: VolleyError) {
Toast.makeText(applicationContext, volleyError.message, Toast.LENGTH_LONG)
.show()
}
}) {
#Throws(AuthFailureError::class)
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params.put("projectName", projectName)
params.put("projectType", projectType)
params.put("department", department)
params.put("dateAwarded", dateAwarded)
params.put("projectLocation", projectLocation)
params.put("projectCity", projectCity)
params.put("projectDistrict", projectDistrict)
params.put("jointVenture", jointVenture)
params.put("jointVentureWith", jointVentureWith)
params.put("projectStatus", projectStatus)
params.put("projectCost", projectCost)
params.put("ITRatio", ITRatio)
params.put("ITAmount", ITAmount)
params.put("GSTBST", GSTBST)
params.put("GSTBSTAmount", GSTBSTAmount)
return params
}
}
//adding request to queue
VolleySingleton.instance?.addToRequestQueue(stringRequest)
}
}

How do you encompass a try/catch block in these functions?

I get a NumberFormatException if an entry field is left blank in the app. Previously, I had a working try/catch block that would handle it but I needed to add a switch on if/else statement to determine which function to run. I've tried everything I can think of to reformat the try/catch so that error is being handled, but everything just breaks the application. What am I doing wrong here, or is it even possible to do?
package com.WordPlay.awcc
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class Setup3 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main
)
editTextNumber2.text.toString().toInt()
editTextNumber3.text.toString().toInt()
editTextNumber4.text.toString().toInt()
editTextNumber5.text.toString().toInt()
editTextNumber6.text.toString().toInt()
editTextNumber15.text.toString().toInt()
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/// Define button for checked
fun essentialexpert() {
val int11 = editTextNumber.text.toString().toInt()
val pay21 = 5
val product11 = int11 * pay21
val int12 = editTextNumber2.text.toString().toInt()
val pay22 = 12.5
val product12 = int12 * pay22
val int13 = editTextNumber3.text.toString().toInt()
val pay23 = 15
val product13 = int13 * pay23
val int16 = editTextNumber6.text.toString().toInt()
val pay24 = 5
val product14 = int16 * pay24
val int15 = editTextNumber5.text.toString().toInt()
val pay25 = 5
val product15 = int15 * pay25
val int14 = editTextNumber4.text.toString().toInt()
val pay26 = 2
val product16 = int14 / pay26
val final =
product11 + product12 + product13 + product14 + product15 + product16
val complete = final.toString()
try {
editTextNumber15?.setText(complete)
} catch (e: NumberFormatException) {
Toast.makeText(
applicationContext,
"Please enter a 0 in the blank field",
Toast.LENGTH_LONG
).show()
}
}
/// Define function for unchecked
fun essential() {
val int1 = editTextNumber.text.toString().toInt()
val pay1 = 5
val product1 = int1 * pay1
val int2 = editTextNumber2.text.toString().toInt()
val pay2 = 7.5
val product2 = int2 * pay2
val int3 = editTextNumber3.text.toString().toInt()
val pay3 = 10
val product3 = int3 * pay3
val int6 = editTextNumber6.text.toString().toInt()
val pay4 = 5
val product4 = int6 * pay4
val int5 = editTextNumber5.text.toString().toInt()
val pay5 = 0
val product5 = int5 * pay5
val int4 = editTextNumber4.text.toString().toInt()
val pay6 = 2
val product6 = int4 / pay6
val final = product1 + product2 + product3 + product4 + product5 + product6
val complete = final.toString()
try {
editTextNumber15?.setText(complete)
} catch (e: NumberFormatException) {
Toast.makeText(
applicationContext,
"Please enter a 0 in the blank field",
Toast.LENGTH_LONG
).show()
}
}
try {
essential()
} catch (e: java.lang.NumberFormatException) {
Toast.makeText(
applicationContext,
"Please enter a 0 in the blank fields",
Toast.LENGTH_LONG
).show()
/// Define buttons to change activity
val button2 = findViewById<Button>(R.id.button2)
button2.setOnClickListener {
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
}
val button3 = findViewById<Button>(R.id.button3)
button3.setOnClickListener {
val intent2 = Intent(this, ThirdActivity::class.java)
startActivity(intent2)
}
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
if (switch1.isChecked) {
essentialexpert()
} else {
essential()
}
}
}
}
}
You shouldn't catch errors when writing to an EditText, but when reading. Something like that:
fun essentialexpert() {
val int11 = try {
editTextNumber.text.toString().toInt()
} catch (e: NumberFormatException) {
Toast.makeText(
applicationContext,
"Please enter a 0 in the blank field",
Toast.LENGTH_LONG ).show()
return
}
val pay21 = 5
val product11 = int11 * pay21
// ...
// If you reach here, all fields are ok
val final = product11 + /* ... */ + product16
val complete = final.toString()
editTextNumber15?.setText(complete)
}
With Kotlin, you can simplify this try/catch using the toIntOrNull method.
var areAllFieldsValid = false
fun essentialexpert() {
val int11 = editTextNumber.text.toString().toIntOrNull() ?: return
val pay21 = 5
val product11 = int11 * pay21
// ...
// If you reach here, all fields are ok
areAllFieldsValid = true
val final = product11 + /* ... */ + product16
val complete = final.toString()
editTextNumber15?.setText(complete)
}
override fun onCreate(savedInstanceState: Bundle?) {
// ...
btnFinish.setOnClickListener {
essentialexpert()
if (!areAllFieldsValid) {
Toast.makeText(
applicationContext,
"Please enter a 0 in the blank fields",
Toast.LENGTH_LONG).show()
} else {
// Do something when all fields are valid
}
}
}
Some tips for you:
Replace final.toString() with "$final"
Replace Toast.makeText(applicationContext, ... with Toast.makeText(this, .... An Activity is a Context.
I'm not sure what Setup3 is, but if it only exists for getting the EditText values, it won't work. You can do it in MainActivity.
The expression 5/2 may not return what you think it returns.

android viewmodel observer inside RecyclerView.Adapter.onBindViewHolder() update every item

I need to download images from AWS S3 and update ImageViews inside a recycler view. I am using ViewModel for downloading files from S3. A file object is observing inside onBindViewHolder() method and once receive the file my intention was to update the image belongs with that particular holder.
But the problem is if there were two rows, then two images need to download. So each view holder will attach with the observer. After downloading the first file, both the image views inside the recycler view become updated with the first image and after downloading the second image, both images updated with the second image. I am a little bit confuse about working. Please help me with this.
I cannot use Glide for this. Because S3 have authentication. So, I need to use S3 library for downloading files.
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
val postUrl = listData[position].postUrl
val createdAt = listData[position].createdAt
val postImage = listData[position].postImage
val postVideo = listData[position].postVideo
val postVideoThumbnail = listData[position].postVideoThumbnail
val groupId = listData[position].groupId
val postStatus = listData[position].postStatus
val postId = listData[position].postId
val userId = listData[position].userId
val postHeading = listData[position].postHeading
val postDescription = listData[position].postDescription
val updatedAt = listData[position].updatedAt
val profileName = listData[position].userName
val profileImage = listData[position].profileImage
val likeCount = listData[position].likeCount
val commentCount = listData[position].commentCount
var key = ""
if(!profileImage.isNullOrEmpty()){
Glide.with(activity).load(profileImage) to holder.imgProfile
}
holder.textName.text = profileName.substring(0, 1).toUpperCase() + profileName.substring(1).toLowerCase()
holder.textPostedDateTime.text = SimpleDateFormat(POST_LIST_DATE_FORMAT).format(Date(createdAt))
holder.textPostHeading.text = postHeading
if(postDescription.isNullOrEmpty() || postDescription == "null"){
holder.textPostDescription.visibility = View.GONE
} else{
holder.textPostDescription.visibility = View.VISIBLE
holder.textPostDescription.text = postDescription
}
if(postUrl.isNullOrEmpty() || postUrl == "null"){
holder.textPostLink.visibility = View.GONE
} else{
holder.textPostLink.visibility = View.VISIBLE
holder.textPostLink.text = postUrl
}
if(postVideoThumbnail.isNullOrEmpty() || postVideoThumbnail == "null"){
holder.imgPostVideoPreview.visibility = View.GONE
} else{
holder.imgPostVideoPreview.visibility = View.VISIBLE
loadImageToFile(holder.imgPostVideoPreview, postVideoThumbnail, position)
key = postVideoThumbnail
}
if(postImage.isNullOrEmpty() || postImage == "null"){
holder.imgPostImagePreview.visibility = View.GONE
} else{
holder.imgPostImagePreview.visibility = View.VISIBLE
loadImageToFile(holder.imgPostImagePreview, postImage, position)
key = postImage
}
holder.textLikeCount.text = likeCount.toString()
holder.textCommentCount.text = commentCount.toString()
if(!isSelfPosts){
holder.layoutCommentLikeShare.visibility = View.VISIBLE
holder.imgAddComment.setOnClickListener { }
holder.imgAddLike.setOnClickListener { }
holder.imgShare.setOnClickListener { }
}
holder.itemView.setOnClickListener {
moveTOPostDetails(postId, listData[position], Environment.getExternalStorageDirectory().path + "/" + EXTERNAL_STORAGE_FOLDER_NAME + "/" + key.substring(key.lastIndexOf("/")+1))
}
}
class ListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val imgProfile: ImageView = itemView.imgProfile
val textName: TextView = itemView.textName
val textPostedDateTime: TextView = itemView.textPostedDateTime
val textPostHeading: TextView = itemView.textPostHeading
val textPostDescription: TextView = itemView.textPostDescription
val textPostLink: TextView = itemView.textPostLink
val imgPostVideoPreview: ImageView = itemView.imgPostVideoPreview
val imgPostImagePreview: ImageView = itemView.imgPostImagePreview
val textCommentCount: TextView = itemView.textCommentCount
val textLikeCount: TextView = itemView.textLikeCount
val layoutCommentLikeShare: LinearLayout = itemView.layoutCommentLikeShare
val imgAddComment: ImageView = itemView.imgAddComment
val imgAddLike: ImageView = itemView.imgAddLike
val imgShare: ImageView = itemView.imgShare
}
private fun moveTOPostDetails(postId: String, fetchPostsResponseModel: FetchPostsResponseModel, imageFileName: String){
val intent = Intent(activity, PostDetails::class.java)
intent.putExtra("POST_DETAILS", fetchPostsResponseModel)
intent.putExtra("IS_SELF_POST", isSelfPosts)
intent.putExtra("IMAGE_FILE_NAME", imageFileName)
activity.startActivity(intent)
}
private fun loadImageToFile(imageView: ImageView, key: String, position: Int){
var postListAdapterViewModel: PostListAdapterViewModel = ViewModelProviders.of(fragment).get(PostListAdapterViewModel::class.java)
postListAdapterViewModel.init(activity)
postListAdapterViewModel.getMediaFile()?.observe(fragment, Observer<File>{ file ->
var a=position
imageView.setImageURI(Uri.fromFile(file))
} )
postListAdapterViewModel.performDownload(key)
}
This is my viewmodel
class PostListAdapterViewModel(application: Application):AndroidViewModel(application){
private val file = MutableLiveData<File>()
private lateinit var context: Context
fun init(context: Context) {
this.context = context
AWSMobileClient.getInstance().initialize(context).execute()
}
fun performDownload(key : String){
val credentials = BasicAWSCredentials(AMAZON_S3_ACCESS_KEY, AMAZON_S3_SECRET_KEY)
val s3Client = AmazonS3Client(credentials)
val transferUtility = TransferUtility.builder()
.context(context)
.awsConfiguration(AWSMobileClient.getInstance().configuration)
.s3Client(s3Client)
.build()
val downloadObserver = transferUtility.download (
key,
File(Environment.getExternalStorageDirectory().path + "/" + EXTERNAL_STORAGE_FOLDER_NAME + "/" + key.substring(key.lastIndexOf("/")+1)))
// Attach a listener to get state updates
downloadObserver.setTransferListener(object : TransferListener {
override fun onStateChanged(id: Int, state: TransferState) {
if (state == TransferState.COMPLETED) {
// Handle a completed upload.
file.value = File(Environment.getExternalStorageDirectory().path + "/" + EXTERNAL_STORAGE_FOLDER_NAME + "/" + key.substring(key.lastIndexOf("/")+1))
}
}
override fun onProgressChanged(id: Int, current: Long, total: Long) {
try {
val done = (((current.toDouble() / total) * 100.0).toInt()) //as Int
Log.d("PostListAdapterVM", "DOWNLOAD - - ID: $id, percent done = $done")
}
catch (e: Exception) {
Log.e("PostListAdapterVM", "Trouble calculating progress percent", e)
}
}
override fun onError(id: Int, ex: Exception) {
Log.d("PostListAdapterVM", "DOWNLOAD ERROR - - ID: $id - - EX: ${ex.message.toString()}")
}
})
// If you prefer to poll for the data, instead of attaching a
// listener, check for the state and progress in the observer.
if (downloadObserver.state == TransferState.COMPLETED) {
// Handle a completed upload.
}
Log.d("PostListAdapterVM", "Bytes Transferrred: ${downloadObserver.bytesTransferred}")
}
fun getMediaFile(): MutableLiveData<File> {
return file
}
}

Get share value from onActivityResult

Hello I have activity with two buttons. First I take a photo and in override onActivityResult I upload the photo in firebase and I get an url which I save to photoUrl . Then in the other btn listener inside oncreate I want to use this variable but I get null as I define it in the begin of the class. How can I get the value of photoUrl which I want?
class AddYourStory : AppCompatActivity() {
val storage = FirebaseStorage.getInstance()
private val REQUEST_IMAGE = 100
private val TAG = "MainActivity"
var destination: File? = null
var imagePath: String? = null
var photoUrl : String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_your_story)
setSupportActionBar(toolbar)
val db: FirebaseFirestore
val intent = intent
val lat = intent.getStringExtra("lng")
val lng = intent.getStringExtra("lng")
db = FirebaseFirestore.getInstance()
val builder = StrictMode.VmPolicy.Builder()
StrictMode.setVmPolicy(builder.build());
val name = dateToString(Date(), "yyyy-MM-dd-hh-mm-ss")
destination = File(Environment.getExternalStorageDirectory(), "$name.jpg")
val takephoto = findViewById<Button>(R.id.button2)
takephoto.setOnClickListener {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
startActivityForResult(intent, REQUEST_IMAGE);
}
val txtTitle = findViewById<TextInputEditText>(R.id.textInputEditText2)
val txtStory = findViewById<EditText>(R.id.editText)
val btn = findViewById<Button>(R.id.button)
btn.setOnClickListener{
println("????????????????????????>>>>"+photoUrl)
val MyStory: HashMap<String, String> = HashMap<String,String>()
MyStory.put("title",txtTitle.text.toString())
MyStory.put("story",txtStory.text.toString())
MyStory.put("lat",lat)
MyStory.put("lng",lng)
MyStory.put("url",photoUrl.toString())
db.collection("Stories").document().set(MyStory as Map<String, Any>)
val confirm = Intent(this, MapsActivity::class.java)
startActivity(confirm)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK) {
try {
val `in` = FileInputStream(destination)
val options = BitmapFactory.Options()
options.inSampleSize = 10
imagePath = destination!!.getAbsolutePath()
val storageRef = storage.reference
val stream = FileInputStream(File(imagePath))
val picRef = storageRef.child(dateToString(Date(), "yyyy-MM-dd-hh-mm-ss"))
val uploadTask = picRef.putStream(stream)
uploadTask.addOnFailureListener { exception ->
println("Failed")
}.addOnSuccessListener { taskSnapshot ->
println("OK")
picRef.downloadUrl.addOnCompleteListener () {taskSnapshot ->
photoUrl = taskSnapshot.result.toString()
println ("url =" + photoUrl.toString ())
}
}
val bmp = BitmapFactory.decodeStream(`in`, null, options)
} catch (e: FileNotFoundException) {
e.printStackTrace()
}
} else {
println("Cancel")
}
}
fun dateToString(date: Date, format: String): String {
val df = SimpleDateFormat(format)
return df.format(date)
}
}

Read contacts and display it in a recyclerview in Kotlin

I am trying to read contacts from ContactsContract in Kotin. But it's not showing any of the contact in the recyclerview. The noticeable thing is that the java version of this code is working fine.
So, I here is my Kotlin code for reading the contact:
private var adapter: ContactsAdapter? = null
private var myContacts : MutableList<MyContacts> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// code for recyclerview and adapter and checkPermission
val itemDecoration = DividerItemDecoration(this, DividerItemDecoration.VERTICAL)
recycler_view.layoutManager = LinearLayoutManager(this)
recycler_view.addItemDecoration(itemDecoration)
adapter = ContactsAdapter(myContacts)
recycler_view.hasFixedSize()
recycler_view.adapter = ContactsAdapter(myContacts)
checkPermission()
}
private fun loadContactFromProvider() {
showProgressBar()
val contentResolver = contentResolver
val cursor = contentResolver.query(CONTENT_URI, null, null, null, DISPLAY_NAME)
if (cursor != null && cursor.count > 0) {
while (cursor.moveToNext()) {
val id = cursor.getString(cursor.getColumnIndex(ID))
val name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME))
val hasPhoneNumber = cursor.getInt(cursor.getColumnIndex(HAS_PHONE_NUMBER))
val contacts = MyContacts()
if (hasPhoneNumber > 0) {
contacts.contactName = name
val phoneCursor = contentResolver.query(PHONE_URI, arrayOf(NUMBER), "$PHONE_ID = ?", arrayOf(id), null)
val phoneNumbers = ArrayList<String>()
phoneCursor!!.moveToFirst()
while (!phoneCursor.isAfterLast) {
val phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER)).replace(" ", "")
phoneNumbers.add(phoneNumber)
phoneCursor.moveToNext()
}
contacts.contactNumber = phoneNumbers
phoneCursor.close()
}
val inputStream = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, ContentUris.withAppendedId(CONTENT_URI, id.toLong()))
if (inputStream != null) {
val bitmap = BitmapFactory.decodeStream(inputStream)
contacts.contactImage = bitmap?.toString()
} else {
contacts.contactImage = vectorDrawableToBitmap(R.drawable.ic_person)?.toString()
}
log(contacts.contactName + " " + contacts.contactNumber.toString() + " " + contacts.contactImage.toString())
myContacts.add(contacts)
}
adapter?.notifyDataSetChanged()
cursor.close()
}
}
The log details are also fine, they are showing the full contact list. But I am unable to see it in the recyclerview. The constant field like ID, DISPLAY_NAME etc. are already defined in the companion object.
Kotlin code for RecyclerViewAdapter is:
class ContactsAdapter(private val contactList: MutableList<MyContacts>): RecyclerView.Adapter<ContactsAdapter.ContactViewHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, position: Int): ContactViewHolder {
val view = LayoutInflater.from(viewGroup.context).inflate(R.layout.contact_item_layout,viewGroup,false)
return ContactViewHolder(view)
}
override fun onBindViewHolder(holder: ContactViewHolder, position: Int) {
val contact = contactList[position]
holder.name!!.text = contact.contactName
holder.mobile!!.text = contact.contactNumber[0]
Glide.with(holder.itemView.context)
.load(contact.contactImage)
.into(holder.image)
}
override fun getItemCount(): Int = contactList.size
class ContactViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
var image : ImageView = itemView.find(R.id.contact_image) as ImageView
var name : TextView? = itemView.find(R.id.contact_name) as TextView
var mobile : TextView? = itemView.find(R.id.contact_mobile) as TextView
}
}
Any help would be appreciated.
Thankyou

Categories

Resources