Resetting values each day to 0 in Kotlin, Android Studio? - android

I'm having problem with my step counter, I want it to reset to 0 every time the date changes.
I tried doing something like this:
if (currentDate != savedDate) {
previousSteps = totalSteps
tv_totalSteps.text = 0.toString()
saveData()
}
but I just couldn't seem to get it to work for some reason. I'm sure the answer is obvious somewhere in my code, but I've been trying different things for about 2 hours now. So any help would be very much appreciated here. Here's my whole code:
private var sensorManager: SensorManager? = null
private var running = false
private var totalSteps = 0f
private var previousSteps = 0f
var currentSteps = 0
var goalSteps = 5000
private var cal = Calendar.getInstance()
private var currentDate = cal.get(Calendar.DAY_OF_YEAR)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//needs to be called later
loadData()
resetSteps()
sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
}
override fun onResume() {
super.onResume()
running = true
val stepsSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
if (stepsSensor == null) {
Toast.makeText(this, "No sensor detected", Toast.LENGTH_SHORT).show()
} else {
sensorManager?.registerListener(this, stepsSensor, SensorManager.SENSOR_DELAY_UI)
}
}
override fun onAccuracyChanged(p0: Sensor?, p1: Int) {
}
override fun onSensorChanged(event: SensorEvent) {
if (running) {
totalSteps = event.values[0]
currentSteps = totalSteps.toInt() - previousSteps.toInt()
tv_totalSteps.text = ("$currentSteps")
progress_circular.apply {
setProgressWithAnimation(currentSteps.toFloat())
}
progress_circular_outer_ring.apply {
setProgressWithAnimation(totalSteps)
}
val caloriesBurned = totalSteps * .0228f
tv_calories.text = "${caloriesBurned.toInt()} calories"
tv_distance_walked.text = "${currentSteps} steps"
tv_totalDistanceWalked.text = "${(totalSteps* 0.00076f).toInt()} km"
tv_totalStepsTaken.text = "${totalSteps.toInt()} steps"
progress_circular_calories.apply {
setProgressWithAnimation(caloriesBurned)
}
}
}
private fun resetSteps() {
tv_totalSteps.setOnClickListener {
Toast.makeText(this, "Long hold to reset steps", Toast.LENGTH_SHORT).show()
}
tv_totalSteps.setOnLongClickListener {
previousSteps = totalSteps
tv_totalSteps.text = 0.toString()
saveData()
true
}
tv_totalStepsMax.setOnClickListener {
tv_totalStepsMax.visibility = View.GONE
et_totalStepsMax.visibility = View.VISIBLE
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(et_totalStepsMax, 0)
}
rL_wrapper.setOnClickListener {
tv_totalStepsMax.visibility = View.VISIBLE
et_totalStepsMax.visibility = View.GONE
if (et_totalStepsMax.text != null && et_totalStepsMax.text.toString().isNotEmpty()) {
goalSteps = Integer.parseInt(et_totalStepsMax.text.toString())
tv_totalStepsMax.text = goalSteps.toString()
progress_circular.progressMax = goalSteps.toFloat()
saveData()
} else {
return#setOnClickListener
}
val inputMethodManager =
getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(et_totalStepsMax.windowToken, 0)
}
}
override fun onPause() {
super.onPause()
saveData()
}
private fun saveData() {
val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putFloat("key1", previousSteps)
editor.putInt("goalKey", goalSteps)
editor.putInt("DATE_KEY", currentDate)
Log.d("MainActivity", "Today is $currentDate")
editor.apply()
}
private fun loadData() {
val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
val savedNumber = sharedPreferences.getFloat("key1", 0f)
val goalNumber = sharedPreferences.getInt("goalKey", 0)
val savedDate = sharedPreferences.getInt("DATE_KEY", 0)
Log.d("MainActivity", "Saved date is $savedDate")
if (currentDate != savedDate) {
previousSteps = totalSteps
tv_totalSteps.text = 0.toString()
saveData()
}
Log.d("MainActivity", "$savedNumber")
goalSteps = goalNumber
tv_totalStepsMax.text = goalSteps.toString()
previousSteps = savedNumber
}
}

You are just rewriting tv_totalStepsMax.text = goalSteps.toString() after resetting the value tv_totalSteps.text = 0.toString().
The code should look like:
if (currentDate != savedDate) {
tv_totalSteps.text = 0.toString()
...
saveData()
} else {
tv_totalStepsMax.text = goalSteps.toString()
...
}

Related

How to add a local filter to calendar using kotlin?

