Android/Kotlin: Intent always NULL - android

I have searched through multiple posts on here which seem to all have the same problem but with different causes. I am getting NULL results from my bundle when calling them from the second activity. I will post more of my code if required;
Here is where i package my bundle on initial activity:
val extras = Bundle()
extras.putString("EXTRA_DIFFICULTY", dif_spinner.getSelectedItem().toString())
extras.putString("EXTRA_CAT", cat_spinner.getSelectedItem().toString())
intent.putExtras(extras)
And when I am in my second activity:
val bundle :Bundle ?=intent.extras
val difficultystring = bundle?.getString("EXTRA_DIFFICULTY")
val catstring = bundle?.getString("EXTRA_CAT")
txtV.text = "Your difficulty level is " + difficultystring + " and your cat is " + catstring
In both cases it return null. The spinners initialise on create so there should always be a value to call, can anyone point me in the right direction please?
FULL CODE (less functions - not causing any issues)
Activity 1
class MainActivity : AppCompatActivity() {
lateinit var btnSTART: Button
lateinit var switchSNOW: Switch
lateinit var imageviewSNOW: ImageView
lateinit var requested_difficulty: String
lateinit var dif_spinner: Spinner
lateinit var cat_spinner: Spinner
var difficulty_array = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
dif_spinner = findViewById(R.id.difficulty_spinner)
cat_spinner = findViewById(R.id.cat_spinner)
switchSNOW = findViewById(R.id.snow_switch) as Switch
imageviewSNOW = findViewById(R.id.imageViewSnow) as ImageView
imageviewSNOW.setVisibility(View.INVISIBLE);
switchSNOW.setOnCheckedChangeListener { _, isChecked ->
if(isChecked){
imageviewSNOW.setVisibility(View.VISIBLE);
} else {
imageviewSNOW.setVisibility(View.INVISIBLE);
}
}
btnSTART = findViewById(R.id.buttonSTART) as Button
btnSTART.setOnClickListener{
val intent = Intent(this, Quiz::class.java)
startActivity(intent)
}
// Create an ArrayAdapter using the string array and a default spinner layout
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter.createFromResource(
this,
R.array.difficulty_array,
android.R.layout.simple_spinner_item
).also { adapter ->
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// Apply the adapter to the spinner
dif_spinner.adapter = adapter
}
ArrayAdapter.createFromResource(
this,
R.array.cat_array,
android.R.layout.simple_spinner_item
).also { adapter ->
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// Apply the adapter to the spinner
cat_spinner.adapter = adapter
}
val extras = Bundle()
extras.putString("EXTRA_DIFFICULTY", dif_spinner.getSelectedItem().toString())
extras.putString("EXTRA_CAT", cat_spinner.getSelectedItem().toString())
intent.putExtras(extras)
}
}
Activity 2
class Quiz : AppCompatActivity() {
lateinit var txtV: TextView
lateinit var btn1: Button
lateinit var btn2: Button
lateinit var btn3: Button
lateinit var btn4: Button
lateinit var viewQ: TextView
var ans: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_quiz)
btn1 = findViewById(R.id.button1) as Button
btn2 = findViewById(R.id.button2) as Button
btn3 = findViewById(R.id.button3) as Button
btn4 = findViewById(R.id.button4) as Button
viewQ = findViewById(R.id.textview_question)
txtV = findViewById(R.id.textView_info) as TextView
ans = GetQuestion(1, rand(1, 6))
btn1.setOnClickListener{
val theirans: String = btn1.getText().toString() //this will get a string
val TheirAnswer = theirans.toInt() //this will get a no from the string
if(TheirAnswer==ans) {
btn1.setBackgroundResource(R.color.lime_green);
} else {
btn1.setBackgroundResource(R.color.red);
}
next()
};
btn2.setOnClickListener {
val theirans: String = btn2.getText().toString() //this will get a string
val TheirAnswer = theirans.toInt() //this will get a no from the string
if(TheirAnswer==ans) {
btn2.setBackgroundResource(R.color.lime_green);
} else {
btn2.setBackgroundResource(R.color.red);
}
next()
};
btn3.setOnClickListener{
val theirans: String = btn3.getText().toString() //this will get a string
val TheirAnswer = theirans.toInt() //this will get a no from the string
if(TheirAnswer==ans) {
btn3.setBackgroundResource(R.color.lime_green);
} else {
btn3.setBackgroundResource(R.color.red);
}
next()
};
btn4.setOnClickListener{
val theirans: String = btn4.getText().toString() //this will get a string
val TheirAnswer = theirans.toInt() //this will get a no from the string
if(TheirAnswer==ans) {
btn4.setBackgroundResource(R.color.lime_green);
} else {
btn4.setBackgroundResource(R.color.red);
}
next()
};
val bundle :Bundle ?=intent.extras
val difficultystring = bundle?.getString("EXTRA_DIFFICULTY")
val catstring = bundle?.getString("EXTRA_CAT")
txtV.text = "Your difficulty level is " + difficultystring + " and your category is " + catstring
}

