从文件中读取数据,并在应用屏幕上使用Jetpack Compose显示数据。

huangapple go评论59阅读模式
英文:

Read and display data from file on an app screen using jetpack compose

问题

我正在使用Jetpack Compose和Kotlin在Android Studio中构建一个应用程序。
这个应用程序能够显示特定歌曲的标题和作者等信息。我想到使用JSON文件来存储所有的数据,以便应用程序可以读取数据并在应用程序的“音乐屏幕”上显示它。

这是我的项目的外观:

为了实现这个目标,我进行了一些测试。
首先,在MainActivity文件中使用了applicationContext.assets.open("musics.json")

data class MyData(
    val title: String,
    val author: String,
)

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val jsonString = applicationContext.assets
                .open("musics.json")
                .bufferedReader()
                .use { it.readText() }

            val dataArray = JSONArray(jsonString)
            val dataList = mutableListOf<MyData>()

            for (i in 0 until dataArray.length()) {
                val item = dataArray.getJSONObject(i)
                val title = item.getString("title")
                val author = item.getString("author")
                dataList.add(MyData(title, author))
            }

            LazyColumn {
                items(dataList.size) {
                    Row {
                        Text(dataList[it].title)
                        Text(dataList[it].author)
                    }
                }
            }
        }
    }
}

这种方法非常有效,但我想在MusicsScreen上显示数据。不幸的是,我之前使用的applicationContext对象仅在MainActivity类中可用。所以我不得不尝试其他方法。

我在MusicsScreen文件中尝试了File.io库,但它并没有正常工作,导致错误。有人知道如何解决这个问题吗?

附言:我是移动开发的初学者,对Jetpack Compose框架了解不多,所以如果您认为我应该加深学习中的某些方面,请不要犹豫告诉我。

英文:

I am using jetpack compose and kotlin in android studio to build an app.
This app would be able to display certain songs like title and author. I came up with the idea of using a JSON file to write all my data so the app could read the data and display it on the "Musics Screen" of the app.
This is what my project looks like :

从文件中读取数据,并在应用屏幕上使用Jetpack Compose显示数据。

To achieve this goal I made some tests.
First, by using applicationContext.assets.open(&quot;musics.json&quot;) in the MainActivity file:


data class MyData(
    val title: String,
    val author: String,
)

class MainActivity : ComponentActivity() {
    // Routing object
    // lateinit var navController: NavHostController

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
          
                //navController = rememberNavController()

                val jsonString = applicationContext.assets
                    .open(&quot;musics.json&quot;)
                    .bufferedReader()
                    .use { it.readText() }

            val dataArray = JSONArray(jsonString)
            val dataList = mutableListOf&lt;MyData&gt;()

            for (i in 0 until dataArray.length()) {
                val item = dataArray.getJSONObject(i)
                val title = item.getString(&quot;title&quot;)
                val author = item.getString(&quot;author&quot;)
                dataList.add(MyData(title, author))
            }

            LazyColumn {
                items(dataList.size) {
                    Row {
                            Text(dataList[it].title)
                            Text(dataList[it].author)
                        }
                }
            }

            // entry point of my navigation graph
            // SetupNavGraph(navController = navController)


        }
    }
}

That method worked really well but I wanted to display the datas on the MusicsScreen.
And unfortunately, the applicationContext object that I used earlier is only available in the MainActivity class. So I had to use other methods.

I tried the File.io library in the MusicsScreen file but it didn't work properly and resulted in an error.
Does anyone have an idea how to make this work?

PS : I'm a beginner in mobile development and I don't know the JetPack Compose framework well so if you think I should deepen some point in my learning, don't hesitate to let me know.

答案1

得分: 0

好的,让我分享一种从文件中读取和显示数据的好方法,希望对你有帮助,检查下面的代码

首先创建 MusicUtils 文件并粘贴下面的代码:

fun getJsonDataFromAsset(
    context: Context,
    fileName: String
): String? {
    val jsonString: String
    try {
        jsonString = context.assets.open(fileName).bufferedReader().use {
            it.readText()
        }
    } catch (exp: IOException) {
        exp.printStackTrace()
        return null
    }

    return jsonString
}

fun musicList(context: Context): MutableList<MyData> {
    val jsonFileString = getJsonDataFromAsset(context = context, "musics.json")
    val type = object : TypeToken<List<MyData>>() {}.type
    return Gson().fromJson(jsonFileString, type)
}

data class MyData(
    val title: String,
    val author: String,
)

现在 musicList 函数包含了音乐数据的列表,可以在需要的地方调用这个函数。希望这对你有帮助! 🎵🎶

英文:

Okay let me share a good way to read and display data from a file hope it helps you , check the below code

First make MusicUtils file and paste the below code there

fun getJsonDataFromAsset(
    context: Context,
    fileName: String
): String? {
    val jsonString: String
    try {
        jsonString = context.assets.open(fileName).bufferedReader().use {
            it.readText()
        }
    } catch (exp: IOException) {
        exp.printStackTrace()
        return null
    }

    return jsonString
}

fun musicList(context: Context): MutableList&lt;MyData&gt; {
    val jsonFileString = getJsonDataFromAsset(context = context, &quot;musics.json&quot;)
    val type = object : TypeToken&lt;List&lt;MyData&gt;&gt;() {}.type
    return Gson().fromJson(jsonFileString, type)
}

data class MyData(
    val title: String,
    val author: String,
)

Now the musicList function contains the list of musics data , call this function where ever you want. Hope this will work👍🏻

huangapple
  • 本文由 发表于 2023年2月26日 21:39:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75572370.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定