开发者

Check if integer value has increased?

I have the following code, which checks for the number of rows in the d开发者_Go百科atabase.

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.


you can regsister a braodcastreceiver for new coming mms and this way you will come to know that the change has taken place..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