Use below answer
val intent = intent
val difficultystring = intent.getStringExtra("EXTRA_DIFFICULTY")
val catstring = intent.getStringExtra("EXTRA_CAT")
txtV.text = "Your difficulty level is " + difficultystring + " and your cat is " + catstring

Question raised by #cutiko provided the answer to my problem. For some reason I added the bundle to the end of my code rather than with my start activity intent.
From activity 1 my code went from:
btnSTART.setOnClickListener{
val intent = Intent(this, Quiz::class.java)
startActivity(intent)
}
&
val extras = Bundle()
extras.putString("EXTRA_DIFFICULTY", dif_spinner.getSelectedItem().toString())
extras.putString("EXTRA_CAT", cat_spinner.getSelectedItem().toString())
intent.putExtras(extras)
to
btnSTART.setOnClickListener{
val intent = Intent(this, Quiz::class.java)
val extras = Bundle()
extras.putString("EXTRA_DIFFICULTY", dif_spinner.getSelectedItem().toString())
extras.putString("EXTRA_CAT", cat_spinner.getSelectedItem().toString())
intent.putExtras(extras)
startActivity(intent)
}

Related

How to update recyclerview element and retrieve sum all updated elements

Updating value of recyclerview but unable to update corresponding data in model class
Model classes
#Parcelize
class GetStockListData : ArrayList<GetStockListDataItem>(), Parcelable
#Parcelize
data class GetStockListDataItem(
var Qty:#RawValue Double,
var selectedQty: Double
): Parcelable
able to change recyclerview element using alertbox as follows
private fun showAlertDialog(stockListData: GetStockListData, position: Int) {
val layoutInflater = LayoutInflater.from(context)
val customView =
layoutInflater.inflate(R.layout.change_qty_dialog, null)
val myBox: android.app.AlertDialog.Builder = android.app.AlertDialog.Builder(context)
myBox.setView(customView)
val dialog = myBox.create()
dialog.show()
val etQuantity = customView.findViewById<AppCompatEditText>(R.id.et_quantity)
if (stockListData[position].Qty < args.getListDetailsByRNumberModelItem.ReqQty) {
val df = DecimalFormat("#.##")
df.roundingMode = RoundingMode.CEILING
etQuantity.setText(df.format(stockListData[position].Qty).toString())
} else
etQuantity.setText(args.getListDetailsByRNumberModelItem.ReqQty.toString())
etQuantity.setSelection(etQuantity.text.toString().length)
etQuantity.requestFocus()
requireContext().showKeyboard()
customView.findViewById<Button>(R.id.btnDone).setOnClickListener {
if(!etQuantity.text.isNullOrEmpty()) {
val qtyStr = etQuantity.text.toString().trim()
var qtyDouble = qtyStr.toDouble()
stockListData[position].selectedQty = qtyDouble
adapter.notifyDataSetChanged()
dialog.dismiss()
}
}
}
for (i in 0 until stockListData.size){
sum += stockListData[i].selectedQty
}
here if user edit Recyclerview list item multiple times, each value added to list. Finally if i try to retrieve sum of all recyclerview elements getting wrong value because in model class values are added when i try to replace element.
Instead of passing whole list as parameter to showAlertDialog() method, you could just pass single item which has to be updated. And one more thing, you should not call adapter.notifyDataSetChanged() for single item updation, rather call adapter.notifyItemChanged(position). Look at below code, I am getting correct sum :
private fun showRecipeMeasureDialog(recipeItem: RecipeItem?,position: Int){
val dialogView = LayoutInflater.from(context).inflate(R.layout.add_recipe_measure_dialog, null)
val dialog = AlertDialog.Builder(context, R.style.RoundedCornersDialog).setView(dialogView).show()
dialog.setCancelable(false)
val displayRectangle = Rect()
val window = activity?.window
window?.decorView?.getWindowVisibleDisplayFrame(displayRectangle)
dialog.window?.setLayout(
(displayRectangle.width() * 0.5f).toInt(),
dialog.window!!.attributes.height
)
context?.resources?.let {
dialogView.findViewById<TextView>(R.id.recipe_measure_title).text = java.lang.String.format(it.getString(R.string.addRecipeMeasure), unitsArray[currentMeasurementUnits - 1])
}
val doneBtn = dialogView.findViewById<ImageButton>(R.id.recipe_measure_done_btn)
val closeBtn = dialogView.findViewById<ImageButton>(R.id.close_btn_add_recipe)
val conversionEditText = dialogView.findViewById<ClearFocusEditText>(R.id.recipe_conversion_tie)
doneBtn.isEnabled = false
if (recipeItem != null ){
conversionEditText.setText("${recipeItem.conversionRatio}")
}
closeBtn.setOnClickListener {
context?.hideKeyboard(it)
dialog.dismiss() }
doneBtn.setOnClickListener {
context?.hideKeyboard(it)
val conversionRatio = conversionEditText.text.toString().toFloat()
if (recipeItem != null){
recipeItem.conversionRatio = conversionRatio
recipeItemList[position] = recipeItem
recipeAdapter.notifyItemChanged(position)
}else{
recipeItemList.add(0,RecipeItem(0,0,conversionRatio,0)) // Use your data class in place of RecipeItem
recipeAdapter.notifyItemInserted(0) // new Item is added to index zero, so adapter has to be updated at index zero
}
// calculating sum
val sum = recipeItemList.map { it.conversionRatio }.sum()
Log.d("tisha==>>","Conversion ratio sum = $sum")
dialog.cancel()
}
}

