You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发求助:用SharedPreference存二维码联系人并在ListView展示

嘿,作为Android新手能想到用SharedPreferences来存数据已经很棒啦!针对你的需求,我给你一步步拆解实现方法,同时也会给你一些存储方案的建议~

一、存储方案选择建议
  • 如果你的联系人数据量很小(比如几十条以内):用SharedPreferences完全够用,配合Gson把联系人对象转成JSON字符串存储,简单易上手。
  • 如果以后可能要存大量联系人、需要做查询/排序等操作:推荐用Room数据库,它是Jetpack官方组件,ORM操作不用写复杂SQL,对新手也友好。
    先从你提到的SharedPreferences入手,上手更快!
二、具体实现步骤

1. 定义联系人实体类

先把二维码解析出的联系人信息封装成实体类,方便后续操作:

// Kotlin写法(简洁易维护),Java可改成普通类加getter/setter
data class Contact(
    val name: String,
    val phone: String,
    val email: String? // 可选字段,问号表示可为空
)

2. 解析二维码并存储到SharedPreferences

假设你已经用扫码库(比如ZXing)解析出了Contact对象,接下来把它存入SharedPreferences:
首先在app/build.gradle的dependencies中添加Gson依赖,用来把对象转成JSON字符串:

implementation 'com.google.code.gson:gson:2.10.1'

然后写存储逻辑:

// 获取SharedPreferences实例,MODE_PRIVATE表示仅当前应用可访问
val sharedPref = getSharedPreferences("ContactStorage", MODE_PRIVATE)
val editor = sharedPref.edit()

val gson = Gson()
// 先读取已存储的联系人列表(避免覆盖原有数据)
val existingContactsJson = sharedPref.getString("contacts", "")
val contactsList = if (existingContactsJson.isNullOrEmpty()) {
    mutableListOf<Contact>()
} else {
    gson.fromJson(existingContactsJson, object : TypeToken<MutableList<Contact>>() {}.type)
}

// 替换成你从二维码解析到的真实联系人对象
val newContact = Contact("张三", "138xxxx1234", "zhangsan@example.com")
contactsList.add(newContact)

// 更新后的列表转成JSON存回SharedPreferences
val updatedJson = gson.toJson(contactsList)
editor.putString("contacts", updatedJson)
editor.apply() // 异步提交,比commit更高效

3. 在目标Activity读取数据并展示到ListView

首先写一个ListView的适配器,用来渲染联系人项:

class ContactAdapter(context: Context, private val contacts: List<Contact>) :
    ArrayAdapter<Contact>(context, android.R.layout.simple_list_item_2, contacts) {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        // 复用View提升性能
        val view = convertView ?: LayoutInflater.from(context)
            .inflate(android.R.layout.simple_list_item_2, parent, false)
        val contact = contacts[position]
        // 给列表项的两个文本框赋值
        view.findViewById<TextView>(android.R.id.text1).text = contact.name
        view.findViewById<TextView>(android.R.id.text2).text = contact.phone
        return view
    }
}

然后在目标Activity的onCreate方法中读取数据并绑定适配器:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_contact_list)

    val listView = findViewById<ListView>(R.id.list_view)
    val sharedPref = getSharedPreferences("ContactStorage", MODE_PRIVATE)
    val gson = Gson()

    // 读取存储的联系人JSON并转成列表
    val contactsJson = sharedPref.getString("contacts", "")
    val contactsList = if (contactsJson.isNullOrEmpty()) {
        emptyList<Contact>()
    } else {
        gson.fromJson(contactsJson, object : TypeToken<List<Contact>>() {}.type)
    }

    // 设置适配器
    val adapter = ContactAdapter(this, contactsList)
    listView.adapter = adapter

    // 可选:添加列表项点击事件
    listView.setOnItemClickListener { _, _, position, _ ->
        val selectedContact = contactsList[position]
        Toast.makeText(this, "选中了:${selectedContact.name}", Toast.LENGTH_SHORT).show()
    }
}

最后别忘了在目标Activity的布局文件中添加ListView:

<!-- activity_contact_list.xml -->
<ListView
    android:id="@+id/list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
三、额外小贴士
  • 如果你用Java开发,逻辑完全一致,仅语法稍有不同,比如Gson的TypeToken写法会变成new TypeToken<MutableList<Contact>>(){}.getType()
  • 扫码功能推荐用ZXing的Android集成库,依赖为implementation 'com.journeyapps:zxing-android-embedded:4.3.0',能快速实现扫码解析
  • 若后续数据量增大,建议切换到Room数据库,它更适合处理结构化、大批量的数据

内容的提问来源于stack exchange,提问作者sumit sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:29:17