Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-1106· OpenAIHugging Face Arena Human Preference 55K

For Android, in Kotlin write code to select and load context of file on button click.

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Perplexitypplx-7b-online’s answer.
  1. User

    For Android, in Kotlin write code to select and load context of file on button click.

  2. Assistant

    Sure! Here's an example of how you can select and load the content of a file in Kotlin for an Android app:

    import android.content.Intent
    import android.net.Uri
    import android.os.Bundle
    import android.widget.Button
    import androidx.activity.result.contract.ActivityResultContracts
    import androidx.appcompat.app.AppCompatActivity
    import java.io.BufferedReader
    import java.io.InputStreamReader
    
    class MainActivity : AppCompatActivity() {
    
        private val pickFile = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                result.data?.data?.let { uri ->
                    val inputStream = contentResolver.openInputStream(uri)
                    val reader = BufferedReader(InputStreamReader(inputStream))
                    val content = StringBuilder()
                    var line: String?
                    while (reader.readLine().also { line = it } != null) {
                        content.append(line)
                    }
                    // Do something with the loaded file content
                    // For example, display it in a TextView
                    // textView.text = content.toString()
                }
            }
        }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            val button: Button = findViewById(R.id.button)
            button.setOnClickListener {
                val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
                    addCategory(Intent.CATEGORY_OPENABLE)
                    type = "*/*"
                }
                pickFile.launch(intent)
            }
        }
    }
    

    In this code, we use the ActivityResultContracts.StartActivityForResult contract to handle the file selection. When the button is clicked, it creates an intent to open a document, and then launches the file picker using pickFile.launch(intent). When a file is selected, the content is read from the file and can be used as needed.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.