序列化

序列化

Serializable

  • activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/edt_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Name"
        android:inputType="textPersonName"
        android:minHeight="48dp"
        app:layout_constraintBottom_toTopOf="@+id/edt_age"
        app:layout_constraintEnd_toStartOf="@+id/guideline3"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/edt_math"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Math"
        android:inputType="textPersonName"
        android:minHeight="48dp"
        app:layout_constraintBottom_toTopOf="@+id/edt_english"
        app:layout_constraintEnd_toEndOf="@+id/edt_name"
        app:layout_constraintTop_toBottomOf="@+id/edt_age" />

    <EditText
        android:id="@+id/edt_english"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="English"
        android:inputType="textPersonName"
        android:minHeight="48dp"
        app:layout_constraintBottom_toTopOf="@+id/edt_chinese"
        app:layout_constraintEnd_toEndOf="@+id/edt_name"
        app:layout_constraintTop_toBottomOf="@+id/edt_math" />

    <EditText
        android:id="@+id/edt_chinese"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Chinese"
        android:inputType="textPersonName"
        android:minHeight="48dp"
        app:layout_constraintBottom_toTopOf="@+id/guideline2"
        app:layout_constraintEnd_toEndOf="@+id/edt_name"
        app:layout_constraintTop_toBottomOf="@+id/edt_english" />

    <EditText
        android:id="@+id/edt_age"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Age"
        android:inputType="textPersonName"
        android:minHeight="48dp"
        app:layout_constraintBottom_toTopOf="@+id/edt_math"
        app:layout_constraintEnd_toEndOf="@+id/edt_name"
        app:layout_constraintTop_toBottomOf="@+id/edt_name" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.6" />

    <TextView
        android:id="@+id/tv_grade"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/btn_save"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/guideline3"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="save"
        app:layout_constraintBottom_toTopOf="@+id/btn_load"
        app:layout_constraintEnd_toEndOf="@+id/tv_grade"
        app:layout_constraintStart_toStartOf="@+id/tv_grade"
        app:layout_constraintTop_toBottomOf="@+id/tv_grade" />

    <Button
        android:id="@+id/btn_load"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="load"
        app:layout_constraintBottom_toTopOf="@+id/guideline2"
        app:layout_constraintStart_toStartOf="@+id/btn_save"
        app:layout_constraintTop_toBottomOf="@+id/btn_save" />
</androidx.constraintlayout.widget.ConstraintLayout>
  • Student.java
package com.example.myserialization;

import java.io.Serializable;

public class Student implements Serializable {
    // 用ide自动生成版本号。否则,类的结构变化后,数据就没了。
    private static final long serialVersionUID = -7091411988309226703L;
    private String name;
//    private transient int age; // 设置该属性不参加序列化
    private int age;
    private Score score;

    public Student(String name, int age, Score score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Score getScore() {
        return score;
    }

    public void setScore(Score score) {
        this.score = score;
    }
}

class Score implements Serializable{
    private static final long serialVersionUID = -3142893894209501048L;
    private int Math;
    private int English;
    private int Chinese;
    private String grade;

    public Score(int math, int english, int chinese) {
        Math = math;
        English = english;
        Chinese = chinese;
        if (math >= 90 && english >= 90 && chinese >= 90) {

            this.grade = "A";
        } else if (math >= 80 && english >= 80 && chinese >= 80) {
            this.grade = "B";
        } else {
            this.grade = "C";
        }
    }

    public int getMath() {
        return Math;
    }

    public void setMath(int math) {
        Math = math;
    }

    public int getEnglish() {
        return English;
    }

    public void setEnglish(int english) {
        English = english;
    }

    public int getChinese() {
        return Chinese;
    }

    public void setChinese(int chinese) {
        Chinese = chinese;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }
}

