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.
Very basically, add a class variable - you can either make it static
across all instances of the class, or an instance variable (by removing the static
keyword).
Each time you get a number, you can compare it to oldNumber
. After the comparison, set the oldNumber
to the current number - so you have something to compare against next time:
private static int oldNumber = -1;
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);
if(number != oldNumber){
System.out.println("Changed");
// add any code here that you want to react to the change
}
oldNumber = number;
}
}
Update:
My answer's a straight code hack & slash solution, but I'd probably recommend amit's answer.
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)
int currentValue = 0;
private void checkMMSRows(){
Cursor curPdu = getContentResolver().query(Uri.parse("content://mms/part"), null, null, null, null);
if (curPdu.moveToNext()){
int newValue = curPdu.getCount();
if (newvalue != currentValue) {
//detected a change
currentValue = newValue;
}
System.out.println(newValue);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With