hashmap和SharedPreferences存储

本文介绍了如何将HashMap转换为字符串并存储在Android的SharedPreferences中,详细步骤包括:HelloActivity、FirstActivity的操作,通过Extras传递数据,以及使用SpUtils进行SharedPreferences的存取操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

hashmap和SharedPreferences存储

把hashmap转换成string,然后存到共享参数里面,然后从共享参数取数据

step1: HelloActivity

package com.example.myapplication;

import static com.example.myapplication.ExtrasKt.FIRST_GUID_NET;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
import java.util.HashMap;

public class HelloActivity extends AppCompatActivity {
   

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
   
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello);

        Button btn_hello = findViewById(R.id.btn_hello);

        btn_hello.setOnClickListener(new View.OnClickListener() {
   
            @Override
            public void onClick(View v) {
   
                hashmapTest();
            }
        });
    }

    private void hashmapTest() {
   
        HashMap<String, String> testHashMap = new HashMap<String, String>();
        testHashMap.put("A4:C1:07:7F:74:2B", "通断器");
        testHashMap.put("A7:C1:07:7F:74:2B", "随意贴");
        Gson gson = new Gson();
        String hashMapString = gson.toJson(testHashMap);
        SpUtils.putString(HelloActivity.this, FIRST_GUID_NET, hashMapString);
        Intent intent = new Intent(HelloActivity.this,FirstActivity.class);
        startActivity(intent);
    }
}

step2: FirstActivity

package com.example.myapplication;


import static com.example.myapplication.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值