  • MainActivity.java
package com.example.myserialization;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class MainActivity extends AppCompatActivity {
    private EditText edt_name, edt_age, edt_math, edt_english, edt_chinese;
    private Button btn_save, btn_load;
    private TextView tv_grade;
    public static final String FILE_NAME = "myfile.data";

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

        edt_name = findViewById(R.id.edt_name);
        edt_age = findViewById(R.id.edt_age);
        edt_math = findViewById(R.id.edt_math);
        edt_english = findViewById(R.id.edt_english);
        edt_chinese = findViewById(R.id.edt_chinese);
        btn_save = findViewById(R.id.btn_save);
        btn_load = findViewById(R.id.btn_load);
        tv_grade = findViewById(R.id.tv_grade);

        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int math = Integer.parseInt(edt_math.getText().toString());
                int english = Integer.parseInt(edt_english.getText().toString());
                int chinese = Integer.parseInt(edt_chinese.getText().toString());
                Score score = new Score(math, english, chinese);
                String name = edt_name.getText().toString();
                int age = Integer.parseInt(edt_age.getText().toString());
                Student student = new Student(name, age, score);

                try {
                    // 写入对应用来说是输出,从磁盘读取是输入
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(openFileOutput(FILE_NAME, MODE_PRIVATE));
                    objectOutputStream.writeObject(student);
                    objectOutputStream.flush(); // 清理缓冲区
                    objectOutputStream.close();
                    Toast.makeText(MainActivity.this, "存入成功", Toast.LENGTH_SHORT).show();
                    edt_name.getText().clear();
                    edt_age.getText().clear();
                    edt_english.getText().clear();
                    edt_math.getText().clear();
                    edt_chinese.getText().clear();
                    tv_grade.setText("-");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        btn_load.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    ObjectInputStream objectInputStream = new ObjectInputStream(openFileInput(FILE_NAME));
                    Student student = (Student) objectInputStream.readObject();
                    edt_name.setText(String.valueOf(student.getName()));
                    edt_age.setText(String.valueOf(student.getAge()));
                    edt_math.setText(String.valueOf(student.getScore().getMath()));
                    edt_english.setText(String.valueOf(student.getScore().getEnglish()));
                    edt_chinese.setText(String.valueOf(student.getScore().getChinese()));
                    tv_grade.setText(String.valueOf(student.getScore().getGrade()));
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });

    }
}

Parcelable

  • activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <EditText
            android:id="@+id/edt_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Name"
            android:inputType="textPersonName"
            app:layout_constraintBottom_toTopOf="@+id/edt_age"
            app:layout_constraintEnd_toEndOf="@+id/edt_age"
            app:layout_constraintStart_toStartOf="@+id/edt_age"
            app:layout_constraintTop_toTopOf="parent" />

        <EditText
            android:id="@+id/edt_age"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Age"
            android:inputType="textPersonName"
            app:layout_constraintBottom_toTopOf="@+id/edt_math"
            app:layout_constraintEnd_toEndOf="@+id/edt_math"
            app:layout_constraintStart_toStartOf="@+id/edt_math"
            app:layout_constraintTop_toBottomOf="@+id/edt_name" />

        <EditText
            android:id="@+id/edt_math"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Math"
            android:inputType="textPersonName"
            app:layout_constraintBottom_toTopOf="@+id/edt_english"
            app:layout_constraintEnd_toEndOf="@+id/edt_english"
            app:layout_constraintStart_toStartOf="@+id/edt_english"
            app:layout_constraintTop_toBottomOf="@+id/edt_age" />

        <EditText
            android:id="@+id/edt_english"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="English"
            android:inputType="textPersonName"
            app:layout_constraintBottom_toTopOf="@+id/button"
            app:layout_constraintEnd_toEndOf="@+id/button"
            app:layout_constraintStart_toStartOf="@+id/button"
            app:layout_constraintTop_toBottomOf="@+id/edt_math" />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/edt_english" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
  • activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity2">

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name"
            android:textSize="34sp"
            app:layout_constraintBottom_toTopOf="@+id/tv_age"
            app:layout_constraintEnd_toEndOf="@+id/tv_age"
            app:layout_constraintStart_toStartOf="@+id/tv_age"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/tv_age"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Age"
            android:textSize="34sp"
            app:layout_constraintBottom_toTopOf="@+id/tv_math"
            app:layout_constraintEnd_toEndOf="@+id/tv_math"
            app:layout_constraintStart_toStartOf="@+id/tv_math"
            app:layout_constraintTop_toBottomOf="@+id/tv_name" />

        <TextView
            android:id="@+id/tv_math"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Math"
            android:textSize="34sp"
            app:layout_constraintBottom_toTopOf="@+id/tv_english"
            app:layout_constraintEnd_toEndOf="@+id/tv_english"
            app:layout_constraintStart_toStartOf="@+id/tv_english"
            app:layout_constraintTop_toBottomOf="@+id/tv_age" />

        <TextView
            android:id="@+id/tv_english"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="English"
            android:textSize="34sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tv_math" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
  • 注册清单里设置第二个进程
<activity
    android:name=".MainActivity2"
    android:process=":process2"
    android:exported="true" />
  • Student.java
package com.example.myserialization2;

import android.os.Parcel;
import android.os.Parcelable;

public class Student implements Parcelable {
    private String name;
    private int age;
    private Score score;