private var modelList: ArrayList<PMDetailResponse.ResultBean>? = null
private var modelListUnchecked: ArrayList<PMDetailResponse.ResultBean>? = null
private lateinit var headerFilter: PMDetailResponse.ResultBean
private var mDetailAdapter: PMDetailAdapter? = null
lateinit var mPreventiveMaintenanceViewModel: PreventiveMaintenanceViewModel
//var mDetailAdapter!!.mAnythingChecked = false
var openedBy: String = ""
var runQuery:String = ""
var noDataReceived = false
companion object {
fun getInstance(): PMWorkOrderDueSoonFragment {
return PMWorkOrderDueSoonFragment()
}
}
private fun handleIncidentListApiResponse(
pmResponses: PMDetailResponse,
isHeaderNeedToAdd: Boolean
) {
mPMResponse = pmResponses
if (pmResponses.result != null) {
var lstResult =
pmResponses.result as ArrayList<PMDetailResponse.ResultBean>
modelList = lstResult
if (lstResult.size > 0) {
setAdapter(
lstResult as ArrayList<PMDetailResponse.ResultBean>,
isHeaderNeedToAdd
)
} else
showNoData(true)
} else
showNoData(true)
}
private fun showNoData(showNoData: Boolean) {
mBindingFragmentGroupBinding.pmAssignedToDeviceRecycerparent.listIncidentNoRecordTv.visibility =
if (showNoData) View.VISIBLE else View.GONE
mBindingFragmentGroupBinding.pmAssignedToDeviceRecycerparent.fragmentIncidentAssigntoHs.visibility =
if (showNoData) View.GONE else View.VISIBLE
}
private fun setAdapter(
lstResult: ArrayList<PMDetailResponse.ResultBean>,
isHeaderNeedToAdd: Boolean
) {
mDetailAdapter = PMDetailAdapter(
lstResult,
this,
true, false, mPreventiveMaintenanceViewModel
)
if (isHeaderNeedToAdd) {
mDetailAdapter!!.addHeader()
}
mBindingFragmentGroupBinding.pmAssignedToDeviceRecycerparent.fragmentIncidentAssigntoDashboardRv.adapter =
mDetailAdapter
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
mBindingFragmentGroupBinding =
DataBindingUtil.inflate(
inflater,
R.layout.fragment_pm_assigned_to_device,
container,
false
)
return mBindingFragmentGroupBinding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
mPMApiViewModel =
ViewModelProvider(this).get(PMApiViewModel::class.java)
mPreventiveMaintenanceViewModel =
ViewModelProvider(this).get(PreventiveMaintenanceViewModel::class.java)
setUIBackground()
setHasOptionsMenu(true)
mPMApiViewModel.callDuePMApi(PMAssignedStatus.DUE)
callPmDueWOObserver()
openedBy = SharedPreferenceManager.getString(
WeakReference<Context>(activity?.baseContext),
SharedPreferenceConstant.shared_pref_login_user_email
).toString()
}
private fun setUIBackground() {
if (AppConstants.themeColor == Color.WHITE) {
assign_layout.setBackgroundColor(Color.WHITE)
fragment_incident_assignto_dashboard_rv.setBackgroundColor(Color.WHITE)
//linear_layout_assigned_to_hs.setBackgroundColor(Color.WHITE)
//list_incident_no_record_tv.setTextColor(Color.BLACK)
} else {
assign_layout.setBackgroundColor(Color.BLACK)
fragment_incident_assignto_dashboard_rv.setBackgroundColor(Color.BLACK)
//linear_layout_assigned_to_hs.setBackgroundColor(Color.BLACK)
//list_incident_no_record_tv.setTextColor(Color.WHITE)
}
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
mMenu = menu
clearMenu()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
val exportMenuItem: MenuItem = menu.findItem(R.id.export_filter)
var feedBackSubmitTextView =
exportMenuItem.actionView.findViewById<Button>(R.id.button_export_bt)
feedBackSubmitTextView.setText(getString(R.string.dispatch_pm_to_me))
val exportActionView: View = exportMenuItem.getActionView()
exportActionView.setOnClickListener(object : View.OnClickListener {
override fun onClick(p0: View?) {
onOptionsItemSelected(exportMenuItem)
}
})
/* val awesomeMenuItem: MenuItem = menu.findItem(R.id.run_filter)
val awesomeActionView: View = awesomeMenuItem.getActionView()
awesomeActionView.setOnClickListener(object : View.OnClickListener {
override fun onClick(p0: View?) {
onOptionsItemSelected(awesomeMenuItem)
}
})*/
menu.findItem(R.id.run_filter).isVisible = true
menu.findItem(R.id.save_filter).isVisible = true
menu.findItem(R.id.save_filter).setIcon(resources.getDrawable(R.drawable.calendar));
menu.findItem(R.id.icons_menu).isVisible = true
menu.findItem(R.id.icons_menu).subMenu.findItem(R.id.action_barcode_scanner).isVisible =
false
menu.findItem(R.id.icons_menu).subMenu.findItem(R.id.attach).isVisible = false
menu.findItem(R.id.icons_menu).subMenu.findItem(R.id.action_soti_device_details).isVisible =
false
menu.findItem(R.id.icons_menu).subMenu.findItem(R.id.run_pm_filter).isVisible = false
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.export_filter -> {
Log.e("HistoricalFrag", "Export Button Selected")
if(!noDataReceived) {
if (mDetailAdapter!!.mAnythingChecked) {
val jsonArray = updateList()
val pmDispatchRequest: PMDispatchRequestArray = PMDispatchRequestArray(jsonArray)
Log.i("jsonArray", "jsonArray::$jsonArray")
//val workOrderObj = JSONObject()
// workOrderObj.put("DispatchInfoList", jsonArray)
//val jsonStr = jsonArray.toString()
//Log.i("TAG", "jsonStr::$jsonStr")
mDetailAdapter!!.mAnythingChecked = false
if (!jsonArray.isEmpty()) {
mPMApiViewModel.callPMDispatchToMe(pmDispatchRequest)
setObserverForDispatchToMeAPI()
} else {
showToast("Please Select The CheckBox")
}
} else {
showToast("Please Select The CheckBox")
}
}else{
showToast("Not allowed")
}
return true
}
R.id.run_filter -> {
if(!noDataReceived) {
runQuery = ""
mDetailAdapter!!.mAnythingChecked = false
var runQuery = runPMFilter()
if (runQuery.isNotEmpty()) {
mDetailAdapter!!.removeHeader()
mDetailAdapter!!.clear()
callPmDueFilterObserver()
mPMApiViewModel.callFilterDuePMApi(runQuery, PMAssignedStatus.FILTER)
} else {
showToast("No Filter Provided")
}
}else{
showToast("Not allowed")
}
return true
}
R.id.save_filter->{
pickFromDateTime()
return true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun clearMenu() {
mMenu.findItem(R.id.action_search).setVisible(false)
mMenu.findItem(R.id.action_settings).setVisible(false)
mMenu.findItem(R.id.action_incident).setVisible(false)
mMenu.findItem(R.id.export_filter).setVisible(true)
mMenu.findItem(R.id.run_filter).setVisible(true)
mMenu.findItem(R.id.icons_menu).setVisible(false)
}
private fun callPmDueWOObserver() {
if (mPMApiViewModel.callDuePMWorkOrderResponseObserver()
?.hasActiveObservers()!!
)
mPMApiViewModel.callDuePMWorkOrderResponseObserver()?.removeObserver(
pmResponseObserver
)!!
pmResponseObserver = Observer { value ->
if (mPMApiViewModel.mIsResponseforDuePmWorkOrder) {
if (value.apiStatus) {
showProgressDialog()
} else {
mPMApiViewModel.mIsResponseforDuePmWorkOrder = false
hideProgressDialog()
try {
if (value.response != null && !value.response.equals(getString(R.string.server_error))) {
if (value.response is PMDetailResponse) {
val mPmList =
value.response as PMDetailResponse
if (mPmList.result?.size!! > 0) {
handleIncidentListApiResponse(mPmList, true)
} else
showDialog(
getString(R.string.error_msg),
getString(R.string.no_response_server),
true
)
}
} else {
showToast(getString(R.string.server_error))
noDataReceived = true
showNoData(true)
}
} catch (ex: SocketTimeoutException) {
ex.printStackTrace()
LogOperation.getLogger().logInfo(
LogLevel.INFO_LOG,
"callPmDueWOObserver - Socket Time Out Exception : $ex"
)
showToast(getString(R.string.socket_timeout_error))
} catch (ex: Exception) {
ex.printStackTrace()
LogOperation.getLogger().logInfo(
LogLevel.INFO_LOG,
"callPmDueWOObserver - Exception : $ex"
)
showToast(getString(R.string.exception_error))
}
}
}
}
mPMApiViewModel.callDuePMWorkOrderResponseObserver()
?.observe(viewLifecycleOwner, pmResponseObserver)
}
private fun callPmDueFilterObserver() {
if (mPMApiViewModel.callFilterPMWorkOrderResponseObserver()
?.hasActiveObservers()!!
)
mPMApiViewModel.callFilterPMWorkOrderResponseObserver()?.removeObserver(
pmResponseObserver
)!!
pmResponseObserver = Observer { value ->
if (mPMApiViewModel.mIsResponseForFilterDuePMWO) {
if (value.apiStatus) {
showProgressDialog()
} else {
mPMApiViewModel.mIsResponseForFilterDuePMWO = false
hideProgressDialog()
try {
if (value.response != null && !value.response.equals(getString(R.string.server_error))) {
if (value.response is PMDetailResponse) {
val mPmList =
value.response as PMDetailResponse
if (mPmList.result?.size!! > 0) {
//handleIncidentListApiResponse(mPmList, true)
mDetailAdapter!!.clear()
mDetailAdapter!!.removeHeader()
mDetailAdapter!!.updateData(mPmList.result as ArrayList<PMDetailResponse.ResultBean>)
mDetailAdapter!!.addHeader()
mDetailAdapter!!.notifyDataSetChanged()
} else
showDialog(
getString(R.string.error_msg),
getString(R.string.no_response_server),
true
)
}
} else {
showToast(getString(R.string.server_error_loading_previous))
changeFragment(R.id.nav_drawer_pm_due_soon,Bundle(),false)
}
} catch (ex: SocketTimeoutException) {
ex.printStackTrace()
LogOperation.getLogger().logInfo(
LogLevel.INFO_LOG,
"callPmDueFilterObserver - Socket Time Out Exception : $ex"
)
showToast(getString(R.string.socket_timeout_error))
} catch (ex: Exception) {
ex.printStackTrace()
LogOperation.getLogger().logInfo(
LogLevel.INFO_LOG,
"callPmDueFilterObserver - Exception : $ex"
)
showToast(getString(R.string.exception_error))
}
}
}
}
mPMApiViewModel.callFilterPMWorkOrderResponseObserver()
?.observe(viewLifecycleOwner, pmResponseObserver)
}
private fun setObserverForDispatchToMeAPI() {
mPMApiViewModel.dispatchToMe()
?.observe(this, Observer { value ->
if (mPMApiViewModel.mIsFromDispatchApiCall) {
if (value.apiStatus) {
showProgressDialog()
} else {
mPMApiViewModel.mIsFromDispatchApiCall = false
hideProgressDialog()
try {
if (value.response is UpdateIncidentMessage) {
val responseValue = value.response as UpdateIncidentMessage
Log.d("CheckMyResponseValue", " - " + responseValue)
if (responseValue.result?.http_status?.equals("201")!!) {
if (modelListUnchecked!!.size == 0) {
mBindingFragmentGroupBinding.pmAssignedToDeviceRecycerparent.fragmentIncidentAssigntoDashboardRv!!.visibility =
View.GONE
}
//showToast("Dispatched ")
showDispatchDialog(
resources.getString(R.string.dispatch_msg),
responseValue.result?.status_message,true
)
} else if (responseValue.result?.http_status?.equals("400")!! ||
responseValue.result?.http_status?.equals("501")!!) {
mDetailAdapter!!.notifyDataSetChanged()
showDispatchDialog(
resources.getString(R.string.error_msg),
responseValue.result?.status_message,false
)
}
else {
showDispatchDialog(
resources.getString(R.string.error_msg),
resources.getString(R.string.update_error_msg),
false
)
}
}
} catch (ex: SocketTimeoutException) {
ex.printStackTrace()
LogOperation.getLogger().logInfo(
LogLevel.INFO_LOG,
"setObserverForDispatchToMeAPI - Socket Time Out Exception : $ex"
)
} catch (ex: Exception) {
ex.printStackTrace()
LogOperation.getLogger().logInfo(
LogLevel.INFO_LOG,
"setObserverForDispatchToMeAPI - Exception : $ex"
)
}
}
}
})
}
fun showDialog(title: String?, message: String?, stayOnSameScreen: Boolean) {
val dialogBuilder = AlertDialog.Builder(activity)
dialogBuilder.setMessage(message)
.setCancelable(false)
.setPositiveButton("Ok", DialogInterface.OnClickListener { dialog, id ->
dialog.dismiss()
if (stayOnSameScreen) {
backToPreviousFragment(true)
}
})
val alert = dialogBuilder.create()
alert.setTitle(title)
alert.show()
}
override fun onItemChangeListener(
position: Int,
model: PMDetailResponse.ResultBean
) {
try {
modelList!![position] = model
mDetailAdapter!!.mAnythingChecked = true
} catch (e: Exception) {
}
}
private fun updateList(): ArrayList<PMDispatchRequest> {
val temp = ArrayList<PMDetailResponse.ResultBean>()
val jsonArray = ArrayList<PMDispatchRequest>()
try {
for (i in modelList!!.indices) {
if (!modelList!![i].isChecked) {
temp.add(modelList!![i])
}else{
Log.i("TAG", "Number[" + i + "]::" + modelList!![i].number)
jsonArray?.add(createDispatchPMToMeQuery(modelList!![i].number))
}
}
} catch (e: Exception) {
}
modelListUnchecked = temp
/* mDetailAdapter!!.setModel(modelListUnchecked as ArrayList<PMDetailResponse.ResultBean>)
mDetailAdapter!!.notifyDataSetChanged()*/
return jsonArray
}
private fun createDispatchPMToMeQuery(number: String?): PMDispatchRequest {
/*{
"u_work_order_number": "WO0018180",
"u_subcategory": "Preventative Maintenance",
"u_category": "Device Maintenance",
"u_assign_to": "Kchawla#plan-group.com"
}*/
val workOrder = PMDispatchRequest(number,"Preventative Maintenance","Device Maintenance",openedBy)
return workOrder
}
fun createFilter(filterOptions: String, filterColumn: String) {
if(filterOptions != ""){
runQuery = if(filterOptions.startsWith("*")) {
if(runQuery == "")
filterColumn+"LIKE"+filterOptions.substring(1)
else
"$runQuery^"+filterColumn+"LIKE"+filterOptions.substring(1)
}else {
if (runQuery == "")
filterColumn+"STARTSWITH"+filterOptions
else
"$runQuery^"+filterColumn+"STARTSWITH"+filterOptions
}
}
}
fun createPMFrequencyFilter(filterOptions: String, filterColumn: String) {
var pmFilter = ""
if(filterOptions != ""){
pmFilter = pmFrequency(filterOptions)
runQuery = if(pmFilter.startsWith("*")) {
if(runQuery == "")
filterColumn+"IN"+ pmFilter.substring(1)
else
"$runQuery^"+filterColumn+"IN"+pmFilter.substring(1)
}else {
if (runQuery == "")
filterColumn+"IN"+pmFilter
else
"$runQuery^"+filterColumn+"IN"+pmFilter
}
}
}
private fun runPMFilter(): String {
createFilter(mDetailAdapter!!.searchedNumber,"number")
createFilter(mDetailAdapter!!.searchedCI,"cmdb_ci.name")
createFilter(mDetailAdapter!!.searchedDeviceLocation,"location.name")
createFilter(mDetailAdapter!!.searchedParent,"location.parent.name")
createFilter(mDetailAdapter!!.searchedDispatchLocation,"u_dispatch_location.name")
createFilter(mDetailAdapter!!.searchedRequestedDueBy,"requested_due_by")
createPMFrequencyFilter(mDetailAdapter!!.searchedPMFrequency,"u_pm_frequency")
createFilter(mDetailAdapter!!.searchedShortDesc,"short_description")
Log.i("TAG", "runQuery::"+runQuery)
if(runQuery.isNotEmpty()){
//val runQueryLength = runQuery.length
runQuery = runQuery.trim()
runQuery += "/"
}else{
runQuery = ""
}
Log.i("finalQuery", "runQueryFinal::"+runQuery)
return runQuery
}
fun pmFrequency(pmFrequency:String):String{
var pmFreq = ""
if(pmFrequency.startsWith("*")){
pmFreq = pmFrequency.substring(1)
}
else{
pmFreq = pmFrequency
}
if("Monthly".contains(pmFreq,ignoreCase = true)
&& "Yearly".contains(pmFreq,ignoreCase = true)){
pmFreq = "Yearly,Monthly"
}else if("Yearly".contains(pmFreq,ignoreCase = true)){
pmFreq = "Yearly"
}else if("Monthly".contains(pmFreq,ignoreCase = true)){
//pmFreq = "*Monthly"
pmFreq = "Monthly"
}
return pmFreq
}
fun showDispatchDialog(title: String?, message: String?,isSuccess:Boolean) {
val dialogBuilder = AlertDialog.Builder(activity)
dialogBuilder.setMessage(message)
.setCancelable(false)
.setPositiveButton(getString(R.string.ok), DialogInterface.OnClickListener { dialog, id ->
if(!isSuccess) {
mDetailAdapter!!.setModel(modelList as ArrayList<PMDetailResponse.ResultBean>)
mDetailAdapter!!.notifyDataSetChanged()
}
else{
mDetailAdapter!!.setModel(modelListUnchecked as ArrayList<PMDetailResponse.ResultBean>)
mDetailAdapter!!.notifyDataSetChanged()
}
dialog.dismiss()
changeFragment(R.id.nav_drawer_pm_due_soon,Bundle(),false)
//backToPreviousFragment(false)
})
val alert = dialogBuilder.create()
alert.setTitle(title)
alert.show()
}
private fun pickFromDateTime() {
val currentDateTime = Calendar.getInstance()
val startYear = currentDateTime.get(Calendar.YEAR)
val startMonth = currentDateTime.get(Calendar.MONTH)
val startDay = currentDateTime.get(Calendar.DAY_OF_MONTH)
val startHour = currentDateTime.get(Calendar.HOUR_OF_DAY)
val startMinute = currentDateTime.get(Calendar.MINUTE)
var mFromDatePicker = DatePickerDialog(requireContext(), DatePickerDialog.OnDateSetListener { _, year, month, day ->
TimePickerDialog(requireContext(), TimePickerDialog.OnTimeSetListener { _, hour, minute ->
val pickedDateTime = Calendar.getInstance()
pickedDateTime.set(year, month, day, hour, minute)
val formatterDateTime = SimpleDateFormat("yyyy-MM-dd HH mm ss")
val formatterDate = SimpleDateFormat("yyyy-MM-dd")
var selectedFromDateTime = formatterDateTime.format(pickedDateTime.time)
var selectedFromDate = formatterDate.format(pickedDateTime.time)
Log.i(ContentValues.TAG, "selectedFromDateTime::$selectedFromDateTime")
pickToDateTime(selectedFromDateTime)
}, startHour, startMinute, false).show()
/*val pickedDateTime = Calendar.getInstance()
pickedDateTime.set(year, month, day)
doSomethingWith(pickedDateTime)*/
}, startYear, startMonth, startDay);
mFromDatePicker.setTitle("FROM");
mFromDatePicker.datePicker.maxDate = System.currentTimeMillis();
mFromDatePicker.show()
}
private fun pickToDateTime(selectedDateTime1: String) {
val currentDateTime = Calendar.getInstance()
val startYear = currentDateTime.get(Calendar.YEAR)
val startMonth = currentDateTime.get(Calendar.MONTH)
val startDay = currentDateTime.get(Calendar.DAY_OF_MONTH)
val startHour = currentDateTime.get(Calendar.HOUR_OF_DAY)
val startMinute = currentDateTime.get(Calendar.MINUTE)
var mToDatePicker = DatePickerDialog(requireContext(), DatePickerDialog.OnDateSetListener { _, year, month, day ->
TimePickerDialog(requireContext(), TimePickerDialog.OnTimeSetListener { _, hour, minute ->
val pickedDateTime = Calendar.getInstance()
pickedDateTime.set(year, month, day, hour, minute)
val formatterDateTime = SimpleDateFormat("yyyy-MM-dd HH mm ss")
var selectedFromDateTime = formatterDateTime.format(pickedDateTime.time)
Log.i(ContentValues.TAG, "selectedToDateTime::$selectedFromDateTime")
}, startHour, startMinute, false).show()
/* val pickedToDateTime = Calendar.getInstance()
pickedToDateTime.set(year, month, day)
doCallChangeFragment(selectedDateTime, pickedToDateTime)*/
}, startYear, startMonth, startDay);
mToDatePicker.setTitle("TO");
mToDatePicker.datePicker.maxDate = System.currentTimeMillis();
mToDatePicker.show()
}
}
This code is being used to pick up from date,time and to date, time using calender feature for filtering data for particular period but the data is not getting filtered, the data for all the month is being displayed .So I need to add local filter for filtering data according to specific date and time using calendar feature.

screen is moving to next question even answer is wrong

I'm coding a quiz app, the main problem here is when an option is clicked question is changed I want that if option is wrong question remain same option become red..
class Level1 : AppCompatActivity(),View.OnClickListener {
lateinit var binding: ActivityLevel1Binding
var mQuestionList=QuestionsAndAnswer.getQuestions()
lateinit var imageView: ImageView
private var mCurrentPosition: Int = 0 // this question in model class//
private var mSelectedOptionPostion: Int = 0 // this is current option where user clicked for answer///
lateinit var progress:ProgressBar
private lateinit var tvOptionOne:TextView
private lateinit var tvOptionTwo:TextView
private lateinit var tvOptionThree:TextView
private lateinit var tvOptionFour:TextView
lateinit var progressBar: ProgressBar
lateinit var tvProgressBar: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLevel1Binding.inflate(layoutInflater)
setContentView(binding.root)
mQuestionList=QuestionsAndAnswer.getQuestions()
setQuestion()
binding.tvOptionFour.setOnClickListener(this)
binding.tvOptionThree.setOnClickListener (this)
binding.tvOptionTwo.setOnClickListener (this)
binding.tvOptionOne.setOnClickListener (this)
binding.progressBar
}
private fun setQuestion() {
setDefault()
imageView=binding.quesImage
binding.apply {
val questions= mQuestionList[mCurrentPosition]
progressBar.progress = mCurrentPosition
tvProgressBar.text = "$mCurrentPosition" + "/" + progressBar.max
binding.quesImage.setImageResource(questions.image)
tvOptionOne.text = questions.optionOne
tvOptionTwo.text = questions.optionTwo
tvOptionThree.text = questions.optionThree
tvOptionFour.text = questions.optionFour
}
}
override fun onClick(v: View?) {
when(v?.id){
R.id.tvOptionOne->{
Selected(1,binding.tvOptionOne)
if( mCurrentPosition != mQuestionList.size-1){
mCurrentPosition ++
setQuestion()
val questions=mQuestionList?.get(mCurrentPosition -1)
if (questions?.correctAnswer!=mSelectedOptionPostion){
AnswerView(mSelectedOptionPostion,R.drawable.wrong_answer)
}
else {
AnswerView(mSelectedOptionPostion,R.drawable.correct_answer)
}
}
else {
val intent=Intent(this#Level1,ScoringActivity::class.java)
startActivity(intent)
finish()
}
}
R.id.tvOptionTwo->{
Selected(2,binding.tvOptionTwo)
if( mCurrentPosition != mQuestionList.size-1){
mCurrentPosition ++
setQuestion()
val questions=mQuestionList?.get(mCurrentPosition -1)
if (questions?.correctAnswer!=mSelectedOptionPostion){
AnswerView(mSelectedOptionPostion,R.drawable.wrong_answer)
mCurrentPosition
Toast.makeText(this,"wrong answer",Toast.LENGTH_SHORT).show()
}
AnswerView(mSelectedOptionPostion,R.drawable.correct_answer)
}
else {
val intent=Intent(this#Level1,ScoringActivity::class.java)
startActivity(intent)
finish()
}
}
R.id.tvOptionThree->{
Selected(3,binding.tvOptionThree)
if( mCurrentPosition != mQuestionList.size-1){
mCurrentPosition ++
setQuestion()
val questions=mQuestionList?.get(mCurrentPosition -1)
if (questions?.correctAnswer!=mSelectedOptionPostion){
AnswerView(mSelectedOptionPostion,R.drawable.wrong_answer)
Toast.makeText(this,"wrong answer",Toast.LENGTH_SHORT).show()
}
else{
AnswerView(mSelectedOptionPostion,R.drawable.correct_answer)
}
}
else {
val intent=Intent(this#Level1,ScoringActivity::class.java)
startActivity(intent)
finish()
}
}
// at last question on wrong answer click no action happens like no wrong answer drawable file is called //
R.id.tvOptionFour->{
Selected(4,binding.tvOptionFour)
if( mCurrentPosition != mQuestionList.size-1){
mCurrentPosition ++
setQuestion()
var questions=mQuestionList?.get(mCurrentPosition -1)
if (questions?.correctAnswer!=mSelectedOptionPostion){
AnswerView(mSelectedOptionPostion,R.drawable.wrong_answer)
}
else {
AnswerView(mSelectedOptionPostion,R.drawable.correct_answer)
}
}
else {
val intent=Intent(this#Level1,ScoringActivity::class.java)
startActivity(intent)
finish()
}
}
}
}
// here answers are maatched //
private fun AnswerView(answer: Int, drawAbleView: Int) {
when (answer) {
1 -> {
binding.tvOptionOne.background = ContextCompat.getDrawable(this, drawAbleView)
}
2 -> {
binding.tvOptionTwo.background = ContextCompat.getDrawable(this, drawAbleView)
}
3 -> {
binding.tvOptionThree.background = ContextCompat.getDrawable(this, drawAbleView)
}
4 -> {
binding.tvOptionFour.background = ContextCompat.getDrawable(this, drawAbleView)
}
}
}
private fun Selected(selected: Int, tv: TextView) {
setDefault()
mSelectedOptionPostion = selected
tv.setTextColor(Color.parseColor("#FF03DAC5"))
tv.setTypeface(tv.typeface, Typeface.BOLD)
tv.background = ContextCompat.getDrawable(this,
R.drawable.selected_tex_view)
}
private fun setDefault() {
val options = ArrayList<TextView>()
options.add(0, binding.tvOptionOne)
options.add(1, binding.tvOptionTwo)
options.add(2, binding.tvOptionThree)
options.add(3, binding.tvOptionFour)
for (option in options) {
option.setTextColor(Color.parseColor("#FF03DAC5"))
option.typeface = Typeface.DEFAULT
option.background = ContextCompat.getDrawable(this, R.drawable.round_text_view)
}
}
}
Try to change your onClick logic like this:
Note that I've declared a couple of methods to avoid code duplication
override fun onClick(v: View?) {
when(v?.id){
R.id.tvOptionOne->{
Selected(1, binding.tvOptionOne)
if(mCurrentPosition < mQuestionList.size){
setQuestion()
checkQuestion()
}
else startScoreActivity()
}
R.id.tvOptionTwo->{
Selected(2,binding.tvOptionTwo)
if(mCurrentPosition < mQuestionList.size){
setQuestion()
checkQuestion()
}
else startScoreActivity()
}
R.id.tvOptionThree->{
Selected(3,binding.tvOptionThree)
if( mCurrentPosition < mQuestionList.size){
setQuestion()
checkQuestion()
}
else startScoreActivity()
}
R.id.tvOptionFour->{
Selected(4,binding.tvOptionFour)
if( mCurrentPosition < mQuestionList.size) {
setQuestion()
}
else startScoreActivity()
}
}
}
private fun checkQuestion() {
var questions=mQuestionList?.get(mCurrentPosition)
if (questions?.correctAnswer!=mSelectedOptionPostion){
AnswerView(mSelectedOptionPostion,R.drawable.wrong_answer)
}
else {
AnswerView(mSelectedOptionPostion,R.drawable.correct_answer)
mCurrentPosition++
}
}
private fun startScoreActivity() {
val intent=Intent(this#Level1,ScoringActivity::class.java)
startActivity(intent)
finish()
}
I guess you should try moving
if (questions?.correctAnswer!=mSelectedOptionPostion) {
AnswerView(mSelectedOptionPostion,R.drawable.wrong_answer)
} else {
mCurrentPosition ++
setQuestion()
AnswerView(mSelectedOptionPostion,R.drawable.correct_answer)
}

"Job was Cancelled" Android Kotlin Coroutines

In my app, there is an EditText that shows date picker dialog and also a spinner. The spinner item contains data from database that is filled after date is set.
It was working normal until in some occasion that I couldn't replicate the error, it shows "Job was cancelled" in Logcat. And when it happened, the spinner is empty.
Here is my fragment code
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
private var isMandatory : Boolean? = true
class AddReportFragment : Fragment(), AdapterView.OnItemSelectedListener {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private lateinit var binding: FragmentAddReportBinding
private lateinit var viewModel: AddReportViewModel
private lateinit var sptransactionType: Spinner
private lateinit var spMandatory: Spinner
private lateinit var spNonMandatory: Spinner
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentAddReportBinding.inflate(inflater)
viewModel = ViewModelProvider(this).get(AddReportViewModel::class.java)
val spBookName : Spinner = binding.spBookName
spMandatory = binding.spMandatory
spNonMandatory = binding.spNonMandatory
sptransactionType = binding.sptransactionType
viewModel.bookName.observe(viewLifecycleOwner, Observer {
it?.let {
var string : String = ""
val listArr = arrayListOf<String>()
for (i in 0 .. it.size - 1){
string = it.get(i).bookName
listArr.add(string)
}
ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, listArr)
.also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spBookName.adapter = adapter
}
}
})
binding.etPeriode.setOnFocusChangeListener { v, hasFocus ->
if(v.hasFocus()){
val showDialog = ShowDatePickerDialog()
showDialog.show(requireFragmentManager(), "Show Date Picker")
}
}
sptransactionType.onItemSelectedListener = this
spBookName.onItemSelectedListener = this
return binding.root
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
if(parent!!.id == R.id.spBookName) {
val selected = parent.selectedItem
viewModel.getBookType(selected.toString())
viewModel.bookType.observe(viewLifecycleOwner, Observer {
it?.let {
if (it.get(0).bookType == "Mandatory") {
ArrayAdapter.createFromResource(requireContext(), R.array.transactionType, android.R.layout.simple_spinner_item)
.also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
sptransactionType.adapter = adapter
}
isMandatory = true
} else if (it.get(0).bookType == "Non Mandatory") {
ArrayAdapter.createFromResource(requireContext(), R.array.transactionType, android.R.layout.simple_spinner_item)
.also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
sptransactionType.adapter = adapter
}
isMandatory = false
}
viewModel.resetBookType()
}
})
viewModel.getMandatoryName(selected.toString())
viewModel.getNonMandatoryName(selected.toString())
viewModel.mandatoryName.observe(viewLifecycleOwner, Observer {
it?.let {
var string : String = ""
val listArr = arrayListOf<String>()
for(i in 0 .. it.size -1){
string = it.get(i).name
listArr.add(string)
}
ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, listArr)
.also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spMandatory.adapter = adapter
}
}
})
viewModel.nonMandatoryName.observe(viewLifecycleOwner, Observer {
it?.let {
var string : String = ""
val listArr = arrayListOf<String>()
for(i in 0 .. it.size -1){
string = it.get(i).name
listArr.add(string)
}
ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, listArr)
.also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spNonMandatory.adapter = adapter
}
}
})
}else if (parent.id == R.id.sptransactionType){
val selected = parent.selectedItem
if(selected == "Plus" && isMandatory == true) {
binding.spMandatory.visibility = View.VISIBLE
binding.spNonMandatory.visibility = View.GONE
binding.etNameNonMandatory.visibility = View.GONE
binding.etNameNonMandatory.setText("")
}else if(selected == "Minus" && isMandatory == true){
binding.spMandatory.visibility = View.GONE
binding.spNonMandatory.visibility = View.VISIBLE
binding.etNameNonMandatory.visibility = View.GONE
binding.etNameNonMandatory.setText("")
}else if(selected == "Minus" && isMandatory == false){
binding.spMandatory.visibility = View.GONE
binding.spNonMandatory.visibility = View.GONE
binding.etNameNonMandatory.visibility = View.GONE
binding.etNameNonMandatory.setText("")
}else if(selected == "Plus" && isMandatory == false){
binding.spMandatory.visibility = View.GONE
binding.spNonMandatory.visibility = View.GONE
binding.etNameNonMandatory.visibility = View.VISIBLE
binding.etNameNonMandatory.setText("")
}else{
binding.spMandatory.visibility = View.GONE
binding.spNonMandatory.visibility = View.GONE
binding.etNameNonMandatory.visibility = View.GONE
binding.etNameNonMandatory.setText("")
}
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {
}
class ShowDatePickerDialog() : DialogFragment(), DatePickerDialog.OnDateSetListener{
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val calendar = Calendar.getInstance()
val day = calendar.get(Calendar.DAY_OF_MONTH)
val month = calendar.get(Calendar.MONTH)
val year = calendar.get(Calendar.YEAR)
return DatePickerDialog(requireContext(), this, year, month, day)
}
override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
val periode = requireActivity().findViewById<EditText>(R.id.etPeriode)
val spNonMandatory: Spinner = requireActivity().findViewById(R.id.spNonMandatory)
val spMandatory: Spinner = requireActivity().findViewById(R.id.spMandatory)
val spBookName: Spinner = requireActivity().findViewById(R.id.spBookName)
val viewModel = ViewModelProvider(this).get(AddReportViewModel::class.java)
val month = month + 1
val givenDate = "$dayOfMonth $month $year"
val givenDateFormat = SimpleDateFormat("dd MM yyyy")
val givenDateParse = givenDateFormat.parse(givenDate)
val resultGivenDate = givenDateParse.time
val givenMonth = "$month"
val givenMonthFormat = SimpleDateFormat("MM")
val givenMonthParse = givenMonthFormat.parse(givenMonth)
val resultGivenMonth = givenMonthParse.time
val monthNow = SimpleDateFormat("MM").format(Date())
val dateFormat = SimpleDateFormat("MM")
val toMil = dateFormat.parse(monthNow)
val result = toMil.time
if(resultGivenMonth == result){
viewModel.getMandatoryName(spBookName.selectedItem.toString())
viewModel.getNonMandatoryName(spBookName.selectedItem.toString())
viewModel.mandatoryName.observe(this, Observer {
it?.let {
var string : String = ""
val listArr = arrayListOf<String>()
for(i in 0 .. it.size -1){
string = it.get(i).name
listArr.add(string)
}
ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, listArr)
.also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spMandatory.adapter = adapter
adapter.notifyDataSetChanged()
}
}
})
viewModel.nonMandatoryName.observe(this, Observer {
it?.let {
var string : String = ""
val listArr = arrayListOf<String>()
for(i in 0 .. it.size -1){
string = it.get(i).name
listArr.add(string)
}
ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, listArr)
.also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spNonMandatory.adapter = adapter
adapter.notifyDataSetChanged()
}
}
})
}else if(resultGivenMonth != result){
viewModel.getAll(spBookName.selectedItem.toString())
viewModel.getAll.observe(this, Observer {
it?.let {
var string : String = ""
val listArr = arrayListOf<String>()
for(i in 0 .. it.size -1){
string = it.get(i).warga
listArr.add(string)
}
ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, listArr)
.also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spNonMandatory.adapter = adapter
adapter.notifyDataSetChanged()
}
ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, listArr)
.also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spMandatory.adapter = adapter
adapter.notifyDataSetChanged()
}
}
})
// viewModel.resetGetAll()
}
periode.setText(SimpleDateFormat("dd MMM yyyy").format(resultGivenDate))
}
}
And ViewModel code
class AddReportViewModel : ViewModel() {
private val _bookName = MutableLiveData<List<GetBookName>>()
val bookName: LiveData<List<GetBookName>>
get() = _bookName
private val _mandatoryName = MutableLiveData<List<GetMandatoryName>>()
val mandatoryName: LiveData<List<GetMandatoryName>>
get() = _mandatoryName
private val _nonMandatoryName = MutableLiveData<List<GetNonMandatoryName>>()
val nonMandatoryName: LiveData<List<GetNonMandatoryName>>
get() = _nonMandatoryName
private val _bookType = MutableLiveData<List<GetBookType>>()
val bookType: LiveData<List<GetBookType>>
get() = _bookType
private val _getAll = MutableLiveData<List<GetAll>>()
val getAll: LiveData<List<GetAll>>
get() = _getAll
init {
getBookName()
}
private fun getBookName() {
viewModelScope.launch {
try {
val bookName = Ebook.retrofitService.getBookName()
_bookName.value = bookName
} catch (exception: Exception) {
_bookName.value = ArrayList()
}
}
}
fun getBookType(bookName: String){
viewModelScope.launch {
try {
val bookType = Ebook.retrofitService.getBookType(bookName)
_bookType.value = bookType
}catch (exception: Exception){
_bookType.value = ArrayList()
}
}
}
fun getMandatoryName(bookName: String){
viewModelScope.launch {
try{
val mandatoryName = Ebook.retrofitService.getMandatory(bookName)
_mandatoryName.value = mandatoryName
}catch (exception: Exception){
Log.e("Exception Message", exception.message.toString())
Log.e("Exception Message", exception.cause.toString())
}
}
}
fun getNonMandatoryName(bookName: String){
viewModelScope.launch {
try{
val nonMandatoryName = Ebook.retrofitService.getNonMandatory(bookName)
_nonMandatoryName.value = nonMandatoryName
}catch (exception: Exception){
Log.e("Exception Message", exception.message.toString())
Log.e("Exception Message", exception.cause.toString())
}
}
}
fun resetBookType(){
_bookType.value = null
}
fun getAll(bookName: String){
viewModelScope.launch {
try{
val getAll = Ekomplek.retrofitService.getAllBayar(bookName)
_getAll.value = getAll
}catch (exception: Exception){
Log.e("Exception Message", exception.message.toString())
}
}
}
fun resetGetAll(){
_getAll.value = null
}
fun resetDonaturDebetKredit(){
_mandatoryName.value = null
_nonMandatoryName.value = null
}
}
As you can see, here on override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int), I'm doing a check whether month now is the same as the month that is selected from date picker dialog. If it's the same, the spinner is filled with a filtered data from database that is matched with the month. And if month now is not the same as the month that is selected, the spinner is filled with all data from database.
Rarely, after I set the date, it shows "Job was cancelled" and the spinner is blank. Most of the time it works, though.
Is there anyway I fix this?
P.S. the same coroutine is also used in other fragments. Even in class AddReportFragment, that coroutine is also used. Everything was fine. No "Job was cancelled". I don't know why sometimes it doesn't work on DatePickerDialog class

