Android Studio/kotlin how to every 60 seconds run function - android-studio

I have next a fragment code:
#RequiresApi(Build.VERSION_CODES.O)
fun get_date_to_new_year(): String {
val CurrentDate = LocalDateTime.now()
val needDateToNewYear = LocalDateTime.of(2023, 1, 1, 0, 0, 0)
val DateToNewYear = Duration.between(CurrentDate, needDateToNewYear)
return "До нового года " + (DateToNewYear.toDays()).toString() + " дней\nили " +
(DateToNewYear.toHours()).toString() + " часов\nили " + (DateToNewYear.toMinutes()).toString() + " минут\nили " +
(DateToNewYear.seconds).toString() + " секунд"
}
#RequiresApi(Build.VERSION_CODES.O)
private var _text = MutableLiveData<String>().apply {
value = get_date_to_new_year()
}
#RequiresApi(Build.VERSION_CODES.O)
var text: LiveData<String> = _text
I need text variable to be updated every 60 seconds

If you move this to a ViewModel, it’s pretty easy using the liveData coroutine builder. No need for the MutableLiveData.
#RequiresApi(Build.VERSION_CODES.O)
val text: LiveData<String> = liveData {
while(true) {
emit(get_date_to_new_year())
delay(60_000)
}
}
If you don’t want to use a ViewModel, you could launch a coroutine in onViewCreated().
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
//..
viewLifecycleOwner.lifecycleScope.launch {
while(true) {
_text.value = get_date_to_new_year()
delay(60_000)
}
}
}
But if you’re not using a ViewModel, I think the LiveData is just an unnecessary extra layer. You could update your TextView or whatever directly in the coroutine.

Related

Kotlin Edit Text as Integer