    public Student(String name, int age, Score score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    protected Student(Parcel in) {
        name = in.readString();
        age = in.readInt();
        score = in.readParcelable(Score.class.getClassLoader());
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(age);
        dest.writeParcelable(score, flags);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public static final Creator<Student> CREATOR = new Creator<Student>() {
        @Override
        public Student createFromParcel(Parcel in) {
            return new Student(in);
        }

        @Override
        public Student[] newArray(int size) {
            return new Student[size];
        }
    };

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Score getScore() {
        return score;
    }

    public void setScore(Score score) {
        this.score = score;
    }
}

class Score implements Parcelable {
    private static final long serialVersionUID = -3142893894209501048L;
    private int Math;
    private int English;


    public Score(int math, int english) {
        Math = math;
        English = english;
    }

    protected Score(Parcel in) {
        Math = in.readInt();
        English = in.readInt();
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(Math);
        dest.writeInt(English);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public static final Creator<Score> CREATOR = new Creator<Score>() {
        @Override
        public Score createFromParcel(Parcel in) {
            return new Score(in);
        }

        @Override
        public Score[] newArray(int size) {
            return new Score[size];
        }
    };

    public int getMath() {
        return Math;
    }

    public void setMath(int math) {
        Math = math;
    }

    public int getEnglish() {
        return English;
    }

    public void setEnglish(int english) {
        English = english;
    }

}
  • MainActivity.java
package com.example.myserialization2;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.example.myserialization2.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        Log.d("wmj", "onCreate: " + android.os.Process.myPid());
//        Log.d("wmj", "onCreate: " + Thread.currentThread().getId());

        ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        binding.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = binding.edtName.getText().toString();
                int age = Integer.valueOf(binding.edtAge.getText().toString());
                int math = Integer.valueOf(binding.edtMath.getText().toString());
                int english = Integer.valueOf(binding.edtEnglish.getText().toString());
                Student student = new Student(name, age, new Score(math, english));

                Intent intent = new Intent(MainActivity.this, MainActivity2.class);
//                intent.putExtra("student", student);
                Bundle bundle = new Bundle();
                bundle.putParcelable("student", student);
                intent.putExtra("data", bundle);
                startActivity(intent);
            }
        });
    }
}
  • MainActivity2.java
package com.example.myserialization2;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.content.Intent;
import android.os.Bundle;

import com.example.myserialization2.databinding.ActivityMain2Binding;

public class MainActivity2 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActivityMain2Binding binding = DataBindingUtil.setContentView(this, R.layout.activity_main2);

        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("data");
        Student student = bundle.getParcelable("student");
        binding.tvName.setText(student.getName());
        binding.tvAge.setText(String.valueOf(student.getAge()));
        binding.tvMath.setText(String.valueOf(student.getScore().getMath()));
        binding.tvEnglish.setText(String.valueOf(student.getScore().getEnglish()));
    }
}

Gson

  • 添加依赖
implementation 'com.google.code.gson:gson:2.8.8'
  • 属性前加@SerializedName("student_name")自定义序列化时的名称
Gson gson = new Gson();

// 单个对象
Student student1 = new Student("Tom", 20, new Score(100, 99, 98));
String jsonStr1 = gson.toJson(student1);
String jsonStr2 = "{\"age\":22,\"name\":\"Lili\",\"score\":{\"Chinese\":80,\"English\":97,\"Math\":100}}";
Student student2 = gson.fromJson(jsonStr2, Student.class);

// List
List<Student> list = new ArrayList<>();
list.add(student1);
list.add(student2);
String jsonList = gson.toJson(list);
String jsonList2 = "[{\"age\":20,\"name\":\"Tom\",\"score\":{\"Chinese\":98,\"English\":99,\"Math\":100}},{\"age\":22,\"name\":\"Lili\",\"score\":{\"Chinese\":80,\"English\":97,\"Math\":100}}]";
Type typeStudents = new TypeToken<List<Student>>(){}.getType();
list = gson.fromJson(jsonList2, typeStudents);

// 数组
Student[] students = {student1, student2};
String jsonStudents1 = gson.toJson(students);
String jsonStudents2 = "[{\"age\":20,\"name\":\"Tom\",\"score\":{\"Chinese\":98,\"English\":99,\"Math\":100}},{\"age\":22,\"name\":\"Lili\",\"score\":{\"Chinese\":80,\"English\":97,\"Math\":100}}]";
Student[] students2 = gson.fromJson(jsonStudents2, Student[].class);
posted @ 2021-09-13 09:23  n1ce2cv  阅读(36)  评论(0编辑  收藏  举报