What did i do wrong in my understand of save data, need to make an easy app for adding to numbers together and save the result for adding more to it - sharedpreferences

package com.example.application.myapplicationenter code here
import android.content.Contextenter code here
import android.os.Bundleenter code here
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var c = Antal.text.toString().toInt()
val MY_PREFS_NAME = "MyPrefsFile";
val editor = getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE).edit()
editor.putString("name", "Elena")
editor.putInt("idName", 12)
editor.apply()
val prefs = getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE)
val name = prefs.getString("name", "No name defined") value.
val idName = prefs.getInt("idName", 0)
Navn.text = name.toString()`enter code here`
Alder.text = idName.toString()
button.setOnClickListener {
val pref = applicationContext.getSharedPreferences("MyPref", Context.MODE_PRIVATE)
var a = Antal.text.toString().toInt();`enter code here`
Alder.text = pref.edit(a + c)`enter code here`
}
}
}

Related

How to send data another page and list with kotlin?

I just started learning Kotlin. I am making an application that saves bank (IBAN) information. I save the information locally using sharedpreferences.
I save the information to the list and save it as sharedpreferences.
Information is recorded on page 2 and I want to list this recorded information on page 1.
I was doing this simply in Flutter, but I couldn't understand how to do it in Kotlin.
package com.example.ibansfer
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.ibansfer.databinding.ActivityAddIbanBinding
import com.example.ibansfer.models.IbanModel
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
class AddIbanActivity : AppCompatActivity() {
private lateinit var binding: ActivityAddIbanBinding
private var ibanList: ArrayList<IbanModel> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAddIbanBinding.inflate(layoutInflater)
setContentView(binding.root)
setTitle("IBAN bilgisi ekle")
getSupportActionBar()?.setDisplayHomeAsUpEnabled(true);
val sharedPreferences = this.getSharedPreferences("ibans", MODE_PRIVATE)
val editor = sharedPreferences.edit()
fun saveData() {
val gson = Gson()
val json = gson.toJson(ibanList)
editor.putString("ibans", json)
editor.apply()
}
binding.ibanSaveBttn.setOnClickListener {
val ibanOwner = binding.ibanOwner.text.toString()
val bankName = binding.bankName.text.toString()
val ibanAdress = binding.ibanAdress.text.toString()
if (ibanOwner.isEmpty() || bankName.isEmpty() || ibanAdress.isEmpty()) {
Toast.makeText(this, "Lütfen tüm alanları doldurunuz.", Toast.LENGTH_LONG).show()
} else {
ibanList.add(IbanModel(ibanOwner, bankName, ibanAdress))
saveData()
Toast.makeText(this, "IBAN bilgileri başarıyla eklendi.", Toast.LENGTH_LONG).show()
finish()
}
}
}
}
If you save the data in SharedPrefferences, you can always retrieve it back in the other screen.
val sharedPref = activity?.getPreferences("ibans", Context.MODE_PRIVATE) ?: return
val myString = sharedPref.getString("ibans", defaultValue)
You can even set up a SharedPrefferences listener that will get notified whenever new data is added to it and act accordingly.
val sharedPreferencesListener =
SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
// code to execute on changes here
}
activity?.getPreferences("ibans", Context.MODE_PRIVATE)
?.registerOnSharedPreferenceChangeListener(sharedPreferencesListener )
Also don't forget to unregister using unregisterOnSharedPreferenceChangeListener
Or alternatively, use Intents as the comment suggests to pass data between Activities/Fragments.

How to send a variable to an Adapter to send it through an Intent to another activity?