I want to make an app where you have to guess two numbers that eaquals a random number. But my app crash at the start because of java.lang.NumberFormatException: For input string: ""
val intNumber1 = etNumber1.text.toString().toInt() is the line that causes the crash. But I dont know what to do.
Here is my main activity:
//Buttons und Text initialisieren
private lateinit var btnCheck: Button
private lateinit var tvRndNumber: TextView
private lateinit var etNumber1: EditText
private lateinit var etNumber2: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Buttons und Text verknüpfen
btnCheck = findViewById(R.id.checkButton)
tvRndNumber = findViewById(R.id.randomNumber)
etNumber1 = findViewById(R.id.inputNumber1)
etNumber2 = findViewById(R.id.inputNumber2)
val intNumber1 = etNumber1.text.toString().toInt()
val intNumber2 = etNumber2.text.toString().toInt()
fun getRandomNumber(): Int {
return Random.nextInt(0,100)
}
var intRdnNumber = getRandomNumber()
tvRndNumber.text = intRdnNumber.toString()
fun checkNumbers(num1: Int, num2: Int){
if (num1 + num2 == intRdnNumber) {
tvRndNumber.text = "Richtig"
}
else {
Toast.makeText(this,"Probier es nochmal", Toast.LENGTH_LONG).show()
}
}
btnCheck.setOnClickListener {
checkNumbers(intNumber1, intNumber2)
}
Try like the following
//....
val intNumber1 = etNumber1.text.toString()
val intNumber2 = etNumber2.text.toString()
//.....
btnCheck.setOnClickListener {
if(intNumber1.isNotEmpty && intNumber2.isNotEmpty{
checkNumbers(intNumber1.toInt(), intNumber2.toInt())
}else{
// input filed is empty
// show message or do nothing
}
}
val intNumber1 = if(etNumber1.text.isNotEmpty()) {
etNumber1.text.toString().toInt()
} else {
0
}
val intNumber2 = if(etNumber2.text.isNotEmpty()) {
etNumber2.text.toString().toInt()
} else {
0
}

How to change language locale in Jetpack Compose

I want to change language programmatically in Jetpack Compose. I've read quite some posts and watch videos but still can't find the way to do it. (The post and video are in Android view system.)
How to change language in kotlin (locale)
https://www.youtube.com/watch?v=xxPzi2h0Vvc
I want my app works like below image. After clicking the language, the whole app will change the language. Below code is the clickable's part. What should I do in this clickable part and MainActivity.kt?
#Composable
fun LanguageScreen(
navController: NavController,
) {
val context = LocalContext.current
val langList = arrayOf("English", "繁體中文", "简体中文", "日本語")
var items by remember {
mutableStateOf(
langList.map {
LanguageItem(
title = it,
isSelected = false
)
}
)
}
LazyColumn(
modifier = Modifier
.fillMaxSize()
) {
items(items.size) { i ->
Row(
modifier = Modifier
.fillMaxWidth()
.clickable {
items = items.mapIndexed { j, item ->
if (i == j) {
item.copy(isSelected = true)
} else item.copy(isSelected = false)
}
if (i == 0) {
setLocaleLang("", context)
} else if (i == 1) {
setLocaleLang("zh-rTW", context)
} else if (i == 2) {
setLocaleLang("zh-rCN", context)
} else {
setLocaleLang("ja", context)
}
}
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(text = items[i].title, fontSize = 20.sp)
if (items[i].isSelected) {
Icon(
imageVector = Icons.Default.Check,
contentDescription = "Selected",
tint = Color.Blue,
modifier = Modifier.size(24.dp)
)
}
}
Spacer(
modifier = Modifier
.fillMaxWidth()
.height(1.dp)
.background(Color.LightGray)
)
}
}
}
fun setLocaleLang(lang: String, context: Context) {
val locale = Locale(lang)
Locale.setDefault(locale)
val resources = context.resources
val configuration = resources.configuration
configuration.setLocale(locale)
resources.updateConfiguration(configuration, resources.displayMetrics)
val editor = context.getSharedPreferences("Settings", Context.MODE_PRIVATE).edit()
editor.putString("My_Lang", lang)
editor.apply()
}
fun loadLocale(context: Context) {
val sharedPreferences = context.getSharedPreferences("Settings", Activity.MODE_PRIVATE)
val language = sharedPreferences.getString("My_Lang", "")
setLocaleLang(language!!, context)
}
MainActivity.kt
class MainActivity : ComponentActivity() {
#ExperimentalFoundationApi
override fun onCreate(savedInstanceState: Bundle?) {
loadLocale(this)
super.onCreate(savedInstanceState)
setContent {
SpanishTravelTheme {
Image: https://i.stack.imgur.com/y5kcO.png
Try this
val context = LocalContext.current
Row(
modifier = Modifier
.fillMaxWidth()
.clickable {
val locale = Locale(language) //Here I assume you have access to the language you want
Locale.setDefault(locale)
val resources = context.getResources()
val configuration = resources.getConfiguration()
configuration.locale = locale
resources.updateConfiguration(configuration, resources.getDisplayMetrics())
}
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
)
You can try this
Create a helper object
LocaleUtils.kt
object LocaleUtils {
// [AppPrefs] is sharedpreferences or datastore
fun setLocale(c: Context, pref: AppPrefs) = updateResources(c, pref.language ?: "en") //use locale codes
private fun updateResources(context: Context, language: String) {
context.resources.apply {
val locale = Locale(language)
val config = Configuration(configuration)
context.createConfigurationContext(configuration)
Locale.setDefault(locale)
config.setLocale(locale)
context.resources.updateConfiguration(config, displayMetrics)
}
}
}
Call setLocale inside setContent to change the language at runtime.
setContent {
LocaleUtils.setLocale(LocalContext.current, viewModel.pref)
To change the App language
fun changeAppLanguage(languageISO: String) {
sharedPrefs.edit().putString(LANGUAGE_KEY, languageISO).apply()
}
Please remember to use language ISO 639-1 Code
here's a list of Locale codes
https://developers.google.com/interactive-media-ads/docs/sdks/android/client-side/localization

how to fix conversion error when converting from java to kotlin

I am a student, new to kotlin, so I am converting java codes to kotlin to learn and see how it works, but I didnt understand what the error says.
private val _songs = ArrayList<SongInfo>()
internal lateinit var recyclerView: RecyclerView
internal lateinit var seekBar: SeekBar
internal lateinit var songAdapter: SongAdapter
internal var mediaPlayer: MediaPlayer? = null
private val myHandler = Handler()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById(R.id.recyclerView) as RecyclerView
seekBar = findViewById(R.id.seekBar) as SeekBar
songAdapter = SongAdapter(this, _songs)
recyclerView.adapter = songAdapter
val linearLayoutManager = LinearLayoutManager(this)
val dividerItemDecoration = DividerItemDecoration(recyclerView.context,
linearLayoutManager.orientation)
recyclerView.layoutManager = linearLayoutManager
recyclerView.addItemDecoration(dividerItemDecoration)
songAdapter.setOnItemClickListener { b, view, obj, position ->
if (b.text == "Stop") {
mediaPlayer!!.stop()
mediaPlayer!!.reset()
mediaPlayer!!.release()
mediaPlayer = null
b.text = "Play"
} else {
val runnable = Runnable {
try {
mediaPlayer = MediaPlayer()
mediaPlayer!!.setDataSource(obj.songUrl)
mediaPlayer!!.prepareAsync()
mediaPlayer!!.setOnPreparedListener { mp ->
mp.start()
seekBar.progress = 0
seekBar.max = mediaPlayer!!.duration
Log.d("Prog", "run: " + mediaPlayer!!.duration)
}
b.text = "Stop"
} catch (e: Exception) {
}
}
myHandler.postDelayed(runnable, 100)
}
}
checkUserPermission()
val t = runThread()
t.start()
}
inner class runThread : Thread() {
override fun run() {
while (true) {
try {
Thread.sleep(1000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
Log.d("Runwa", "run: " + 1)
if (mediaPlayer != null) {
seekBar.post { seekBar.progress = mediaPlayer!!.currentPosition }
Log.d("Runwa", "run: " + mediaPlayer!!.currentPosition)
}
}
}
}
private fun checkUserPermission() {
if (Build.VERSION.SDK_INT >= 23) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 123)
return
}
}
loadSongs()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
123 -> if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
loadSongs()
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()
checkUserPermission()
}
else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
private fun loadSongs() {
val uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
val selection = MediaStore.Audio.Media.IS_MUSIC + "!=0"
val cursor = contentResolver.query(uri, null, selection, null, null)
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
val name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME))
val artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST))
val url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA))
val s = SongInfo(name, artist, url)
_songs.add(s)
} while (cursor.moveToNext())
}
cursor.close()
songAdapter = SongAdapter(this#MainActivity, _songs)
}
}
}
This is the error:
"Error:(46, 44) Type mismatch: inferred type is (???, ???, ???, ???)
-> Any but SongAdapter.OnItemClickListener was expected Error:(46, 46) Cannot infer a type for this parameter. Please specify it explicitly."
Batch conversion to Kotlin is not the best way to learn the language. I suggest you to re-implement your Android component in Kotlin manually, to get the feeling of language.
The error you see says: "I can not understand how this lambda with 4 parameters can be an instance of SongAdapter.OnItemClickListener, please help". You can try anonymous class in this place.