How to run code when resuming an activity after a swipe back gesture from another activity in WearOS?

I have three activities
MainActivity
StartActivity
EndActivity
When the app loads it opens MainActivty, there are two buttons called Start and End. Clicking on Start takes to StartActivity and End takes to EndActivity. From both these activities, I can swipe back to MainActivity. I want to execute code in MainActivity when the others are swiped away and the MainActivity is revealed.
So far I have tried OnResume and OnRestart events with no success. Please suggest something that I can try?
Please note: I am not interested about the Activity from which I come back from. Only need to execute code when the MainActivity is resumed.
MainActivity
class MainActivity : WearableActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnStart = findViewById(R.id.btnStartActivity) as Button
btnStart.setOnClickListener{
//Toast.makeText(this#MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
val intent = Intent(this#MainActivity, StartActivity::class.java)
startActivity(intent)
}
val btnEnd = findViewById(R.id.btnEndActivity) as Button
btnEnd.setOnClickListener{
//Toast.makeText(this#MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
val intent = Intent(this#MainActivity, EndActivity::class.java)
startActivity(intent)
}
// Enables Always-on
setAmbientEnabled()
}
fun onRestart(savedInstanceState: Bundle?) {
super.onRestart();
val btnStart = findViewById(R.id.btnStartActivity) as Button
btnStart.text = MyApplication.Companion.g_hour_start.toString() +":" + MyApplication.Companion.g_min_start.toString()
}
}
StartActivity
class StartActivity : WearableActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_start)
val pickerStart = findViewById(R.id.timePickerStart) as TimePicker
pickerStart.setIs24HourView(true)
pickerStart.setHour(MyApplication.Companion.g_hour_start)
pickerStart.setMinute(MyApplication.Companion.g_min_start)
pickerStart.setOnTimeChangedListener(TimePicker.OnTimeChangedListener { view, hourOfDay, minute ->
MyApplication.Companion.g_hour_start = hourOfDay
MyApplication.Companion.g_min_start =minute
})
// Enables Always-on
setAmbientEnabled()
}
override fun onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed()
finish()
}
}
EndActivity is similar to StartActivity
Link to Code: Layout and code
If you launch StartActivity and EndActivity using
startActivityForResult (Intent intent, int requestCode)
you will get a callback once they finish (i.e. dismissed by the user and returns to MainActivity)
onActivityResult (int requestCode, int resultCode, Intent data)
Since you don't care about the activity you come back from you can ignore most of the arguments and just execute the code you need to run.
More details can be found in the official documentation.
I got the code to work. But not sure if it is the right way.
Screen record of the App - TimeDifference Screen Record
MainActivity
class MainActivity : WearableActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
//Log.d(TAG,"onCreate: called")
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
MyApplication.Companion.g_hour_start =0
MyApplication.Companion.g_min_start = 0
MyApplication.Companion.g_hour_end =0
MyApplication.Companion.g_min_end = 0
val btnStart = findViewById(R.id.btnStartActivity) as Button
btnStart.setOnClickListener{
//Toast.makeText(this#MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
val intent = Intent(this#MainActivity, StartActivity::class.java)
startActivity(intent)
}
val btnEnd = findViewById(R.id.btnEndActivity) as Button
btnEnd.setOnClickListener{
//Toast.makeText(this#MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
val intent = Intent(this#MainActivity, EndActivity::class.java)
startActivity(intent)
}
// Enables Always-on
setAmbientEnabled()
}
override fun onResume() {
//Log.d(TAG,"onResume: called")
super.onResume();
val btnStart = findViewById(R.id.btnStartActivity) as Button
val btnEnd = findViewById(R.id.btnEndActivity) as Button
val txtCalc = findViewById(R.id.txtResult) as TextView
val StartHour = MyApplication.Companion.g_hour_start
val StartMin = MyApplication.Companion.g_min_start
val EndHour = MyApplication.Companion.g_hour_end
val EndMin = MyApplication.Companion.g_min_end
val DifferenceMinutes : Int
val DiffHour : Int
val DiffMin : Int
if (StartHour + StartMin != 0 ) {
btnStart.text =
StartHour.toString().padStart(2,'0') + ":" + StartMin.toString().padStart(2,'0')
}
if (EndHour + EndMin != 0 ) {
btnEnd.text =
EndHour.toString().padStart(2,'0') + ":" + EndMin.toString().padStart(2,'0')
}
if (StartHour + StartMin != 0 &&
EndHour + EndMin != 0 ){
//txtCalc.textSize = 20f
var TotalStartMinutes = StartHour * 60 + StartMin
var TotalEndMinutes = EndHour * 60 + EndMin
if(TotalEndMinutes> TotalStartMinutes) {
DifferenceMinutes = TotalEndMinutes - TotalStartMinutes
}else{
DifferenceMinutes = TotalStartMinutes - TotalEndMinutes
}
DiffHour = DifferenceMinutes / 60
DiffMin = DifferenceMinutes % 60
if (DiffHour == 0 && DiffMin == 0){
txtCalc.text = "No Difference!!"
}else if (DiffHour == 0){
txtCalc.text = "$DiffMin m"
} else if(DiffMin == 0){
txtCalc.text = "$DiffHour h"
} else{
txtCalc.text = "$DiffHour h and $DiffMin m"
}
}
}
}
StartActivity
class StartActivity : WearableActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_start)
val pickerStart = findViewById(R.id.timePickerStart) as TimePicker
pickerStart.setIs24HourView(true)
pickerStart.setHour(MyApplication.Companion.g_hour_start)
pickerStart.setMinute(MyApplication.Companion.g_min_start)
pickerStart.setOnTimeChangedListener(TimePicker.OnTimeChangedListener { view, hourOfDay, minute ->
MyApplication.Companion.g_hour_start = hourOfDay
MyApplication.Companion.g_min_start =minute
})
// Enables Always-on
setAmbientEnabled()
}
}
For Global Variables
class MyApplication : Application() {
companion object {
var g_hour_start = 0
var g_min_start = 0
var g_hour_end = 0
var g_min_end = 0
}
override fun onCreate() {
super.onCreate()
// initialization code here
}
}
EndActivity is similar to StartActivity
Code and Layout for the WearOS app

