My activity crashes when making object of json - android

When ever i made a object of JSONObject my crashes
when ever i enter this line in my onPostExecute override fun
val jsonObject=JSONObject(result)
my activity damn crashes after starting the android emulator
my whole code is below
package shubham.lists.simpleapicalldemo
import android.app.Dialog
import android.os.AsyncTask
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.loader.content.AsyncTaskLoader
import org.json.JSONObject
import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.IOException
import java.io.InputStreamReader
import java.lang.StringBuilder
import java.net.HttpURLConnection
import java.net.SocketTimeoutException
import java.net.URL
import java.sql.Connection
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
CallAPILoginAsyncTask("SHUBHAM","123456").execute()
}
private inner class CallAPILoginAsyncTask(val username:String,val password:String): AsyncTask<Any, Void, String>() {
private lateinit var customProgressDialog:Dialog
override fun onPreExecute() {
super.onPreExecute()
showProgressDialog()
}
override fun doInBackground(vararg params: Any?): String? {
var result:String
var connection:HttpURLConnection?=null
try{ //this link is getting from the mocky.JSON
val url=URL("https://run.mocky.io/v3/3fb2c711-55ea-4de3-aee4-2d7c6848c9d3")
connection=url.openConnection() as HttpURLConnection
connection.doInput=true
connection.doOutput=true
connection.instanceFollowRedirects=false
connection.requestMethod="POST"
connection.setRequestProperty("Content-Type","application/json")
connection.setRequestProperty("charset","utf-8")
connection.setRequestProperty("Accept","application/json")
connection.useCaches=false
val writeDataOutputStream= DataOutputStream(connection.outputStream)
val jsonRequest=JSONObject()
jsonRequest.put("username",username)
jsonRequest.put("password",password)
writeDataOutputStream.writeBytes(jsonRequest.toString())
writeDataOutputStream.flush()
writeDataOutputStream.close()
val httpResult:Int=connection.responseCode
if(httpResult==HttpURLConnection.HTTP_OK){
val inputStream=connection.inputStream
val reader=BufferedReader(InputStreamReader(inputStream))
val stringBuilder=StringBuilder()
var line:String?
try {
while(reader.readLine().also { line=it }!=null){
stringBuilder.append(line + "\n")
}
} catch (e:IOException){
e.printStackTrace()
}
finally {
try{
inputStream.close()
} catch (e:IOException){
e.printStackTrace()
}
}
result=stringBuilder.toString()
}
else{
result=connection.responseMessage
}
}
catch (e:SocketTimeoutException){
result="Connection timed out"
}
catch (e:Exception){
result="Error "+ e.message
}
finally {
connection?.disconnect()
}
return result
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
cancelProgressDialog()
Log.i("JSON RESPONSE RESULT","$result")
val jsonObject=JSONObject(result) //deconstructing json object
/*val message=jsonObject.optString("message")
Log.i("message",message)
val user_id=jsonObject.optInt("USER_ID")
Log.i("user_id","$user_id")
val profiledetails=jsonObject.optJSONObject("profile_details") //deconstructing json object inside json object
val is_profile_completed= profiledetails?.optString("IS_PROFILE_COMPLETED")
Log.i("is_profile_completed","$is_profile_completed")
val dataList=jsonObject.optJSONArray("data-list")
val dataListArray=jsonObject.optJSONArray()
jsonObject=JSONObject(result)
Log.i(“Data list size”,”${datalistArray.size()}”)
for(item in 0 until datalistArray.length()){
Log.i(“value $item”,”${datalistArray[item]}”)
Val dataItemObject:JSONObject=datalistArray[item] as JSONObject
val id=dataitemObject.optInt(“id”)
Log.i(“ID”,$”id”)
val value=dataitemObject.optString(“value”)
Log.i(“value”,$”value”)
*/
}
private fun showProgressDialog(){
customProgressDialog=Dialog(this#MainActivity)
customProgressDialog.setContentView(R.layout.dialog_custom_progress)
customProgressDialog.show()
}
private fun cancelProgressDialog(){
customProgressDialog.dismiss()
}
}
}