Changing the constraints in a Container object

In Java 8, the Container class has an void add(Component comp, Object constraints) method that adds the component with a constraints information. I want to build a GUI with three panels, where pressing a button would result in switching the constraint information of the components that do not include the button object. How is it possible to switch the constraint information?
EDIT:
I tried the following:
private Map<SpecUITitlePanel, GridBagConstraints> constraints = new Hashtable<SpecUITitlePanel, GridBagConstraints>();
[…]
switchPanelsButton.setText( "Switch panels");
switchPanelsButton.addActionListener( new java.awt.event.ActionListener() {
public void actionPerformed( final java.awt.event.ActionEvent event) {
switchPanelsActionPerformed( event);
}
[…]
private void switchPanelsActionPerformed( final java.awt.event.ActionEvent event) {
boolean swapped = false;
final GridBagLayout layout = (GridBagLayout) getLayout();
final Iterator<SpecUITitlePanel> keysIter = constraints.keySet().iterator();
// summaryPanel, testPanel
while (keysIter.hasNext() && layout != null) {
final SpecUITitlePanel key = keysIter.next();
final String title = key.getTitle();
final Iterator<SpecUITitlePanel> keysIter2 = constraints.keySet().iterator();
while (keysIter2.hasNext()) {
final SpecUITitlePanel key2 = keysIter2.next();
final String title2 = key2.getTitle();
if (!title.equals( title2)) {
if (!title.contains( BUTTON_PANEL_TITLE) && !title2.contains( BUTTON_PANEL_TITLE)) {
// swap components
String message = "component = " + title + ", "
+ constraints.get( key) + "; component2 = " + title2
+ ", " + constraints.get( key2);
System.out.println( message);
final GridBagConstraints value = constraints.get( key);
final GridBagConstraints value2 = constraints.get( key2);
constraints.put(key, value2);
layout.setConstraints( key, value2);
constraints.put(key2, value);
layout.setConstraints( key2, value);
swapped = true;
message = "component = " + title + ", "
+ constraints.get( key) + "; component2 = " + title2
+ ", " + constraints.get( key2);
System.out.println( message);
}
}
}
}
if (swapped) {
repaint();
}
}
The relevant part of the output is
component = Test, java.awt.GridBagConstraints#5179288b; component2 = tna.rads.main_panel.violation_summary_panel, java.awt.GridBagConstraints#f1a7ed2
component = Test, java.awt.GridBagConstraints#f1a7ed2; component2 = tna.rads.main_panel.violation_summary_panel, java.awt.GridBagConstraints#5179288b

Strange behavior of threads

I’m writing an application that communicates with some hardware using the MODBUS protocol.
I'm using this sample from Code Project.
While trying to optimize the code (mainly the PollFunction function), I've encountered with a very strange threads lock.
Instead of sending each line of string to the DoGUIUpdate delagate, I'm constructing a string array and sending it as a whole.
Doing so causes the application to crush with a System.Reflection.targetParametercountException: Parameter count mismatch error.
The original code:
public delegate void GUIUpdate(string paramString);
public void DoGUIUpdate(string paramString)
{
if (InvokeRequired)
BeginInvoke(new GUIUpdate(DoGUIUpdate), paramString);
else
lstRegisterValues.Items.Add(paramString);
}
private void PollFunction()
{
...
string itemString;
for (int i = 0; i < pollLength; i++)
{
itemString = "[" + Convert.ToString(pollStart + i + 40001) + "] , MB[" + Convert.ToString(pollStart + i) + "] = " + values[i];
DoGUIUpdate(itemString);
}
}
My code:
public delegate void GUIUpdate2(string[] paramString);
public void DoGUIUpdate2(string[] paramString)
{
if (InvokeRequired)
BeginInvoke(new GUIUpdate2(DoGUIUpdate2), paramString);
else
{
lstRegisterValues.Items.Clear();
lstRegisterValues.Items.AddRange(paramString);
}
}
string[] valuesStrings;
private void PollFunction()
{
...
valuesStrings = new string[pollLength];
for (int i = 0; i < pollLength; i++)
{
valuesStrings[i] = "[" + Convert.ToString(pollStart + i + 40001) + "] , MB[" + Convert.ToString(pollStart + i) + "] = " + values[i];
}
DoGUIUpdate2(valuesStrings);
}
Any advice will be welcome.
i think BeginInvoke(new GUIUpdate2(DoGUIUpdate2), paramString); is the problem...
the second parameter of "begininvoke" accepts a param object[] params which will result in the call DoGuiUpdate(string1,string2,string3) which is not what you want...
try encapsulate in the following way:
BeginInvoke(new GUIUpdate2(DoGUIUpdate2), new[]{ paramString });

Resources