How to click a button multiple times and change modes in an android app

I am new to Android Development. I need to build a temperature converter app which would convert Celcius to Farenheit and Farenheit to Celcius. I have used an editText for user input. There are two buttons. One button is to convert the input and the other one is the mode button which would toggle between the two modes of conversion. When I launch the app the mode is in celcius to farenheit by default. By clicking on mode button I can change the mode to farenheit to celcius scale. The problem is that when I again click on the mode button it does not return to the celcius to farenheit conversion mode. I don't know how to do it. Can someone help me in this regard?
I have set the function getset() for the convert button and function mode() for the mode button.
fun getSet(view: View)
{
val convert = findViewById<Button>(R.id.button)
convert.setOnClickListener {
if(editText.length()==0)
{
editText.setError("Enter a Value")
}
else
{
val editxt = findViewById<EditText>(R.id.editText)
val msg = editxt.text.toString()
val txtview = findViewById<TextView>(R.id.textView2).apply {
val cel = msg.toDouble()
val far = (cel*1.8)+32
text = "Result: " + far.toString()
}
}
}
}
fun mode(view: View)
{
val convert = findViewById<Button>(R.id.button)
val heading = findViewById<TextView>(R.id.textView).apply {
val caption = "Farenheit to Celcius"
text = caption
}
convert.setOnClickListener {
if(editText.length()==0)
{
editText.setError("Enter a Value")
}
else
{
val editxt = findViewById<EditText>(R.id.editText)
val msg = editxt.text.toString()
val txtview = findViewById<TextView>(R.id.textView2).apply {
val far = msg.toDouble()
val cel = (far-32)*0.5555555556
text = "Result: " + cel.toString()
}
}
}
}
You need to store the "mode" in a global variable.
create a global variable
var isModeCelsius: Boolean = true
Now inside your onCreate() method in your activity, under the setContentView(R.layout.your_layout_name) line enter the below code.
//Initialize edittext and button
val convert = findViewById<Button>(R.id.button)
val heading = findViewById<TextView>(R.id.textView)
val modeButton = findViewById<Button>(R.id.id_of_button)
val editxt = findViewById<EditText>(R.id.editText)
val showResultTextView = findViewById<TextView>(R.id.textView2)
//You only need to assign the click listener once
modeButton.setOnClickListener {
if (isModeCelsius) {
isModeCelsius = false
} else {
isModeCelsius = true
}
//Or you can simply use
//isModeCelsius=!isModeCelsius
}
convert.setOnClickListener {
val msg = editxt.text.toString()
if(isModeCelsius){
val far = msg.toDouble()
val cel = (far-32)*0.5555555556
showResultTextView.text = "Result: " + cel.toString()
}else{
val cel = msg.toDouble()
val far = (cel*1.8)+32
showResultTextView.text = "Result: " + far.toString()
}
}

