Computer >> Máy Tính >  >> Lập trình >> Android

Cách chuyển dữ liệu giữa các hoạt động với Android Serializable

Sử dụng tuần tự hóa, chúng ta có thể chuyển trạng thái hoặc mảng của đối tượng giữa hai hoạt động. Trước khi đi vào mã, chúng ta nên biết về tuần tự hóa và cách nó hoạt động với ý định trong android.

Serialization là một giao diện đánh dấu. Sử dụng tuần tự hóa, chúng ta có thể chuyển đổi trạng thái của một đối tượng thành một luồng byte. Luồng byte là một nền tảng độc lập, vì vậy nó sẽ hoạt động trên JVM và các nền tảng khác. Đây là ví dụ để gửi một đối tượng giữa hai hoạt động.

Bước 1 - Tạo một dự án mới trong Android Studio, Đi tới Tệp ⇒ Dự án Mới và điền tất cả các chi tiết cần thiết để tạo một dự án mới.

Bước 2 - Thêm mã sau vào res / layout / activity_main.xml.

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout
   xmlns:android = "https://schemas.android.com/apk/res/android" xmlns:tools = "https://schemas.android.com/tools" android:layout_width = "match_parent"
   android:layout_height = "match_parent">
<LinearLayout
   android:layout_width = "match_parent"
   android:layout_height = "wrap_content"
   android:gravity = "center_horizontal"
   android:orientation = "vertical">
   <EditText
      android:id = "@+id/name"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:ems = "10"
      android:hint = "Enter a name"
      android:inputType = "text" />
   <EditText
      android:id = "@+id/phone"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:ems = "10"
      android:hint = "Enter a Phone number"
      android:inputType = "number"/>
   <Button
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content"
      android:text = "Send data"
      android:id = "@+id/send"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>

Bước 2 - Sau đây là nội dung của tệp hoạt động chính MainActivity.java đã được sửa đổi. Tệp này có thể bao gồm từng phương pháp vòng đời cơ bản.

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   EditText name;
   EditText phone;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      name = findViewById(R.id.name);
      phone = findViewById(R.id.phone);
      Button send = findViewById(R.id.send);
      send.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            if (TextUtils.isEmpty(name.getText().toString()) && TextUtils.isEmpty(phone.getText().toString())) {
               Toast.makeText(MainActivity.this,"Something is wrong kindly check",Toast.LENGTH_LONG).show();
            }else{
sendUserData(name.getText().toString(),phone.getText().toString());
            }
         }
      });
   }
   private void sendUserData(String username, String userPhone) {
      Userinfo userinfo = new Userinfo();
      userinfo.setName(username);
      userinfo.setPhone(userPhone);
      Intent send = new Intent(MainActivity.this,SecondActivity.class);
      Bundle b = new Bundle();
      b.putSerializable("serialzable",userinfo);
      send.putExtras(b);
      startActivity(send);
   }
}

Bước 3 - Sau đây là nội dung của tệp hoạt động chính đã được sửa đổi SecondActivity.java. Tệp này có thể bao gồm từng phương pháp vòng đời cơ bản. Hoạt động này sẽ truy cập đối tượng từ MainActivity như hình dưới đây -

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity {
   Userinfo userinfo;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_second);
      TextView data = findViewById(R.id.data);
      userinfo = (Userinfo) getIntent().getSerializableExtra("serialzable");
      String name = userinfo.getName();
      String phone = userinfo.getPhone();
      data.setText("Your entered name is "+name+" number is "+phone);
   }
   @Override
   protected void onPause() {
      super.onPause();
      userinfo = null;
   }
}

Bước 3 - Sau đây là nội dung của đối tượng Userinfo có thể nối tiếp. Dữ liệu đối tượng này chúng ta đang chuyển giữa MainActivity và SecondActivity. Để làm cho đối tượng có thể tuần tự hóa Userinfo, chúng ta nên triển khai java.io.Serializable giao diện như hình bên dưới -

import java.io.Serializable;
class Userinfo implements Serializable {
   String name;
   String phone;
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getPhone() {
      return phone;
   }
   public void setPhone(String phone) {
      this.phone = phone;
   }
}

Hãy thử chạy ứng dụng của bạn. Tôi giả sử bạn đã kết nối thiết bị Di động Android thực tế với máy tính của mình. Để chạy ứng dụng từ android studio, hãy mở một trong các tệp hoạt động của dự án của bạn và nhấp vào Chạy Cách chuyển dữ liệu giữa các hoạt động với Android Serializable biểu tượng từ thanh công cụ. Chọn thiết bị di động của bạn làm tùy chọn, sau đó kiểm tra thiết bị di động sẽ hiển thị màn hình mặc định của bạn.

Cách chuyển dữ liệu giữa các hoạt động với Android Serializable


Cách chuyển dữ liệu giữa các hoạt động với Android Serializable

Bây giờ hãy nhấp vào nút Gửi dữ liệu, nó sẽ đưa bạn đến SecondActivity như hình dưới đây -

Cách chuyển dữ liệu giữa các hoạt động với Android Serializable

Trong đầu ra ở trên, chúng tôi đã có thông tin từ MainActivity đến SecondActivity