I have an adapter for my RecyclerView where I program that when I click on the element (of my RecyclerView) it executes an Intent with a putExtra to take me to another activity, the variable that contains my putExtra comes from the element that I clicked, but now I need to add a More variable that comes from the activity. The issue is that I don't know how to send it from the adapter.
this is my adapter.
package com.example.atipicoapp
import android.app.Activity
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.view.menu.ActionMenuItemView
import androidx.core.content.ContextCompat.startActivity
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.list_item.view.*
class MyAdapter(private val platoList : ArrayList<Plato>
) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyAdapter.MyViewHolder {
val itemView =
LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false)
itemView.platoTouch.setOnClickListener(View.OnClickListener { v: View ->
})
return MyViewHolder(itemView)
}
override fun onBindViewHolder(holder: MyAdapter.MyViewHolder, position: Int) {
val plato: Plato = platoList[position]
holder.platoName.text = plato.platoName
holder.platoDescription.text = plato.platoDescription
holder.platoPrecio.text = plato.platoPrecio.toString()
holder.platoCantidad.text = plato.platoCantidad.toString()
when(holder){
is MyViewHolder -> {
holder.bind(platoList[position])
}
}
}
override fun getItemCount(): Int {
return platoList.size
}
public class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val platoName: TextView = itemView.findViewById(R.id.platoNombre)
val platoDescription: TextView = itemView.findViewById(R.id.platoDescripcion)
val platoPrecio: TextView = itemView.findViewById(R.id.platoPrecio)
val platoTouch: LinearLayout = itemView.findViewById(R.id.platoTouch)
val platoCantidad: TextView = itemView.findViewById(R.id.platoCant)
private val mActivity = itemView.context as Activity
private val intent = Intent(mActivity,SlotActivity::class.java)
fun bind(plato: Plato){
platoTouch.setOnClickListener{
intent.putExtra("id", platoName.text.toString())
mActivity.startActivity(intent)
}
}
}
}
And this is my Activity which contains my RecyclerView and the variable I want to send.
package com.example.atipicoapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.firestore.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_menu_atipico.*
class MenuAtipicoActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private lateinit var platoArrayList: ArrayList<Plato>
private lateinit var myAdapter: MyAdapter
private lateinit var db: FirebaseFirestore
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_menu_atipico)
recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.setHasFixedSize(true)
platoArrayList = arrayListOf()
myAdapter = MyAdapter(platoArrayList)
recyclerView.adapter = myAdapter
pedidoId = intent.extras?.getString("pedidoId") //This is the variable I need to send
EventChangeListener()
Setup()
}
private fun EventChangeListener() {
db = FirebaseFirestore.getInstance()
db.collection("Platos").addSnapshotListener(object : EventListener<QuerySnapshot> {
override fun onEvent(
value: QuerySnapshot?,
error: FirebaseFirestoreException?
) {
if (error != null) {
Log.e("Firestore Error", error.message.toString())
return
}
for (dc: DocumentChange in value?.documentChanges!!) {
if (dc.type == DocumentChange.Type.ADDED) {
platoArrayList.add(dc.document.toObject(Plato::class.java))
}
}
myAdapter.notifyDataSetChanged()
}
})
}
private fun Setup() {
botonAceptar.setOnClickListener {
val SlotIntent = Intent(this, SlotActivity::class.java).apply {
}
startActivity(SlotIntent)
}
}
}
How can I send the variable if the Intent is executed from the Adapter?
Or... If it is not recommended to send intent from my Adapter, how can I send them from the activity?
Knowing that I have to carry a variable that is in the item of the RecyclerView.
Thanks for your help <3
Firstly, create a MyAdapter constructor where you pass arrayList as well as pedidoId like, your MyAdapter should be something like below:
MyAdapter.class
class MyAdapter(private val platoList : ArrayList<Plato>, val pedidoId:String
) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
........
.....
....
//in your bind(..) method
fun bind(plato: Plato){
platoTouch.setOnClickListener{
intent.putExtra("id", platoName.text.toString())
intent.putExtra("pedidoId", pedidoId)
mActivity.startActivity(intent)
}
}
}
And, in your MenuAtipicoActivity you need to do something like:
MenuAtipicoActivity
class MenuAtipicoActivity : AppCompatActivity() {
...............
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_menu_atipico)
recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.setHasFixedSize(true)
platoArrayList = arrayListOf()
pedidoId = intent.extras?.getString("pedidoId") //This is the variable I need to send
myAdapter = MyAdapter(platoArrayList,pedidoId)
recyclerView.adapter = myAdapter
EventChangeListener()
Setup()
}
..........
........
}

