首页 > 其他分享 >【android 】Android intent 传递对象以及返回刷新

【android 】Android intent 传递对象以及返回刷新

时间:2023-02-21 14:56:07浏览次数:50  
标签:public intent user new import android Android User

之前项目需要,找过这方面知识。所以今天也总结一下。大家都知道activity跳转用intent,Android的当前页面跳转到新的页面。当然跳转的同时常常要携带数据或者对象。那我下面就说说跳转带对象吧。还有在例子当中,新的activity返回时,也有对象一起返回。下面看代码,只要入门Android了都看得懂,我就不再写很多注释了。

有两种对象类型可以传递,一是Parcelable,推荐用这个。二是Serializable。当然你在class建立对象时,都要对这两个进行接口。看代码。

 

package com.example.intentdemo;
 
import android.os.Parcel;
import android.os.Parcelable;
 
public class User implements Parcelable{
 
    private String name;
    private String sex;
    private int eage;
    
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getSex() {
        return sex;
    }
 
    public void setSex(String sex) {
        this.sex = sex;
    }
 
    public int getEage() {
        return eage;
    }
 
    public void setEage(int eage) {
        this.eage = eage;
    }
    
    public static final Parcelable.Creator<User> CREATOR = new Creator<User>() {
        public User createFromParcel(Parcel source) {
            User user = new User();
            user.name = source.readString();
            user.sex = source.readString();
            user.eage = source.readInt();
            return user;
        }
 
        public User[] newArray(int size) {
            return new User[size];
        }
    };
 
    @Override
    public int describeContents() {
        return 0;
    }
 
    @Override
    public void writeToParcel(Parcel parcel, int arg1) {
         parcel.writeString(name);  
         parcel.writeString(sex);  
         parcel.writeInt(eage);  
    }
 
}

 

package com.example.intentdemo;
 
import java.io.Serializable;
 
public class Student implements Serializable {
    private String name;
    private String sex;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public int getEage() {
        return eage;
    }
    public void setEage(int eage) {
        this.eage = eage;
    }
    private int eage;
}

MainActivity.class

 

package com.example.intentdemo;
 
import java.util.ArrayList;
 
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
 
public class MainActivity extends Activity implements OnClickListener {
 
    private ArrayList<User> mArrayListUsers = new ArrayList<User>();
    private ArrayList<Student> mArrayListStudent = new ArrayList<Student>();
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        InitUI();
    }
 
    private void InitUI() {
        Button Parcelable = (Button) findViewById(R.id.button1);
        Button Serializable = (Button) findViewById(R.id.button2);
 
        if (Parcelable != null) {
            Parcelable.setOnClickListener(this);
        }
        if (Serializable != null) {
            Serializable.setOnClickListener(this);
        }
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 
    @Override
    public void onClick(View arg0) {
        if (arg0.getId() == R.id.button1) {
            setParcelable();
        } else if (arg0.getId() == R.id.button2) {
            setSerializable();
        }
 
    }
 
    private void setSerializable() {
        Student student = new Student();
        student.setName("Serializable");
        student.setSex("nv");
        student.setEage(25);
 
        mArrayListStudent.add(student);
        mArrayListStudent.add(student);
 
        Intent mIntent = new Intent(this, IntentSerializableActivity.class);
        Bundle mBundle = new Bundle();
        mBundle.putSerializable("student_key", student); // 传递一个user对象
        mBundle.putSerializable("student_Arry", mArrayListStudent); // 传递一个user对象列表
        mIntent.putExtras(mBundle);
 
        startActivityForResult(mIntent, 200); // 带返回结果的Intent,标志码是1
 
    }
 
    private void setParcelable() {
        User user = new User();
        user.setName("Parcelable");
        user.setSex("nan");
        user.setEage(25);
 
        mArrayListUsers.add(user);
        mArrayListUsers.add(user);
 
        Intent mIntent = new Intent(this, IntentParcelableActivity.class);
        Bundle mBundle = new Bundle();
        mBundle.putParcelable("User_key", user); // 传递一个user对象
        mBundle.putParcelableArrayList("User_Arry", mArrayListUsers); // 传递一个user对象列表
        mIntent.putExtras(mBundle);
 
        startActivityForResult(mIntent, 100); // 带返回结果的Intent,标志码是1
 
    }
 
    // 返回activity页面刷新
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        TextView show = (TextView) findViewById(R.id.test);
        if (resultCode == RESULT_OK && requestCode == 100) {
 
            Bundle bundle = this.getIntent().getExtras();
            if (bundle != null) {
                mArrayListUsers = bundle.getParcelableArrayList("User_Arry");
            }
 
            show.setText("");
            show.append("IntentParcelableActivity返回的数据: " + "\n");
            for (int i = 0; i < mArrayListUsers.size(); i++) {
                User userArrayList = new User();
                userArrayList = mArrayListUsers.get(i);
                show.append("name is: " + userArrayList.getName() + "\n"
                        + "age is: " + userArrayList.getEage() + "\n");
            }
 
        } else if (resultCode == RESULT_OK && requestCode == 200) {
 
            Bundle bundle = this.getIntent().getExtras();
            if (bundle != null) {
                mArrayListStudent = (ArrayList<Student>) bundle
                        .getSerializable("student_Arry");
            }
 
            show.setText("");
            show.append("IntentSerializableActivity返回的数据: " + "\n");
            for (int i = 0; i < mArrayListStudent.size(); i++) {
                Student studentArrayList = new Student();
                studentArrayList = mArrayListStudent.get(i);
                show.append("name is: " + studentArrayList.getName() + "\n"
                        + "age is: " + studentArrayList.getEage() + "\n");
            }
 
        }
    }
 
}