RecyclerView not updating after delete/update of a note

PROBLEM - After a note is deleted from second activity, on returning back to first activity(this activity displays notes), changed made to note i.e deleted or edited does not shows change UNLESS the app is restarted and onCreate() method is recalled. If I change my device orientation, then the data gets updated.
How my code works - Basically, my app consists of two activities. First(Main) Activity is where recyclerview resides, this activity handles display of notes by fetching data from SQLite database and displays in form of cardViews. Those cardViews are click able, each cardView when clicked takes to Second(Reference) activity and a corresponding data is loaded into that activity. Now a user has a choice to either make changes to current note or to delete it. If a user clicks on delete button, data of the corresponding note is deleted from SQLite database. On deletion, app automatically goes back to Main activity. HOWEVER, the deleted note does not appears to be deleted in the main activity not until the app is restarted and onCreate method is called.
I have gone through multiple almost similar questions on the site but they do not appear to fit my needs. I am a beginner in Android development so if you could please explain it a little would greatly help me. Thank you.
MAIN ACTIVITY
class MainActivity : AppCompatActivity() {
//START OF EX-INITIALIZATIONS
var dbHandler: PediaDatabase? = null
var adapter: PediaAdapter? = null
var layoutManager: RecyclerView.LayoutManager? = null
var list: ArrayList<UserNotes>? = ArrayList()
var listItems: ArrayList<UserNotes>? = ArrayList()
val PREFS_NAME: String = "MYPREFS"
var myPrefs: SharedPreferences? = null
var first_run: Boolean = true
val REQUEST_CODE: Int = 1
var deletedNoteID: Int = 0
var deletedNoteAdapterPos: Int = 0
//END OF EX-INITIALIZATIONS
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
showOneTimeMessage()
invalidateOptionsMenu()
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
window.navigationBarColor = Color.BLACK
}
//START OF IN-INITIALIZATIONS
dbHandler = PediaDatabase(this)
list = ArrayList<UserNotes>()
listItems = ArrayList()
adapter = PediaAdapter(this, listItems!!)
layoutManager = LinearLayoutManager(this)
recyclerViewID.adapter = adapter
recyclerViewID.layoutManager = layoutManager
//END OF IN-INITIALIZATIONS
//DATA POPULATION STARTS HERE
list = dbHandler!!.readAllNotes()
for(reader in list!!.iterator())
{
var note = UserNotes()
note.noteTitle = reader.noteTitle
note.noteText = reader.noteText
note.noteID = reader.noteID
note.noteDate = reader.noteDate
listItems!!.add(note)
}
adapter!!.notifyDataSetChanged()
//DATA POPULATION ENDS HERE
if(dbHandler!!.totalNotes() == 0) {
recyclerViewID.visibility = View.GONE
}
else{
recyclerViewID.visibility = View.VISIBLE
showWhenEmptyID.visibility = View.GONE
}
}//end onCreate
override fun onRestart() {
super.onRestart()
overridePendingTransition(R.anim.slide_out, R.anim.slide_in)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.top_menu, menu)
val item = menu!!.findItem(R.id.delete_note_menu)
item.setVisible(false)
return true
//return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if(item!!.itemId == R.id.add_note_menu){
var isNewNote = Intent(this, ReferenceActivity::class.java)
isNewNote.putExtra("isNewNote", true)
startActivityForResult(isNewNote, REQUEST_CODE)
}
if(item!!.itemId == R.id.delete_note_menu)
{
Toast.makeText(this,"DELETED", Toast.LENGTH_SHORT).show()
}
return super.onOptionsItemSelected(item)
}
private fun showOneTimeMessage()
{
var data: SharedPreferences = getSharedPreferences(PREFS_NAME, 0)
if(data.contains("isShown"))
{
first_run = data.getBoolean("isShown", true)
}
Log.d("FIRST_RUN", first_run.toString())
if(first_run) {
val oneTimeMsg = SweetAlertDialog(this)
oneTimeMsg.setTitleText("Hey there!")
oneTimeMsg.setContentText("Thank you for downloading! Please don`t forget to rate our app :)").show()
oneTimeMsg.setConfirmClickListener(object : SweetAlertDialog.OnSweetClickListener {
override fun onClick(sweetAlertDialog: SweetAlertDialog?) {
oneTimeMsg.dismissWithAnimation()
}
}).show()
myPrefs = getSharedPreferences(PREFS_NAME, 0)
var editor: SharedPreferences.Editor = (myPrefs as SharedPreferences).edit()
editor.putBoolean("isShown", false)
editor.commit()
}
}
REFERENCE ACTVITY
class ReferenceActivity : AppCompatActivity() {
var dbHandler: PediaDatabase? = null
var note = UserNotes()
var existingNote = UserNotes()
var noteExisted: Boolean = false
var cardID: Int = 0
var cardAdapterPos: Int? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_reference)
getSupportActionBar()!!.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar()!!.setCustomView(R.layout.custom_toolbar);
val dateTxtView = findViewById<View>(resources.getIdentifier("action_bar_title", "id", packageName)) as TextView
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
window.navigationBarColor = Color.RED
dbHandler = PediaDatabase(this)
var data = intent
var isNewNote = intent
if(isNewNote != null)
if(isNewNote.extras.getBoolean("isNewNote") != true)
{
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
if(data != null)
{
noteExisted = true
this.cardAdapterPos = data.extras.getInt("cardPosition")
cardID = data.extras.getInt("cardID")
existingNote = dbHandler!!.readNote(cardID)
refTitleID.setText(existingNote.noteTitle, TextView.BufferType.EDITABLE)
refTextID.setText(existingNote.noteText, TextView.BufferType.EDITABLE)
dateTxtView.text = existingNote.noteDate.toString()
}
}else{
dateTxtView.text = "New note"
}
}//end onCreate()
override fun onStop() {
super.onStop()
var title: String = refTitleID.text.toString().trim()
var text: String = refTextID.text.toString().trim()
if(existingNote.noteText == text && existingNote.noteTitle == title)
finish()
if(noteExisted)
{
if(TextUtils.isEmpty(title))
title = "No title"
existingNote.noteTitle = title
existingNote.noteText = text
//existingNote.noteDate =
dbHandler!!.updateNote(existingNote)
var dataToMain = this.intent
dataToMain.putExtra("cardID", cardID)
dataToMain.putExtra("cardAdapterPos", cardAdapterPos)
setResult(Activity.RESULT_OK, dataToMain)
finish()
}
else
{
if(TextUtils.isEmpty(title) && TextUtils.isEmpty(text))
{
finish()
}
else
{
if(TextUtils.isEmpty(title))
title = "No title"
note.noteTitle = title
note.noteText = text
dbHandler!!.createNote(note)
finish()
}
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.top_menu, menu)
val addItem: MenuItem = menu!!.findItem(R.id.add_note_menu)
val delItem:MenuItem = menu.findItem(R.id.delete_note_menu)
addItem.setVisible(false)
delItem.setVisible(false)
if(noteExisted)
delItem.setVisible(true)
return true
//return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if(item!!.itemId == R.id.delete_note_menu)
{
val dialogMsg = SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
dialogMsg.setTitleText("Are you sure?")
dialogMsg.setContentText("You won`t be able to recover this note!")
dialogMsg.setConfirmText("Yes,delete it!")
dialogMsg.setConfirmClickListener(object: SweetAlertDialog.OnSweetClickListener {
override fun onClick(sweetAlertDialog: SweetAlertDialog?) {
dialogMsg.dismissWithAnimation()
dbHandler!!.deleteNote(cardID)
var successMsg = SweetAlertDialog(sweetAlertDialog!!.context, SweetAlertDialog.SUCCESS_TYPE)
successMsg.setTitleText("Note deleted!")
successMsg.setContentText("So long,note").show()
successMsg.setCancelable(false)
//TODO Disable 'OK' button on successMsg dialogbox
Handler().postDelayed({
successMsg.dismissWithAnimation()
finish()
}, 1200)
}
}).show()
}
return super.onOptionsItemSelected(item)
}
}
you need to update your list items inside your adapter;
not sure how it works on kotlin, but I use something like this:
after a note update call adapter.updateItens(itens);
MyAdapter extendes RecyclerView.Adapter<MyViewHolder>
private List<MyItem> elements;
MyAdapter(){
this.elements = new ArrayList<>();
}
void updateElements(List<MyItem> itens){
Collections.sort(itens, new SortByName());
this.elements.clear();
this.elements.addAll(itens);
notifyDataSetChanged();
}
you can do even better if instead of notifyDataSetChanged(), you implement a DiffUtil;
After making changes to the data in the database, the RecyclerViewAdapter needs to be given a new list of data. This should be done in onRestart(), so that once you navigate back to MainActivity from SecondActivity, the RecyclerView is populated with the updated data. Try copying the code that populates the RecyclerView and put it into onRestart(). The reason why it was only updating when onCreate() was called is because that's the only place where you do anything to the view.