Related

How to set the visibility GONE after the download was successful, and visibility still VISIBLE if download was unsuccessful?

I am making a studymaterial app, where i want to add a functionality where - when a user download a particular chapter from recyclerview and after the successful download of that item the Download button visivity should make GONE of that item at that time.
I have implemented a method to do thisd but it only works when user finish the activity and come back again on that activity then the download button automatic not showing, but i want to implement at that point of time when user download something.
Here is my DownloadHandler.kt class
package com.tworoot2.class9thhistoryncert.downloadHandler
import android.app.AlertDialog
import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.widget.Toast
import com.downloader.*
import com.tworoot2.class9thhistoryncert.DownloadedFiles
import java.io.File
import com.tworoot2.class9thhistoryncert.R
class DownloadHandler {
lateinit var alertDialog: AlertDialog.Builder
lateinit var failed: AlertDialog.Builder
var progressDialog: ProgressDialog? = null
var fileDestination: File? = null
var down: Boolean = false
fun downloadFile(url: String?, fileName: String, context: Context, filePath: File): Boolean {
progressDialog = ProgressDialog(context)
progressDialog!!.setMessage("Downloading....")
progressDialog!!.setCancelable(false)
progressDialog!!.max = 100
progressDialog!!.setProgressStyle(ProgressDialog.STYLE_SPINNER)
progressDialog!!.show()
alertDialog = AlertDialog.Builder(context)
alertDialog.setTitle("Downloaded successfully")
alertDialog.setMessage("$fileName is downloaded successfully")
alertDialog.setIcon(R.drawable.check)
alertDialog.setPositiveButton(
"Open"
) { _, i ->
val intent = Intent(context, DownloadedFiles::class.java)
context.startActivity(intent)
}
failed = AlertDialog.Builder(context)
failed.setTitle("Downloading failed")
failed.setMessage("Your file is not downloaded successfully")
failed.setIcon(R.drawable.failed)
PRDownloader.download(url, filePath.path, fileName)
.build()
.setOnStartOrResumeListener { }
.setOnPauseListener { }
.setOnCancelListener { }
.setOnProgressListener { progress ->
val per = progress.currentBytes * 100 / progress.totalBytes
progressDialog!!.setMessage("Downloading : $per %")
}
.start(object : OnDownloadListener {
override fun onDownloadComplete() {
down = true
Toast.makeText(context, "Download completed ", Toast.LENGTH_SHORT).show()
progressDialog!!.dismiss()
alertDialog.show()
}
override fun onError(error: Error) {
down = false
Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show()
failed.show()
progressDialog!!.dismiss()
}
})
return down
}
}
Adapter Class
package com.tworoot2.class9thhistoryncert.adapters
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.tworoot2.class9thhistoryncert.Interface.OnPDFSelectListener
import com.tworoot2.class9thhistoryncert.Interface.PDFDownloadListner
import com.tworoot2.class9thhistoryncert.PDFActivity
import com.tworoot2.class9thhistoryncert.R
import com.tworoot2.class9thhistoryncert.models.StudyMaterials
import java.io.File
import java.lang.String
import kotlin.Int
class MaterialsAdapter(
var context: Context,
var arrayList: List<StudyMaterials>,
var listener: PDFDownloadListner,
var pdfSelectListener: OnPDFSelectListener,
var folderLocations: File
) :
RecyclerView.Adapter<MaterialsAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.custom_materials, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.subjectHead.text = arrayList[position].chNo
holder.subjectName.text = arrayList[position].Title
val file =
File(
"$folderLocations/" + String.valueOf(
"Ch-" + arrayList[position].chNo + ". "
+ arrayList[position].Title + " [twoRoot2]" + ".pdf"
)
)
if (file.exists()) {
holder.downloadBtn.visibility = View.GONE
}
holder.itemView.setOnClickListener {
if (file.exists()) {
pdfSelectListener.onPDFSelected(file)
} else {
val intent = Intent(holder.itemView.context, PDFActivity::class.java)
intent.putExtra("link", arrayList[position].Link)
intent.putExtra("flag", "y")
intent.putExtra("title", arrayList[position].Title)
intent.putExtra("chNo", arrayList[position].chNo)
it.context.startActivity(intent)
}
}
holder.downloadBtn.setOnClickListener {
val downloaded = listener.onDownload(
arrayList[position].Link,
String.valueOf("Ch-" + arrayList[position].chNo)
.toString() + ". " + arrayList[position].Title
)
}
}
override fun getItemCount(): Int {
return arrayList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val subjectName = itemView.findViewById<TextView>(R.id.subjectName);
val subjectHead = itemView.findViewById<TextView>(R.id.subjectHead);
val downloadBtn = itemView.findViewById<LinearLayout>(R.id.downloadBtn);
}
}
Activity Class
package com.tworoot2.class9thhistoryncert
import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tworoot2.class9thhistoryncert.Interface.OnPDFSelectListener
import com.tworoot2.class9thhistoryncert.Interface.PDFDownloadListner
import com.tworoot2.class9thhistoryncert.adapters.MaterialsAdapter
import com.tworoot2.class9thhistoryncert.application.MyApplicationClass
import com.tworoot2.class9thhistoryncert.downloadHandler.DownloadHandler
import com.tworoot2.class9thhistoryncert.viewModels.MainViewModel
import com.tworoot2.class9thhistoryncert.viewModels.MainViewModelFactory
import com.tworoot2.result10th_12th.Internetconnection.NetworkUtils
import java.io.File
class MaterialsActivity : AppCompatActivity(), PDFDownloadListner, OnPDFSelectListener {
lateinit var recyclerView: RecyclerView
lateinit var mainViewModel: MainViewModel
lateinit var file: File
lateinit var fileDestination: File
lateinit var downloadHandler: DownloadHandler
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_materials)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setDisplayShowHomeEnabled(true)
recyclerView = findViewById(R.id.recView)
recyclerView.layoutManager = LinearLayoutManager(this)
// download listener
downloadHandler = DownloadHandler()
file = File(getExternalFilesDir(null).toString() + "/" + "Class")
fileDestination = File(Environment.getExternalStorageDirectory(), "/Class")
if (!fileDestination.exists()) {
fileDestination.mkdirs()
}
if (!NetworkUtils.isInternetAvailable(this#MaterialsActivity)) {
Toast.makeText(this#MaterialsActivity, "No internet connection", Toast.LENGTH_SHORT)
.show()
}
val progressDialog = ProgressDialog(this)
progressDialog.setMessage("Loading....")
progressDialog.setCancelable(false)
progressDialog.show()
val medium = intent.getStringExtra("medium")
val repository = (application as MyApplicationClass).materialsRepo
mainViewModel =
ViewModelProvider(this, MainViewModelFactory(repository))[MainViewModel::class.java]
if (medium.equals("h")) {
mainViewModel.hisHinLiveData.observe(this) {
this#MaterialsActivity.runOnUiThread(java.lang.Runnable {
val adapter =
MaterialsAdapter(
this#MaterialsActivity, it!!.studyMaterialCS,
this, this, file
)
progressDialog.dismiss()
recyclerView.adapter = adapter
})
}
} else if (medium.equals("e")) {
mainViewModel.hisEngLiveData.observe(this) {
this#MaterialsActivity.runOnUiThread(java.lang.Runnable {
val adapter =
MaterialsAdapter(
this#MaterialsActivity, it!!.studyMaterialCS,
this, this, file
)
progressDialog.dismiss()
recyclerView.adapter = adapter
})
}
} else {
Toast.makeText(this#MaterialsActivity, "Everything is invalid", Toast.LENGTH_SHORT)
.show()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onDownload(url: String?, title: String?) {
val time = System.currentTimeMillis().toString()
val shortTime = time.substring(8, 12)
val fileName = "$title [twoRoot2]"
// downloadFile(url, fileName + ".pdf");
// downloadFile(url, fileName + ".pdf");
Toast.makeText(applicationContext, "Downloading....", Toast.LENGTH_SHORT).show()
val downloaded =
downloadHandler.downloadFile(url, "$fileName.pdf", this#MaterialsActivity, file)
// Toast.makeText(applicationContext, "D...." + downloaded, Toast.LENGTH_SHORT).show()
}
override fun onPDFSelected(file: File?) {
val intent = Intent(this#MaterialsActivity, PDFActivity::class.java)
intent.putExtra("path", file!!.absolutePath)
intent.putExtra("flag", "n")
startActivity(intent)
}
override fun onDelete(file: File?, position: Int) {
TODO("Not yet implemented")
}
override fun inExternalApp(file: File?, context: Context?) {
TODO("Not yet implemented")
}
}
Repository Class
package com.tworoot2.class9thhistoryncert.repository
import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.tworoot2.class9thhistoryncert.api.MaterialsService
import com.tworoot2.class9thhistoryncert.models.MaterialsElist
import com.tworoot2.class9thhistoryncert.models.MaterialsList
import com.tworoot2.result10th_12th.Internetconnection.NetworkUtils
class MaterialsRepo(private val service: MaterialsService, private val context: Context) {
private val hisHinMutableLiveData = MutableLiveData<MaterialsList>()
private val hisEngMutableLiveData = MutableLiveData<MaterialsList>()
val hisHinLiveData: LiveData<MaterialsList>
get() = hisHinMutableLiveData
val hisEngLiveData: LiveData<MaterialsList>
get() = hisEngMutableLiveData
suspend fun getHisHindi() {
if (NetworkUtils.isInternetAvailable(context)) {
val result = service.getHistoryHindiFromAPI()
if (result.body() != null) {
hisHinMutableLiveData.postValue(result.body())
}
} else {
Log.e("InternetError", "No Internet Connection")
}
}
suspend fun getHisEnglish() {
if (NetworkUtils.isInternetAvailable(context)) {
val result = service.getHistoryEnglishFromAPI()
if (result.body() != null) {
hisEngMutableLiveData.postValue(result.body())
}
}else{
Log.e("InternetError", "No Internet Connection")
}
}
}
[Screen Shot 1]
[Screen Shot 2]
Maybe you want to use LiveData to handle realtime update UI for your case. After download thread run completed, let observer call update item in recyclerview.
Hope it help!

Profile Pic not displaying on Card View in Andorid Studio Kotlin

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.

Android Studio Kotlin : App freezes when trying to read from inputStream (Bluetooth)

So im completely new to Android Studio and Kotlin. I have been following videos as well as looking over the Bluetooth overview from developer.android.com. I am really lost in trying to continuously read data from the inputBuffer, and have no idea where to start. I am able to send data successfully through the bluetooth, but whenever I try to continuously listen for data, the app freezes. Could anyone help elaborate or help step through the process for doing this?
package com.example.airboard
import android.app.ProgressDialog
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.Context
import android.os.AsyncTask
import android.os.Bundle
import android.os.Handler
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.control_layout.*
import org.jetbrains.anko.toast
import java.io.IOException
import java.util.*
class ControlActivity: AppCompatActivity() {
companion object {
var m_myUUID: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
var m_bluetoothSocket: BluetoothSocket? = null
lateinit var m_progress: ProgressDialog
lateinit var m_bluetoothAdapater: BluetoothAdapter
var m_isConnected: Boolean = false
lateinit var m_address: String
private val mmBuffer: ByteArray = ByteArray(1024)
private const val TAG = "MY_APP_DEBUG_TAG"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.control_layout)
m_address = intent.getStringExtra(SettingsActivity.EXTRA_ADDRESS)!!
ConnectToDevice(this).execute()
control_led_on.setOnClickListener { sendCommand("1") }
control_led_off.setOnClickListener { sendCommand("2") }
control_led_disconnect.setOnClickListener { disconnect() }
listen.setOnClickListener { listen() }
}
private fun listen() {
var numBytes: Int // bytes returned from read()
// Keep listening to the InputStream until an exception occurs.
//while (true) {
// Read from the InputStream.
numBytes = try {
m_bluetoothSocket!!.inputStream.read(mmBuffer)
} catch (e: IOException) {
Log.d(TAG, "Input stream was disconnected", e)
//break
}
toast(numBytes)
// Send the obtained bytes to the UI activity.
// }
}
private fun sendCommand(input: String){
if (m_bluetoothSocket != null){
try {
m_bluetoothSocket!!.outputStream.write(input.toByteArray())
Log.i("data", "sending..")
} catch (e: IOException) {
e.printStackTrace()
Log.i("data", "couldn't send")
}
return
}
}
private fun disconnect(){
if (m_bluetoothSocket != null){
try {
m_bluetoothSocket!!.close()
m_bluetoothSocket = null
m_isConnected = false
} catch (e: IOException) {
e.printStackTrace()
}
}
finish()
}
private class ConnectToDevice(c: Context) : AsyncTask<Void, Void, String>(){
private var connectSuccess: Boolean = true
private val context: Context
init {
this.context = c
}
override fun onPreExecute() {
super.onPreExecute()
m_progress = ProgressDialog.show(context, "Connecting...", "please wait")
}
override fun doInBackground(vararg p0: Void?) : String? {
try {
if (m_bluetoothSocket == null || !m_isConnected){
m_bluetoothAdapater = BluetoothAdapter.getDefaultAdapter()
val device: BluetoothDevice = m_bluetoothAdapater.getRemoteDevice(m_address)
m_bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(m_myUUID)
BluetoothAdapter.getDefaultAdapter().cancelDiscovery()
m_bluetoothSocket!!.connect()
}
} catch (e: IOException){
connectSuccess = false
e.printStackTrace()
}
return null
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
if(!connectSuccess){
Log.i("data", "couldn't connect")
} else {
m_isConnected = true
Log.i("data", "connected")
}
m_progress.dismiss()
}
}
}
Digging through some other questions, maybe ASyncTask is not a good option for doing this?
Android runs code in the UI thread by default. So you cant use while(true) in the main thread or the UI will freeze. Instead, do this task in a separate thread. You can extend the Thread class and check for incoming messages inside the run() method of the class. Check the documentation for more info.

Android studio app suddenly changes of activity

Im making a bluetooth app where you can turn on and off an arduino light. If i comment the setContentView, this does not happen. However, when I turn it on, it happens one of two things:
the app stops
it changes of activity
here's my code
package com.ainimei.remotemouse
import android.app.ProgressDialog
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.Context
import android.os.AsyncTask
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AlertDialog
import kotlinx.android.synthetic.main.activity_control_bluetooth_connection.*
import java.io.IOException
import java.util.*
class ControlBluetoothConnection : AppCompatActivity() {
companion object {
var m_myUUID: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
var m_bluetoothSocket: BluetoothSocket? = null
lateinit var m_progress: ProgressDialog
lateinit var m_bluetoothAdapter: BluetoothAdapter
var m_isConnected: Boolean = false
lateinit var m_address: String
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_keyboard)
onCreateExtra()
}
private fun onCreateExtra() {
m_address = intent.getStringExtra(Connection.EXTRA_ADDRESS).toString()
ConnectToDevice(this).execute()
control_led_on.setOnClickListener { sendCommand("a") }
control_led_off.setOnClickListener { sendCommand("b") }
control_led_disconnect.setOnClickListener { disconnect() }
}
private fun sendCommand(input: String) {
if (m_bluetoothSocket != null) {
try{
m_bluetoothSocket!!.outputStream.write(input.toByteArray())
} catch(e: IOException) {
e.printStackTrace()
}
}
}
private fun disconnect() {
if (m_bluetoothSocket != null) {
try {
m_bluetoothSocket!!.close()
m_bluetoothSocket = null
m_isConnected = false
} catch (e: IOException) {
e.printStackTrace()
}
}
finish()
alertMessage("Disconnected Successfully", "Bluetooth")
}
private class ConnectToDevice(c: Context) : AsyncTask<Void, Void, String>() {
private var connectSuccess: Boolean = true
private val context: Context
init {
this.context = c
}
override fun onPreExecute() {
super.onPreExecute()
m_progress = ProgressDialog.show(context, "Connecting...", "please wait")
}
override fun doInBackground(vararg p0: Void?): String? {
try {
if (m_bluetoothSocket == null || !m_isConnected) {
m_bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
val device: BluetoothDevice = m_bluetoothAdapter.getRemoteDevice(m_address)
m_bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(m_myUUID)
BluetoothAdapter.getDefaultAdapter().cancelDiscovery()
m_bluetoothSocket!!.connect()
}
} catch (e: IOException) {
connectSuccess = false
e.printStackTrace()
}
return null
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
if (!connectSuccess) {
//Log.i("data", "couldn't connect")
} else {
m_isConnected = true
}
m_progress.dismiss()
}
}
open fun alertMessage(message: String, title: String) {
var builder = AlertDialog.Builder(this)
builder.setTitle(title)
builder.setMessage(message)
val dialog = builder.create()
dialog.show()
}
}
i tried commenting some functions, and I saw that when i commented the onCreateExtra() function, this made the layout dont appear. need help

How to call Activity class method in inner class method in kotlin android

I have create one progress method in Activity class. then create one another class for AsyncTask.
My requirement is call processProgressBar() method in AsyncTask class doInBackground()
How it possible?
See My Code:
package com.example.bharat.generalknowledge
import android.os.AsyncTask
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import com.example.bharat.generalknowledge.dbhandler.DatabaseHandler
import org.xml.sax.InputSource
import java.io.BufferedInputStream
import java.io.FileOutputStream
import java.net.URL
import java.util.zip.GZIPInputStream
class WelcomeActivity : AppCompatActivity() {
init {
println("Init block")
}
companion object {
var dbPath: String = ""
var isDatabaseExist: Boolean = false
private val handler = Handler()
val wActivity = WelcomeActivity()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_welcome)
val dbHandler = DatabaseHandler(this)
isDatabaseExist = dbHandler.checkIfTableExistOrNot()
Log.w("isDatabaseExist: ", isDatabaseExist.toString())
if(!isDatabaseExist){
dbPath = dbHandler.getDatabasePath()
downloadDb().execute()
}
}
fun processProgressBar(pStatus: Int=10){
println("====================processProgressBar==========================")
val res = resources
val drawable = res.getDrawable(R.drawable.circular)
val mProgress = findViewById<View>(R.id.circularProgressbar) as ProgressBar
mProgress.progress = 0 // Main Progress
mProgress.secondaryProgress = 100 // Secondary Progress
mProgress.max = 100 // Maximum Progress
mProgress.progressDrawable = drawable
mProgress.progress = pStatus
}
class downloadDb() : AsyncTask<Void, Void, String>() {
override fun doInBackground(vararg params: Void?): String? {
try {
// download the file
val url = URL("http://192.168.0.105/new-gk-app/web/uploads/db-backup/gk_app.gz")
val connection = url.openConnection()
connection.connect()
// get stream and convert gzip to db original
var stream = connection.getInputStream()
stream = GZIPInputStream(stream)
val `is` = InputSource(stream)
val input = BufferedInputStream(`is`.byteStream, 8192)
val output = FileOutputStream(dbPath)
val data = ByteArray(1024)
while ((input.read(data)) != -1) {
output.write(data);
// processProgressBar(30) /* ****** my requirement is call this method ******* */
}
output.flush()
output.close()
input.close()
} catch (e: Exception) {
Log.e("Error: ", e.message)
}
return null
}
override fun onPreExecute() {
super.onPreExecute()
Log.w("Database Downloded: ", "Start")
// ...
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
Log.w("Database Downloded: ", "Finish")
}
}
}
You can pass the reference of your activity in the constructor of your Async task, wrapped in a weak reference and call your function from there.
class downloadDb(var activity:WeakReference<WelcomeActivity >) : AsyncTask<Void, Void, String>()
and in you doInBackground
activity.get()?.let {
it.runOnUiThread({
})
}
To initialise the AysncTask,downloadDb(WeakReference(this))

Categories

Resources