检查整数值是否增加?
我有以下代码,用于检查数据库中的行数。
private void checkMMSRows(){
Cursor curPdu = getContentResolver().query(Uri.parse("content://mms/part"), null, null, null, null);
if (curPdu.moveToNext()){
int number = curPdu.getCount();
System.out.println(number);
}
}
我将每秒运行此代码并在值发生变化时执行某些操作。问题是,我如何去“检测”变化?任何帮助将不胜感激。
I have the following code, which checks for the number of rows in the database.
private void checkMMSRows(){
Cursor curPdu = getContentResolver().query(Uri.parse("content://mms/part"), null, null, null, null);
if (curPdu.moveToNext()){
int number = curPdu.getCount();
System.out.println(number);
}
}
I will to run this code every second and do something when the value has changed. The problems is, how do I go about "detecting" the change? Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
基本上,添加一个类变量 - 您可以将其设置为该类的所有实例的静态变量,也可以将其设置为实例变量(通过删除静态关键字)。
每次获得一个数字时,您都可以将其与
oldNumber
进行比较。比较后,将oldNumber
设置为当前数字 - 这样您下次就有了可比较的内容:更新:
我的答案是直接代码 hack &斜杠解决方案,但我可能会推荐amit的答案。
Very basically, add a class variable - you can either make it
static
across all instances of the class, or an instance variable (by removing thestatic
keyword).Each time you get a number, you can compare it to
oldNumber
. After the comparison, set theoldNumber
to the current number - so you have something to compare against next time:Update:
My answer's a straight code hack & slash solution, but I'd probably recommend amit's answer.
取决于运行的上下文。
假设该方法所属的对象在不同的检查之间存在,您需要做的就是向该对象添加一个 int currentValue 字段,将第一次检查时的值存储在那里,然后将该值与存储的值进行比较在后续检查中(并在必要时更新)
Depends on the context in which this is run.
Assuming that the Object which this method belongs to will live between different checks, all you need to do is to add a int currentValue field to the object, store the value in there first time you check, and then compare the value with the stored ones in subsequent checks (and update if necessary)
您可能需要考虑一种替代方案,而不是每秒检查元素是否已更改:仅允许对此元素进行特殊访问,并在更改后执行某些操作。
这是一种众所周知的设计模式,称为观察者模式。
这是一种经过充分验证的设计模式,它将使您的代码更具可读性,并且可能还会提高应用程序的性能和正确性。
编辑:
在java中,可以使用观察者 接口和 Observable按顺序上课这样做。
Instead of checking every second if your element was changed, you might want to consider an alternative: allow only special access to this element, and do something once it is changed.
This this is a well known design pattern and is called the Observer Pattern.
This is a well-proven design pattern, which will make your code more readable, and will probably also enhance performance, and correctness of your application.
EDIT:
In java, you can use the Observer interface and Observable class in order to do so.
您可以为新的彩信注册一个
braodcastreceiver
,这样您就会知道更改已经发生。you can regsister a
braodcastreceiver
for new coming mms and this way you will come to know that the change has taken place..