How to pick every time new or unique random item from a array list in android?

I need to pick a new item from a list that hasn't been picked already until there are no more.
Here is my code:
private var quizQuestionList: ArrayList<Quiz>
private var pickedItems: ArrayList<Int>
private var random: Random = Random()
private fun pickItem(): Quiz {
var index = random?.nextInt(quizQuestionList!!.size)
if (pickedItems.contains(index)) {
index = random?.nextInt(quizQuestionList!!.size)
pickedItems.add(index)
} else {
pickedItems.add(index)
}
val item = quizQuestionList!!.get(index!!)
return item
}
Please suggest any solution that gives me a new item every time. I used an int list for all previously picked items and check every time when picked new item but I didn't get success.
It isn't obvious what you are looking for, but it looks like you want to show different Quiz question from ArrayList. In condition of, when that question is shown, no more same question will be shown. Here is how you should do, I will give you just the logic you could try it yourself:
import java.util.Random
fun main(args: Array<String>) {
val random = Random()
var randomInt: Int
var pickedInt: MutableSet<Int> = mutableSetOf()
fun rand(from: Int, to: Int): Int{
do{
randomInt = random.nextInt(to - from) + from
}while(pickedInt.contains(randomInt))
pickedInt.add(randomInt)
return randomInt
}
while(pickedInt.size < 9){
var differentNumber = rand(1,11)
println(differentNumber)
}
}
This will print nine different Number. The way I choosing MutableSet is because it will only have unique values, no duplicated value. Hope it helps!
here is code for same::
val arrayList = ArrayList<String>()
arrayList.add("a")
arrayList.add("b")
arrayList.add("c")
arrayList.add("d")
arrayList.add("e")
arrayList.add("f")
arrayList.add("g")
arrayList.add("h")
arrayList.add("i")
arrayList.add("j")
arrayList.add("k")
random = Random()
Low = 0
High = arrayList.size
val generateRandom = findViewById<View>(R.id.generateRandom) as Button
generateRandom.setOnClickListener {
val Result = random.nextInt(High - Low) + Low
Log.v("check", arrayList[Result])
}
Please let me know if need more!!
Try this way
class MainActivity : AppCompatActivity() {
private var arrayList = ArrayList<String>()
private var lastItem = -1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
for (i in 0..9) {
arrayList.add(i.toString())
}
btnData.setOnClickListener {
Log.e("RANDOM_NUMBER", "" + getRandomItemFromList())
}
}
private fun getRandomItemFromList(): Int {
val randomValue = Random().nextInt(arrayList.size)
return if (randomValue != lastItem) {
lastItem = randomValue
randomValue
} else {
getRandomItemFromList()
}
}
}
I made this extension for the ArrayList class in Kotlin you can use it multiple times in only one line.
fun <T> ArrayList<T>.generateRandomItems(numberOfItems: Int): ArrayList<T> {
val range = if(numberOfItems > this.size){this.size}else{numberOfItems}
val randomItems = ArrayList<T>()
for (i in 0..range) {
var randomItem: T
do {
randomItem = this.random()
} while (randomItems.contains(randomItem))
randomItems.add(randomItem)
}
return randomItems
}
Usage:
val randomUsersList = usersList.generateRandomItems(20)
Note: the usersList is the list that has items to generate random items from.

Categories

Resources