Home > Mobile >  Android Kotlin | Picking random line from text file
Android Kotlin | Picking random line from text file

Time:12-02

very simple, android kotlin. i have a file in the project assest folder with sentence in each line. what i wants, is when i open dialog, it will select random line and put it as the dialog message. i couldn't find any proper solution. dialog's code:

class JokeFragment : DialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return activity?.let {
            val sentence: String = //random line from the file
            // Use the Builder class for convenient dialog construction
            val builder = Builder(it)
            builder.setMessage(sentence)
                .setNegativeButton(R.string.cancel){ _, _->}
            // Create the AlertDialog object and return it
            builder.create()
        } ?: throw IllegalStateException("Activity cannot be null")
    }
}

CodePudding user response:

Based on this answer:

fun readRandomLineFromAsset(context: Context, fileName: String): String =
        context
            .assets
            .open(fileName)
            .bufferedReader()
            .use(BufferedReader::readText)
            .lines()
            .shuffled()
            .first()

Updated code - shuffled().first() instead of random()

Random picks same line every time fo some reason.

CodePudding user response:

I solved it by this: Activity:

val sharedPreference =  getSharedPreferences("PREFERENCE_NAME", Context.MODE_PRIVATE)
val editor = sharedPreference.edit()
...
    btn.setOnClickListener{
        val file = assets.open("jokes.txt")
        val joke :String =file.bufferedReader().use(BufferedReader::readText).lines().shuffled().first()
        editor.putString("joke", joke)
        editor.apply()
        JokeFragment().show(supportFragmentManager, "NoticeDialogFragment")
    }

Dialog:

val sharedPreference = requireActivity().getSharedPreferences("PREFERENCE_NAME", Context.MODE_PRIVATE)
val joke = sharedPreference.getString("joke" , "error")
  • Related