Add button in recyclerview to edit or delete data from realtime database

i'm a beginner in programming so forgive me if my code is messy. I need some help to complete my program.
I'm using recyclerview to retrieve some data from realtime database and i want to add edit and delete button in the recyclerview to edit and delete some data.
I already create the button in the xml file, i just don't know how to code the button. I already tried some tutorial from youtube and refer to some code in some others post on stack overflow but most of the time the code will either give me an error or the button will not do anything. I've included my code and database structure below:
DoctorViewAdapter.kt
package com.example.patientmonitor
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import java.util.ArrayList
import kotlin.concurrent.fixedRateTimer
class DoctorViewAdapter(private val patientList : ArrayList<doctorViewPatient>) : RecyclerView.Adapter<DoctorViewAdapter.DoctorViewHolder>() {
//WebView
private lateinit var pulseGraph: WebView
private lateinit var temperatureGraph: WebView
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DoctorViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.patient_item,parent,false)
return DoctorViewHolder(itemView)
pulseGraph.webViewClient = WebViewClient()
temperatureGraph.webViewClient = WebViewClient()
pulseGraph.settings.javaScriptEnabled = true
temperatureGraph.settings.javaScriptEnabled = true
pulseGraph.settings.builtInZoomControls = true
temperatureGraph.settings.builtInZoomControls = true
}
override fun onBindViewHolder(holder: DoctorViewHolder, position: Int) {
val currentitem = patientList[position]
holder.userID.text = currentitem.userID
holder.fullName.text = currentitem.fullName
holder.userEmail.text = currentitem.email
holder.phoneNumber.text = currentitem.phoneNumber
var pulseValue = "null"
var temperatureValue = "null"
//get pulse value from thingspeak and set to text view
val pulsequeue = Volley.newRequestQueue(holder.pulseValue.context)
val temperaturequeue = Volley.newRequestQueue(holder.temperatureValue.context)
val pulseRequest = StringRequest(Request.Method.GET, currentitem.pulseValue as String?,
Response.Listener<String> { response ->
pulseValue = response
holder.pulseValue.text = pulseValue
}, Response.ErrorListener {
// didn't work
})
//get temperature value from thingspeak and set to text view
val tempRequest = StringRequest(Request.Method.GET, currentitem.temperatureValue as String?,
Response.Listener<String> { response ->
temperatureValue = response
holder.temperatureValue.text = temperatureValue
}, Response.ErrorListener {
// didn't work
})
//get thingspeak data every 1 second
fixedRateTimer("timer", false, 0L, 1000) {
pulsequeue.add(pulseRequest)
temperaturequeue.add(tempRequest)
}
}
override fun getItemCount(): Int {
return patientList.size
}
class DoctorViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
val userID : TextView = itemView.findViewById(R.id.tvUserID)
val fullName : TextView = itemView.findViewById(R.id.tvFullName)
val userEmail : TextView = itemView.findViewById(R.id.tvEmail)
val phoneNumber : TextView = itemView.findViewById(R.id.tvPhoneNumber)
val pulseValue : TextView = itemView.findViewById(R.id.tvPulseValue)
val temperatureValue : TextView = itemView.findViewById(R.id.tvTemperatureValue)
}
}
PatientlistActivity.kt
package com.example.patientmonitor
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.webkit.WebView
import androidx.appcompat.app.ActionBar
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.firebase.database.*
class PatientListActivity : AppCompatActivity() {
private lateinit var dbref : DatabaseReference
private lateinit var userRecyclerview : RecyclerView
private lateinit var userArrayList : ArrayList<doctorViewPatient>
private lateinit var viewPatientBtn : FloatingActionButton
private lateinit var doctorViewAdapter : DoctorViewAdapter
//ActionBar
private lateinit var actionBar: ActionBar
//WebView
private lateinit var pulseView: WebView
private lateinit var tempView: WebView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_patient_list)
//configure Actionbar //enable back button
actionBar = supportActionBar!!
actionBar.title = "View Patients"
actionBar.setDisplayHomeAsUpEnabled(true)
actionBar.setDisplayShowHomeEnabled(true)
userRecyclerview = findViewById(R.id.patientList)
userRecyclerview.layoutManager = LinearLayoutManager(this)
userRecyclerview.setHasFixedSize(true)
userArrayList = arrayListOf<doctorViewPatient>()
getUserData()
}
private fun getUserData() {
//get intent
val assignedDoctor = intent.getStringExtra("doctorID")
val currentUserAccess = intent.getStringExtra("currentUserAccess")
dbref = FirebaseDatabase.getInstance().getReference("Users")
dbref.orderByChild("assignedDoctor").equalTo(assignedDoctor).addListenerForSingleValueEvent(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()){
for (userSnapshot in snapshot.children){
val user = userSnapshot.getValue(doctorViewPatient::class.java)
userArrayList.add(user!!)
}
userRecyclerview.adapter = DoctorViewAdapter(userArrayList)
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
This is my data class
doctorViewPatient.kt
data class doctorViewPatient(val userID : String? =null,
val fullName : String? =null,
val email : String? =null,
val phoneNumber : String? =null,
val pulseValue : String? = null,
val temperatureValue : String? = null)
This is my Realtime Database Structure

Kotlin: Unable to access value in an IntentService class

I'm pulling JSON from a URL and i'm using Gson to convert it to a usable PIN code i need to show to the user.
package example
import android.app.IntentService
import android.content.Intent
import com.google.gson.Gson
import java.net.URL
class SendOrderIntentService : IntentService("SendOrderIntentService") {
override fun onHandleIntent(intent: Intent?) {
val orderNumber = (0..999999999999999).random()
val goodsCode = "1001004"
val orderURLPart1 = "URL"
val orderURLPart2 = "URL"
val orderURLPart3 = "URL"
val orderURL = orderURLPart1 + orderNumber + orderURLPart2 + goodsCode + orderURLPart3
val orderJson = URL(orderURL).readText()
println("Order number $orderNumber")
println(orderJson)
val pinCode = Gson().fromJson(orderJson, OrderData::class.java)
println(pinCode)
}
}
Everything works so far, pinCode has the right data.
package example
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_meal_reserved.*
import example.R
class MealReservedActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_meal_reserved)
setSupportActionBar(my_toolbar)
textViewCode.text = SendOrderIntentService().pinCode
}
}
But i can't get the textViewCode to display the pinCode, it just tells me its an
"Unresolved reference: pinCode"
I've been searching for an answer for hours so i think i'm missing something obvious and simple.
Thank you for reading.

seekbar.progress needs expected type boolean

Im new to kotlin and i am trying to follow this tutorial:https://www.youtube.com/watch?v=EOfCEhWq8sg have a problem where the line
val rand = Random().nextInt(seekBar.progress)
gives a error
Expected a value of type boolean
Full code:
package pro.bwac.randomizer
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rollButton = findViewById<Button>(R.id.RollButton)
val seekBar = findViewById<SeekBar>(R.id.seekBar)
val textView = findViewById<TextView>(R.id.preNumberView)
val ResultsTextView = findViewById<TextView>(R.id.ResultsTextView)
rollButton.setOnContextClickListener{
val rand = Random().nextInt(seekBar.progress)
}
}
The lambda needs to return a boolean value.
Change to:
rollButton.setOnContextClickListener{
val rand = Random().nextInt(seekBar.progress)
true
}