当您可以使用静态变量执行相同的任务时,为什么要使用 Parcelable?
我是 android 和 java 的新手...我花了几天时间阅读有关 android 打包教程的内容,用于将数据或变量值从一个活动传输到另一个活动或从一个类传输到另一个类...但我对此不太了解。 你能告诉我是否有必要使用 Parcelable
来达到此目的,因为同样的任务也可以使用 static
关键字作为字符串、int 或数组类型的变量来执行,那么为什么可包裹请详细解释.. 感谢您的提前解释,请提供与示例的比较
i am new in android and java ... i am reading from couples of day about android parceling tutorial for transfer data or variables values from one activity to other or one class to other ... but i am not so understood about that.
can u tell me that is it necessary to use Parcelable
for this purpose because same task can also be perform using static
key word for variables as string,int or array type then why parcelable pls explain in detail ..
thanks for explanation in advance please provide comparison with example
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然从技术上讲这两种方法都可行,但存在一些缺陷。
首先是静态变量是静态的。如果同一个活动有两个实例,它们都将引用同一个静态对象。这可能不是您想要的。
其次,访问全局变量被认为是不好的做法。这使得很难看到正在发生的事情,很难测试,并且你的某人(另一个类)可以修改你的数据。这会产生一些可怕的错误。
通过通过 Parcelable 对象传递数据,您在做什么就非常清楚,并且可以避免这两个问题。
请注意,此建议并非特定于 Android,而是特定于 Java 和一般编程。
While technically both approaches will work, there are a couple of flaws.
The first is that the static variable is static. If you have two instances of the same activity, they will both reference the same static object. This is probably not what you want.
Secondly, it's considered bad practice to access global variables. It makes it difficult to see what is going on, is difficult to test and you someone (another class) can modify your data. This creates some horrendous bugs.
By passing the data via a Parcelable object it is very clear what you are doing and you avoid both of these problems.
Note that this advice is not specific to Android, rather to Java and programming in general.
静态引用永远不会被垃圾收集,因此最终会造成内存泄漏。
您在内存中保留了一个不需要的对象,并且无法释放它。
如果您像这样实例化足够多的对象,您将收到内存不足(oom)异常,这将导致应用程序崩溃。
Static references never get garbage collected so you end up creating something called a memory leak.
You are keeping an object in memory that you don't need and it can't be freed up.
If you instantiate enough objects like this you will get an out of memory (oom) exception which will cause the app to crash.