How to disable / Remove reCaptcha in firebase phone-auth (OTP) android?

I had Enabled the Google Android Device Verification API.
I had added the SHA-256 onto Firebase setting and updated the GSON file.
and After adding :
Firebase.auth.firebaseAuthSettings.setAppVerificationDisabledForTesting(true)
I am getting error that SafetyNet or Captcha are not succeded (kind of error).
Can anyone tell me how can i disable the captcha check ?
Here is my code
class OTPNewActivity : AppCompatActivity(), OnKeyboardVisibilityListener, View.OnClickListener {
var TAG = "OTPNewActivity"
lateinit var binding: ActivityOtpnewBinding
val action = "android.provider.Telephony.SMS_RECEIVED"
var userEnteredCode = ""
var systemGeneratedCode = ""
var phoneNumer = ""
var phoneDigits = ""
private lateinit var auth: FirebaseAuth
private lateinit var resendToken: PhoneAuthProvider.ForceResendingToken
private var callbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks =
object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(credential: PhoneAuthCredential) {
Log.d(TAG, "onVerificationCompleted: $credential")
val code = credential.smsCode
if (code != null) {
binding.otpView.setText(code)
verifyPhoneNumberWithCode(systemGeneratedCode, code!!)
}
}
override fun onVerificationFailed(e: FirebaseException) {
Log.d(TAG, "onVerificationFailed $e")
if (e is FirebaseAuthInvalidCredentialsException) {
Constants.showToast(
this#OTPNewActivity,
Constants.TOAST_TYPE_FAIL,
"Invalid request"
)
} else if (e is FirebaseTooManyRequestsException) {
Constants.showToast(
this#OTPNewActivity,
Constants.TOAST_TYPE_FAIL,
"The SMS quota for the project has been exceeded $e"
)
} else {
Constants.showToast(
this#OTPNewActivity,
Constants.TOAST_TYPE_FAIL, "Something wents wrong"
)
}
}
override fun onCodeSent(
verificationId: String,
token: PhoneAuthProvider.ForceResendingToken
) {
// The SMS verification code has been sent to the provided phone number, we
// now need to ask the user to enter the code and then construct a credential
// by combining the code with a verification ID.
Log.d(TAG, "onCodeSent: $verificationId")
systemGeneratedCode = verificationId
resendToken = token
countdownTimer()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_otpnew)
initListeners()
}
private fun initListeners() {
LocalSharedPreference.getInstance(this).isPhoneNumberVerified = false
// Firebase.auth.firebaseAuthSettings.setAppVerificationDisabledForTesting(true)
auth = Firebase.auth
setKeyboardVisibilityListener(this)
binding.btnNext.setOnClickListener(this)
binding.tvCount.setOnClickListener(this)
binding.icBack.setOnClickListener(this)
val intent = intent
intent?.let {
phoneNumer = intent.getStringExtra(Constants.PHONE_NUMBER).toString()
phoneDigits = intent.getStringExtra(Constants.SAVE_PHONE_DIGITS).toString()
binding.textView.text =
"${this.resources.getString(R.string.digit_code)} $phoneNumer"
val options = PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(phoneNumer)
.setTimeout(15L, TimeUnit.SECONDS)
.setActivity(this)
.setCallbacks(callbacks)
.build()
PhoneAuthProvider.verifyPhoneNumber(options)
}
binding.otpView.setOtpCompletionListener(OnOtpCompletionListener { otp -> // do Stuff
userEnteredCode = otp
binding.icNext.visibility = View.VISIBLE
binding.pbNext.visibility = View.GONE
verifyPhoneNumberWithCode(systemGeneratedCode, userEnteredCode)
})
}
private fun verifyPhoneNumberWithCode(verificationId: String?, code: String) {
try {
val credential = PhoneAuthProvider.getCredential(verificationId!!, code)
signInWithPhoneAuthCredential(credential);
} catch (e: Exception) {
binding.otpView.setText("")
Constants.showToast(
this#OTPNewActivity,
Constants.TOAST_TYPE_FAIL,
this#OTPNewActivity.resources.getString(R.string.wrong_Code)
)
e.printStackTrace()
}
}
private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) {
auth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success")
LocalSharedPreference.getInstance(this).isPhoneNumberVerified = true
if (phoneNumer.contains("+52")) {
LocalSharedPreference.getInstance(this).setSaveCountry("MX")
} else if (phoneNumer.contains("+92")) {
LocalSharedPreference.getInstance(this).setSaveCountry("PK")
} else if (phoneNumer.contains("+1")) {
LocalSharedPreference.getInstance(this).setSaveCountry("US")
}
LocalSharedPreference.getInstance(this).savePhoneNumber(phoneNumer)
LocalSharedPreference.getInstance(this).setPhoneDigits(phoneDigits)
val user = task.result?.user
val intent = Intent(this#OTPNewActivity, ProfileActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(intent)
finish()
} else {
// Sign in failed, display a message and update the UI
Log.w(TAG, "signInWithCredential:failure", task.exception)
if (task.exception is FirebaseAuthInvalidCredentialsException) {
Constants.showToast(
this#OTPNewActivity,
Constants.TOAST_TYPE_FAIL,
"${task.exception}"
)
}
// Update UI
}
}
}
private fun setKeyboardVisibilityListener(onKeyboardVisibilityListener: OnKeyboardVisibilityListener) {
val parentView: View = (findViewById<View>(android.R.id.content) as ViewGroup).getChildAt(0)
parentView.getViewTreeObserver()
.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
private var alreadyOpen = false
private val defaultKeyboardHeightDP = 100
private val EstimatedKeyboardDP =
defaultKeyboardHeightDP + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) 48 else 0
private val rect: Rect = Rect()
override fun onGlobalLayout() {
val estimatedKeyboardHeight = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
EstimatedKeyboardDP.toFloat(),
parentView.getResources().getDisplayMetrics()
)
.toInt()
parentView.getWindowVisibleDisplayFrame(rect)
val heightDiff: Int =
parentView.getRootView().getHeight() - (rect.bottom - rect.top)
val isShown = heightDiff >= estimatedKeyboardHeight
if (isShown == alreadyOpen) {
Log.d("Keyboard state", "Ignoring global layout change...")
return
}
alreadyOpen = isShown
onKeyboardVisibilityListener.onVisibilityChanged(isShown)
}
})
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
// Checks whether a hardware keyboard is available
if (newConfig.hardKeyboardHidden === Configuration.HARDKEYBOARDHIDDEN_NO) {
Toast.makeText(this, "keyboard visible", Toast.LENGTH_SHORT).show()
} else if (newConfig.hardKeyboardHidden === Configuration.HARDKEYBOARDHIDDEN_YES) {
Toast.makeText(this, "keyboard hidden", Toast.LENGTH_SHORT).show()
}
}
override fun onVisibilityChanged(visible: Boolean) {
if (!visible) {
val imm: InputMethodManager =
getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(binding.otpView, InputMethodManager.SHOW_IMPLICIT)
}
}
override fun onResume() {
super.onResume()
binding.otpView.requestFocus()
val imm: InputMethodManager =
getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(binding.otpView, InputMethodManager.SHOW_IMPLICIT)
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
registerReceiver(receiver, IntentFilter(action))
}
private fun countdownTimer() {
binding.pbNext.visibility = View.VISIBLE
binding.icNext.visibility = View.GONE
object : CountDownTimer(15000, 1000) {
override fun onTick(millisUntilFinished: Long) {
binding.tvCount.setText("Resend Code in : " + millisUntilFinished / 1000)
}
override fun onFinish() {
binding.tvCount.setText("I didn`t receive a code")
binding.icNext.visibility = View.VISIBLE
binding.pbNext.visibility = View.GONE
}
}.start()
}
override fun onClick(view: View) {
when (view.id) {
R.id.btn_next -> {
if (binding.otpView.text.toString().length == 6) {
LocalSharedPreference.getInstance(this#OTPNewActivity).isPhoneNumberVerified =
true
verifyPhoneNumberWithCode(systemGeneratedCode, userEnteredCode)
}
}
R.id.tv_count -> {
if (binding.tvCount.text.equals(this#OTPNewActivity.resources.getString(R.string.i_dont_received_code)))
resendVerificationCode(phoneNumer, resendToken)
}
R.id.ic_back -> {
finish()
}
}
}
private fun resendVerificationCode(
phoneNumber: String,
token: PhoneAuthProvider.ForceResendingToken?
) {
val optionsBuilder = PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(phoneNumber) // Phone number to verify
.setTimeout(15L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(callbacks) // OnVerificationStateChangedCallbacks
if (token != null) {
optionsBuilder.setForceResendingToken(token) // callback's ForceResendingToken
}
PhoneAuthProvider.verifyPhoneNumber(optionsBuilder.build())
}
var receiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent) {
if (intent.action == "android.provider.Telephony.SMS_RECEIVED") {
val bundle = intent.extras
var msgs: Array<SmsMessage?>? = null
var msg_from: String? = ""
Log.d(TAG, "onReceive called ")
if (bundle != null) {
try {
val pdus = bundle["pdus"] as Array<Any>?
msgs = arrayOfNulls(pdus!!.size)
for (i in msgs.indices) {
msgs[i] = SmsMessage.createFromPdu(pdus[i] as ByteArray)
msg_from = msgs[i]!!.getOriginatingAddress()
val msgBody: String = msgs[i]!!.getMessageBody()
if (msgBody.contains("is your verification code for running-errands.firebaseapp.com")) {
val _1: Char = msgBody[0]
val _2: Char = msgBody[1]
val _3: Char = msgBody[2]
val _4: Char = msgBody[3]
val _5: Char = msgBody[4]
val _6: Char = msgBody[5]
val code: String =
_1.toString() + _2.toString() + _3.toString() + _4.toString() + _5.toString() + _6.toString()
// binding.otpView.text = SpannableStringBuilder(code!!)
binding.otpView.setText(code)
verifyPhoneNumberWithCode(systemGeneratedCode, code!!)
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(receiver);
}
}

I want that when I press hardware back button in SongPlayingFragment I should return to main screen. How can I do it?

package com.shivamkapila.echo.fragments
import android.app.Activity
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.media.AudioManager
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.util.Log
import android.view.*
import android.widget.ImageButton
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import com.cleveroad.audiovisualization.AudioVisualization
import com.cleveroad.audiovisualization.DbmHandler
import com.cleveroad.audiovisualization.GLAudioVisualizationView
import com.shivamkapila.echo.CurrentSongHelper
import com.shivamkapila.echo.R
import com.shivamkapila.echo.Songs
import com.shivamkapila.echo.activities.MainActivity
import com.shivamkapila.echo.databases.EchoDatabase
import com.shivamkapila.echo.utils.SeekBarController
import java.util.*
import java.util.concurrent.TimeUnit
class SongPlayingFragment : Fragment() {
object Statified {
var myActivity: Activity? = null
var mediaPlayer: MediaPlayer? = null
var startTimeNext: TextView? = null
var endTimeNext: TextView? = null
var playPauseImageButton: ImageButton? = null
var previousImageButton: ImageButton? = null
var nextImageButton: ImageButton? = null
var loopImageButton: ImageButton? = null
var seekbar: SeekBar? = null
var songArtistView: TextView? = null
var songTitleView: TextView? = null
var shuffleImageButton: ImageButton? = null
var check: Boolean = true
var _currentPosition: Int = 0
var fetchSongs: ArrayList<Songs>? = null
var currentSongHelper: CurrentSongHelper? = null
var audioVisualization: AudioVisualization? = null
var glView: GLAudioVisualizationView? = null
var fab: ImageButton? = null
var favoriteContent: EchoDatabase? = null
var counter: Int = 0
var mSensorManager: SensorManager? = null
var mSensorListener: SensorEventListener? = null
var MY_PREFS_NAME = "ShakeFeature"
var back: String? = null
var updateSongTime = object : Runnable {
override fun run() {
try {
val getCurrent = Statified.mediaPlayer?.getCurrentPosition()
startTimeNext?.setText(String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(getCurrent?.toLong() as Long),
TimeUnit.MILLISECONDS.toSeconds(getCurrent?.toLong() as Long) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(getCurrent?.toLong() as Long))))
seekbar?.setProgress(getCurrent?.toInt() as Int)
Statified.check = true
Handler().postDelayed(this, 1000)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
object Staticated {
var MY_PREFS_SHUFFLE = "Shuffle feature"
var MY_PREFS_LOOP = "Loop feature"
fun onSongComplete() {
if (Statified.currentSongHelper?.isShuffle as Boolean) {
playNext("PlayNextLikeNormalShuffle")
Statified.currentSongHelper?.isPlaying = true
} else {
if (Statified.currentSongHelper?.isLoop as Boolean) {
Statified.currentSongHelper?.isPlaying = true
var nextSong = Statified.fetchSongs?.get(Statified._currentPosition)
Statified.currentSongHelper?.songPath = nextSong?.songData
Statified.currentSongHelper?.songTitle = nextSong?.songTitle
Statified.currentSongHelper?.songArtist = nextSong?.artist
Statified.currentSongHelper?.songId = nextSong?.songID as Long
Statified.currentSongHelper?.currentPosition = Statified._currentPosition
updateTextViews(Statified.currentSongHelper?.songTitle as String, Statified.currentSongHelper?.songArtist as String)
Statified.mediaPlayer?.reset()
try {
Statified.mediaPlayer?.setDataSource(Statified.myActivity, Uri.parse(Statified.currentSongHelper?.songPath) as Uri)
Statified.mediaPlayer?.prepare()
Statified.mediaPlayer?.start()
processInformation(Statified.mediaPlayer as MediaPlayer)
} catch (e: Exception) {
e.printStackTrace()
}
} else {
playNext("PlayNextNormal")
Statified.currentSongHelper?.isPlaying = true
}
}
if (Statified.favoriteContent?.checkifIdExists(Statified.currentSongHelper?.songId?.toInt() as Int) as Boolean) {
Statified.fab?.setImageDrawable(ContextCompat.getDrawable(Statified.myActivity, R.drawable.favorite_on))
} else {
Statified.fab?.setImageDrawable(ContextCompat.getDrawable(Statified.myActivity, R.drawable.favorite_off))
}
}
fun updateTextViews(songTitle: String, songArtist: String) {
var songTitleUpdated = songTitle
var songArtistUpdated = songArtist
if (songTitle.equals("<unknown>", true)) {
songTitleUpdated = "unknown"
}
if (songArtist.equals("<unknown>", true)) {
songArtistUpdated = "unknown"
}
Statified.songTitleView?.setText(songTitleUpdated)
Statified.songArtistView?.setText(songArtistUpdated)
}
fun processInformation(mediaPlayer: MediaPlayer) {
val finalTime = mediaPlayer.duration
val startTime = mediaPlayer.currentPosition
Statified.seekbar?.max = finalTime
Statified.startTimeNext?.setText(String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(startTime.toLong()),
TimeUnit.MILLISECONDS.toSeconds(startTime.toLong()) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(startTime.toLong()))))
Statified.endTimeNext?.setText(String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(finalTime.toLong()),
TimeUnit.MILLISECONDS.toSeconds(finalTime.toLong()) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(finalTime.toLong()))))
Statified.seekbar?.setProgress(startTime)
Handler().postDelayed(Statified.updateSongTime, 1000)
}
fun playNext(check: String) {
if (check.equals("PlayNextNormal", true)) {
Statified._currentPosition = Statified._currentPosition + 1
} else if (check.equals("PlayNextLikeNormalShuffle", true)) {
var randomObject = Random()
var randomPosition = randomObject.nextInt(Statified.fetchSongs?.size?.plus(1) as Int)
Statified._currentPosition = randomPosition
}
if (Statified._currentPosition == Statified.fetchSongs?.size) {
Statified._currentPosition = 0
}
Statified.currentSongHelper?.isLoop = false
var nextSong = Statified.fetchSongs?.get(Statified._currentPosition)
Statified.currentSongHelper?.songPath = nextSong?.songData
Statified.currentSongHelper?.songTitle = nextSong?.songTitle
Statified.currentSongHelper?.songArtist = nextSong?.artist
Statified.currentSongHelper?.songId = nextSong?.songID as Long
Statified.currentSongHelper?.currentPosition = Statified._currentPosition
var editorLoop = Statified.myActivity?.getSharedPreferences(Staticated.MY_PREFS_LOOP, Context.MODE_PRIVATE)?.edit()
Statified.currentSongHelper?.isLoop = false
Statified.loopImageButton?.setBackgroundResource(R.drawable.loop_white_icon)
editorLoop?.putBoolean("feature", false)
editorLoop?.apply()
if (Statified.currentSongHelper?.isPlaying as Boolean) {
Statified.playPauseImageButton?.setBackgroundResource(R.drawable.pause_icon)
} else {
Statified.playPauseImageButton?.setBackgroundResource(R.drawable.play_icon)
}
updateTextViews(Statified.currentSongHelper?.songTitle as String, Statified.currentSongHelper?.songArtist as String)
Statified.mediaPlayer?.reset()
try {
Statified.mediaPlayer?.setDataSource(Statified.myActivity, Uri.parse(Statified.currentSongHelper?.songPath) as Uri)
Statified.mediaPlayer?.prepare()
Statified.mediaPlayer?.start()
Staticated.processInformation(Statified.mediaPlayer as MediaPlayer)
processInformation(Statified.mediaPlayer as MediaPlayer)
} catch (e: Exception) {
e.printStackTrace()
}
if (Statified.favoriteContent?.checkifIdExists(Statified.currentSongHelper?.songId?.toInt() as Int) as Boolean) {
Statified.fab?.setImageDrawable(ContextCompat.getDrawable(Statified.myActivity, R.drawable.favorite_on))
} else {
Statified.fab?.setImageDrawable(ContextCompat.getDrawable(Statified.myActivity, R.drawable.favorite_off))
}
}
fun playPrevious() {
Statified._currentPosition = Statified._currentPosition - 1
if (Statified._currentPosition == -1) {
Statified._currentPosition = 0
}
if (Statified.currentSongHelper?.isPlaying as Boolean) {
Statified.playPauseImageButton?.setBackgroundResource(R.drawable.pause_icon)
} else {
Statified.playPauseImageButton?.setBackgroundResource(R.drawable.play_icon)
}
Statified.currentSongHelper?.isLoop = false
var nextSong = Statified.fetchSongs?.get(Statified._currentPosition)
Statified.currentSongHelper?.songPath = nextSong?.songData
Statified.currentSongHelper?.songTitle = nextSong?.songTitle
Statified.currentSongHelper?.songArtist = nextSong?.artist
Statified.currentSongHelper?.songId = nextSong?.songID as Long
Statified.currentSongHelper?.currentPosition = Statified._currentPosition
Staticated.updateTextViews(Statified.currentSongHelper?.songTitle as String, Statified.currentSongHelper?.songArtist as String)
Statified.mediaPlayer?.reset()
try {
Statified.mediaPlayer?.setDataSource(Statified.myActivity, Uri.parse(Statified.currentSongHelper?.songPath) as Uri)
Statified.mediaPlayer?.prepare()
Statified.mediaPlayer?.start()
Staticated.processInformation(Statified.mediaPlayer as MediaPlayer)
processInformation(Statified.mediaPlayer as MediaPlayer)
} catch (e: Exception) {
e.printStackTrace()
}
if (Statified.favoriteContent?.checkifIdExists(Statified.currentSongHelper?.songId?.toInt() as Int) as Boolean) {
Statified.fab?.setImageDrawable(ContextCompat.getDrawable(Statified.myActivity, R.drawable.favorite_on))
} else {
Statified.fab?.setImageDrawable(ContextCompat.getDrawable(Statified.myActivity, R.drawable.favorite_off))
}
}
}
var mAcceleration: Float = 0f
var mAccelerationCurrent: Float = 0f
var mAccelerationLast: Float = 0f
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val view = inflater!!.inflate(R.layout.fragment_song_playing, container, false)
setHasOptionsMenu(true)
activity.title = "Now Playing"
Statified.seekbar = view?.findViewById(R.id.seekBar)
Statified.startTimeNext = view?.findViewById(R.id.startTime)
Statified.endTimeNext = view?.findViewById(R.id.endTime)
Statified.playPauseImageButton = view?.findViewById(R.id.playPauseButton)
Statified.nextImageButton = view?.findViewById(R.id.nextButton)
Statified.previousImageButton = view?.findViewById(R.id.previousButton)
Statified.loopImageButton = view?.findViewById(R.id.loopButton)
Statified.shuffleImageButton = view?.findViewById(R.id.shuffleButton)
Statified.songArtistView = view?.findViewById(R.id.songArtist)
Statified.songTitleView = view?.findViewById(R.id.songTitle)
Statified.glView = view?.findViewById(R.id.visualizer_view)
Statified.fab = view?.findViewById(R.id.favoriteIcon)
Statified.fab?.alpha = 0.8f
return view
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Statified.audioVisualization = Statified.glView as AudioVisualization
}
override fun onAttach(context: Context?) {
super.onAttach(context)
Statified.myActivity = context as Activity
}
override fun onAttach(activity: Activity?) {
super.onAttach(activity)
Statified.myActivity = activity
}
override fun onResume() {
super.onResume()
Statified.audioVisualization?.onResume()
Statified.mSensorManager?.registerListener(Statified.mSensorListener, Statified.mSensorManager?.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL)
}
override fun onPause() {
Statified.audioVisualization?.onPause()
Statified.mSensorManager?.unregisterListener(Statified.mSensorListener)
super.onPause()
}
override fun onDestroyView() {
super.onDestroyView()
Statified.audioVisualization?.release()
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
Statified.currentSongHelper = CurrentSongHelper()
Statified.currentSongHelper?.isPlaying = true
Statified.currentSongHelper?.isLoop = false
Statified.currentSongHelper?.isShuffle = false
Statified.favoriteContent = EchoDatabase(Statified.myActivity)
var path: String? = null
var _songTitle: String? = null
var _songArtist: String? = null
var songId: Long = 0
var fromFavBottomBar: String? = null
var fromMainScreenBottomBar: String? = null
try {
path = arguments.getString("path")
_songTitle = arguments.getString("songTitle")
_songArtist = arguments.getString("songArtist")
songId = arguments.getInt("songId").toLong()
Statified._currentPosition = arguments.getInt("songPosition")
Statified.fetchSongs = arguments.getParcelableArrayList("songData")
Statified.currentSongHelper?.songPath = path
Statified.currentSongHelper?.songTitle = _songTitle
Statified.currentSongHelper?.songArtist = _songArtist
Statified.currentSongHelper?.songId = songId
Statified.currentSongHelper?.currentPosition = Statified._currentPosition
fromFavBottomBar = arguments.get("FavBottomBar") as? String
fromMainScreenBottomBar = arguments.get("MainScreenBottomBar") as? String
Staticated.updateTextViews(Statified.currentSongHelper?.songTitle as String, Statified.currentSongHelper?.songArtist as String)
} catch (e: Exception) {
e.printStackTrace()
}
if (fromFavBottomBar != null) {
Statified.mediaPlayer = FavoriteFragment.Statified.mediaPlayer
Staticated.processInformation(Statified.mediaPlayer as MediaPlayer)
} else if (fromMainScreenBottomBar != null) {
Statified.mediaPlayer = MainScreenFragment.Statified.mediaPlayer
Staticated.processInformation(Statified.mediaPlayer as MediaPlayer)
} else {
Statified.mediaPlayer = MediaPlayer()
Statified.mediaPlayer?.setAudioStreamType(AudioManager.STREAM_MUSIC)
try {
Statified.mediaPlayer?.setDataSource(Statified.myActivity, Uri.parse(path) as Uri)
Statified.mediaPlayer?.prepare()
} catch (e: Exception) {
e.printStackTrace()
}
Statified.mediaPlayer?.start()
Staticated.processInformation(Statified.mediaPlayer as MediaPlayer)
}
Staticated.processInformation(Statified.mediaPlayer as MediaPlayer)
if (Statified.mediaPlayer?.isPlaying as Boolean) {
Statified.playPauseImageButton?.setBackgroundResource(R.drawable.pause_icon)
} else {
Statified.playPauseImageButton?.setBackgroundResource(R.drawable.play_icon)
}
Statified.mediaPlayer?.setOnCompletionListener {
Staticated.onSongComplete()
}
clickHandler()
var visualizationHandler = DbmHandler.Factory.newVisualizerHandler(Statified.myActivity as Context, 0)
Statified.audioVisualization?.linkTo(visualizationHandler)
var prefsForShuffle = Statified.myActivity?.getSharedPreferences(Staticated.MY_PREFS_SHUFFLE, Context.MODE_PRIVATE)
var isShuffleAllowed = prefsForShuffle?.getBoolean("feature", false)
if (isShuffleAllowed as Boolean) {
Statified.currentSongHelper?.isShuffle = true
Statified.currentSongHelper?.isLoop = false
Statified.shuffleImageButton?.setBackgroundResource(R.drawable.shuffle_icon)
Statified.loopImageButton?.setBackgroundResource(R.drawable.loop_white_icon)
} else {
Statified.currentSongHelper?.isShuffle = false
Statified.shuffleImageButton?.setBackgroundResource(R.drawable.shuffle_white_icon)
}
var prefsForLoop = Statified.myActivity?.getSharedPreferences(Staticated.MY_PREFS_LOOP, Context.MODE_PRIVATE)
var isLoopAllowed = prefsForLoop?.getBoolean("feature", false)
if (isLoopAllowed as Boolean) {
Statified.currentSongHelper?.isShuffle = false
Statified.currentSongHelper?.isLoop = true
Statified.shuffleImageButton?.setBackgroundResource(R.drawable.shuffle_white_icon)
Statified.loopImageButton?.setBackgroundResource(R.drawable.loop_icon)
} else {
Statified.currentSongHelper?.isLoop = false
Statified.loopImageButton?.setBackgroundResource(R.drawable.loop_white_icon)
}
if (Statified.favoriteContent?.checkifIdExists(Statified.currentSongHelper?.songId?.toInt() as Int) as Boolean) {
Statified.fab?.setImageDrawable(ContextCompat.getDrawable(Statified.myActivity, R.drawable.favorite_on))
} else {
Statified.fab?.setImageDrawable(ContextCompat.getDrawable(Statified.myActivity, R.drawable.favorite_off))
}
seekbarHandler()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Statified.mSensorManager = Statified.myActivity?.getSystemService(Context.SENSOR_SERVICE) as SensorManager
mAcceleration = 0.0f
mAccelerationCurrent = SensorManager.GRAVITY_EARTH
mAccelerationLast = SensorManager.GRAVITY_EARTH
bindShakeListener()
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
menu?.clear()
inflater?.inflate(R.menu.song_playing_menu, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onPrepareOptionsMenu(menu: Menu?) {
super.onPrepareOptionsMenu(menu)
val item: MenuItem? = menu?.findItem(R.id.action_redirect)
item?.isVisible = true
val item2: MenuItem? = menu?.findItem(R.id.action_sort)
item2?.isVisible = false
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.action_redirect -> {
var pos = 0
if (Statified.back.equals("Favorite", true)) {
pos = 0
}
if (Statified.back.equals("MainScreen", true)) {
pos = 1
}
if (pos == 1) {
val mainScreenFragment = MainScreenFragment()
(context as MainActivity).supportFragmentManager
.beginTransaction()
.replace(R.id.details_fragment, mainScreenFragment)
.commit()
}
if (pos == 0) {
val favoriteFragment = FavoriteFragment()
(context as MainActivity).supportFragmentManager
.beginTransaction()
.replace(R.id.details_fragment, favoriteFragment)
.commit()
}
return false
}
}
return false
}
fun clickHandler() {
Statified.fab?.setOnClickListener({
if (Statified.favoriteContent?.checkifIdExists(Statified.currentSongHelper?.songId?.toInt() as Int) as Boolean) {
Statified.fab?.setImageDrawable(ContextCompat.getDrawable(Statified.myActivity, R.drawable.favorite_off))
Statified.favoriteContent?.deleteFavourite(Statified.currentSongHelper?.songId?.toInt() as Int)
Toast.makeText(Statified.myActivity, "Removed from favorites", Toast.LENGTH_SHORT).show()
} else {
Statified.fab?.setImageDrawable(ContextCompat.getDrawable(Statified.myActivity, R.drawable.favorite_on))
Statified.favoriteContent?.storeAsFavorite(Statified.currentSongHelper?.songId?.toInt(), Statified.currentSongHelper?.songArtist,
Statified.currentSongHelper?.songTitle, Statified.currentSongHelper?.songPath)
Toast.makeText(Statified.myActivity, "Added to Favorites", Toast.LENGTH_SHORT).show()
}
})
Statified.shuffleImageButton?.setOnClickListener({
var editorShuffle = Statified.myActivity?.getSharedPreferences(Staticated.MY_PREFS_SHUFFLE, Context.MODE_PRIVATE)?.edit()
var editorLoop = Statified.myActivity?.getSharedPreferences(Staticated.MY_PREFS_LOOP, Context.MODE_PRIVATE)?.edit()
if (Statified.currentSongHelper?.isShuffle as Boolean) {
Statified.currentSongHelper?.isShuffle = false
Statified.shuffleImageButton?.setBackgroundResource(R.drawable.shuffle_white_icon)
editorShuffle?.putBoolean("feature", false)
editorShuffle?.apply()
} else {
Statified.currentSongHelper?.isLoop = false
Statified.currentSongHelper?.isShuffle = true
Statified.loopImageButton?.setBackgroundResource(R.drawable.loop_white_icon)
Statified.shuffleImageButton?.setBackgroundResource(R.drawable.shuffle_icon)
editorShuffle?.putBoolean("feature", true)
editorShuffle?.apply()
editorLoop?.putBoolean("feature", false)
editorLoop?.apply()
}
})
Statified.nextImageButton?.setOnClickListener({
Statified.currentSongHelper?.isPlaying = true
if (Statified.currentSongHelper?.isLoop as Boolean) {
Statified.loopImageButton?.setBackgroundResource(R.drawable.loop_white_icon)
}
if (Statified.currentSongHelper?.isShuffle as Boolean) {
Staticated.playNext("PlayNextLikeNormalShuffle")
} else {
Staticated.playNext("PlayNextNormal")
}
})
Statified.previousImageButton?.setOnClickListener({
Statified.currentSongHelper?.isPlaying = true
if (Statified.currentSongHelper?.isLoop as Boolean) {
Statified.loopImageButton?.setBackgroundResource(R.drawable.loop_white_icon)
}
Staticated.playPrevious()
})
Statified.loopImageButton?.setOnClickListener({
var editorShuffle = Statified.myActivity?.getSharedPreferences(Staticated.MY_PREFS_SHUFFLE, Context.MODE_PRIVATE)?.edit()
var editorLoop = Statified.myActivity?.getSharedPreferences(Staticated.MY_PREFS_LOOP, Context.MODE_PRIVATE)?.edit()
if (Statified.currentSongHelper?.isLoop as Boolean) {
Statified.currentSongHelper?.isLoop = false
Statified.loopImageButton?.setBackgroundResource(R.drawable.loop_white_icon)
editorLoop?.putBoolean("feature", false)
editorLoop?.apply()
} else {
Statified.currentSongHelper?.isLoop = true
Statified.currentSongHelper?.isShuffle = false
Statified.loopImageButton?.setBackgroundResource(R.drawable.loop_icon)
Statified.shuffleImageButton?.setBackgroundResource(R.drawable.shuffle_white_icon)
editorLoop?.putBoolean("feature", true)
editorLoop?.apply()
editorShuffle?.putBoolean("feature", false)
editorShuffle?.apply()
}
})
Statified.playPauseImageButton?.setOnClickListener({
if (Statified.mediaPlayer?.isPlaying as Boolean) {
Statified.mediaPlayer?.pause()
Statified.currentSongHelper?.isPlaying = false
Statified.playPauseImageButton?.setBackgroundResource(R.drawable.play_icon)
} else {
Statified.mediaPlayer?.start()
Statified.currentSongHelper?.isPlaying = true
Statified.playPauseImageButton?.setBackgroundResource(R.drawable.pause_icon)
Staticated.processInformation(Statified.mediaPlayer as MediaPlayer)
}
})
}
fun bindShakeListener() {
Statified.mSensorListener = object : SensorEventListener {
override fun onAccuracyChanged(p0: Sensor?, p1: Int) {
}
override fun onSensorChanged(p0: SensorEvent) {
val x = p0.values[0]
val y = p0.values[1]
val z = p0.values[2]
mAccelerationLast = mAccelerationCurrent
mAccelerationCurrent = Math.sqrt(((x * x + y * y + z * z).toDouble())).toFloat()
val delta = mAccelerationCurrent - mAccelerationLast
mAcceleration = mAcceleration * 0.9f + delta
if (mAcceleration > 12) {
println("11111")
val prefs = Statified.myActivity?.getSharedPreferences(Statified.MY_PREFS_NAME, Context.MODE_PRIVATE)
val isAllowed = prefs?.getBoolean("feature", false)
if (isAllowed as Boolean && Statified.check == true) {
Statified.currentSongHelper?.isPlaying = true
if (Statified.currentSongHelper?.isLoop as Boolean) {
Statified.loopImageButton?.setBackgroundResource(R.drawable.loop_white_icon)
}
if (Statified.currentSongHelper?.isShuffle as Boolean) {
Staticated.playNext("PlayNextLikeNormalShuffle")
} else {
Staticated.playNext("PlayNextNormal")
}
Statified.check = false
}
}
}
}
}
fun seekbarHandler() {
val seekbarListener = SeekBarController()
Statified.seekbar?.setOnSeekBarChangeListener(seekbarListener)
}
Let try this ,
This is java code Just u can convert to kotlin it will work fine.
In your Activity
Declare a static variable
public static boolean IS_MUSIC_SCREEN = false;
Implement this method
#Override
public void onBackPressed() {
if (IS_MUSIC_SCREEN) {
IS_MUSIC_SCREEN=false;
startActivity(new Activity(this,MainActivity.class));
}else{
super.onBackPressed();
}
}
In your Fragment,
IS_MUSIC_SCREEN is true set in onCreateView
Like this ,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_song_playing, container, false);
MainActivity.IS_MUSIC_SCREEN =true;
return view;
}
A simple approach would be to initialise a BackHandler mechanism with the Fragment. I have such an approach with my BaseFragment class that would return a boolean to true if the back action is to be handled by the fragment instead of activity. For this you can have a custom LifecycleAdapter:
interface LifecycleAdapter {
fun onBackPressed() : Boolean = false
// add other methods like onActivityResult or similar
// if needed that is to be delegated to the fragment
}
Now in the BaseActivity you would have 2 functions one for addingFragment and a register function for MutableList<WeakReference<LifecycleAdapter>>
open class BaseActivity : AppCompatActivity() { // which ever type
protected open val lifecycleReferrals : MutableList<WeakReference<LifecycleAdapter>> = mutableListOf()
fun addFragment(fragment: BaseFragment,
#IdRes containerId: Int = R.id.fragment_container,
replace: Boolean = true,
addToBackstack: Boolean = false) {
supportFragmentManager?.beginTransaction()?.run {
if (addToBackstack){
addToBackStack(fragment.javaClass.simpleName)
}
if (replace) {
replace(containerId, fragment) // add tag when needed
} else {
add(containerId, fragment)
}
registerLifecycleReferrals(fragment)
commit()
}
}
fun registerLifecycleReferrals(adapter: LifecycleAdapter){
lifecycleReferrals.add(WeakReference(adapter))
}
override fun onBackPressed() {
if (lifecycleReferrals.none { it.get()?.onBackPressed(0) == true }) {
super.onBackPressed()
}
}
}
when ever you need a any class accessing the controller methods like onBackPressed() you can implement the interface in the required class and call registerLifecycleReferrals(obj) from the activity.
Now your base fragment class would be:
open class BaseFragment : Fragment(), LifecycleAdapter{
// have parent level constructs and implementation
// that would serve you well across the entire project
}
and your current fragment can be:
class SongPlayingFragment : BaseFragment() {
// do all fragment inits and override methods
override fun onBackPressed(): Boolean {
if (Statified.currentSongHelper?.isPlaying == true) {
// handle the call and switch to MainScreenActivity
context?.apply {
startActivity<MainScreenActivity>() // anko extension
return true
}
}
return super.onBackPressed()
}
}
Note: The adapters are weak referenced in the BaseActivity class because if the Fragment undergoes a destruction process it can be easily freed up by the GC and list wouldn't withhold the reference to it.

Categories

Resources