接受数据新的activity

 

IntentParcelableActivity.class

package com.example.intentdemo;
 
import java.util.ArrayList;
 
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.Menu;
import android.widget.TextView;
 
public class IntentParcelableActivity extends Activity {
    private ArrayList<User> mArrayListUsers = new ArrayList<User>();
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        TextView mTextView = new TextView(this);
 
        User user = new User();
        Bundle bundle = this.getIntent().getExtras();
        if (bundle != null) {
            user = bundle.getParcelable("User_key");
            mArrayListUsers = bundle.getParcelableArrayList("User_Arry");
        }
 
        mTextView.append("You name is: " + user.getName() + "\n"
                + "You age is: " + user.getEage() + "\n" + "\n");
 
        for (int i = 0; i < mArrayListUsers.size(); i++) {
            User userArrayList = new User();
            userArrayList = mArrayListUsers.get(i);
            mTextView.append("You name is: " + userArrayList.getName() + "\n"
                    + "You age is: " + userArrayList.getEage() + "\n");
        }
 
        setContentView(mTextView);
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    // 返回按键调用
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            Bundle mBundle = new Bundle();  
            mBundle.putParcelableArrayList("User_Arry", mArrayListUsers);   //传递一个user对象列表
            intent.putExtras(mBundle);      
            setResult(RESULT_OK, intent);
            finish();
        }
        return true;
    }
 
}

IntentSerializableActivity.class

 

package com.example.intentdemo;
 
import java.util.ArrayList;
 
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.Menu;
import android.widget.TextView;
 
public class IntentSerializableActivity extends Activity {
    private ArrayList<Student> mArrayListStudent=new ArrayList<Student>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        TextView mTextView = new TextView(this);
 
        Student student = new Student();
        Bundle bundle = this.getIntent().getExtras();
        if (bundle != null) {
            student = (Student) bundle.getSerializable("student_key");
            mArrayListStudent = (ArrayList<Student>) bundle.getSerializable("student_Arry");
        }
 
        mTextView.append("You name is: " + student.getName() + "\n"
                + "You age is: " + student.getEage() + "\n" + "\n");
 
        for (int i = 0; i < mArrayListStudent.size(); i++) {
            Student studentArrayList = new Student();
            studentArrayList = mArrayListStudent.get(i);
            mTextView.append("You name is: " + studentArrayList.getName() + "\n"
                    + "You age is: " + studentArrayList.getEage() + "\n");
        }
 
        setContentView(mTextView);
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    // 返回按键调用
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            Bundle mBundle = new Bundle();  
            mBundle.putSerializable("student_Arry", mArrayListStudent);   //传递一个user对象列表
            intent.putExtras(mBundle);      
            setResult(RESULT_OK, intent);
            finish();
        }
        return true;
    }
 
}

【参考链接】

Android中的Parcelable详解

Android使用Parcelable传递对象方法及注意事项

android对象序列化Parcelable浅析

     

 

 

标签:public,intent,user,new,import,android,Android,User
From: https://www.cnblogs.com/opensmarty/p/17140998.html

相关文章

  • Android和adb命令
    一、名词解释1、SDK:是软件开发工具包2、activity(活动):驱使软件运行的一段程序,软件系统和用户进行交互的界面叫一个活动二、adb命令1、查看连接的设备:adbdevices2、......
  • Android应用禁止屏幕休眠的3种方法
    做android应用开发时,有时需要在应用前台运行时,禁止休眠,以下几种方法供参考。方法一:持有wakelock添加休眠锁,休眠锁必须成对出现。privatewakelockmwakelock=null;......
  • 保持Android Service在手机休眠后继续运行的方法
    保持AndroidService在手机休眠后继续运行的方法 下面小编就为大家分享一篇保持AndroidService在手机休眠后继续运行的方法,具有很好的参考价值,希望对大家有所帮助。一......
  • ue5 - 打包 android apk
    1.要求需要提前安装androidstudio和jdk1.8 androidstudio 我的版本是  android-studio-ide-201.7199119-windows大版本号4.1.32.有个坑项目路径不要有......
  • ue5 - android 打包卡在下载gradle Downloading https://services.gradle.org/distri
    1.下载gradle国内镜像地址https://downloads.gradle-dn.com/distributions/gradle-6.1.1-all.zip下载后,将文件放入\.gradle\wrapper\dists\gradle-6.1.1-all\cfmwm15......
  • 如何在高版本Android 调用 SystemProperties.set
     在高版Android中是无法找到SystemProperties类的,所以我们需要手动导入低版本的SDK.第一步、在app的build.gradle添加:StringSDK_DIR=System.getenv("/Users/dan......
  • Android  JetPack~ ViewModel (一)   介绍与使用
     Android数据绑定技术一,企业级开发Android数据绑定技术二,企业级开发Android JetPack~DataBinding(数据绑定)(一)  集成与使用Android JetPack~LiveData(......
  • writing to settings requires:android.permission.WRITE_SECURE_SETTINGS
    appium第一次连接手机时,报错:java.lang.SecurityException:Permissiondenial:writingtosettingsrequires:android.permission.WRITE_SECURE_SETTINGS解决办法,即打开......
  • Android数据存储知识总结一(小水一波~~)
    第一种获取共享参数的方式是使用键值对SharedPreferences存储结构是key-value键值对,类似于xml文件SharedPreferenceshared=getSharedPreference("share",MODE_PRIVA......
  • 空间清理大师(Windows/Android)
    一坨答辩的系统,一堆存储管理差劲的各类app软件Windows1.使用Dism++/360卫士极速版清理删除使用windows自带功能做的备份,强烈推荐使用Dism++代替windows备份功能关闭休......