Monday, October 31, 2011

CountDownTimer Error: Can't create handler inside thread that has not called Looper.prepare()

Today I was getting this error "Can't create handler inside thread that has not called Looper.prepare()" in a CountDownTimer. All this time this code used to work perfectly but suddenly it stopped.

Problem is, in CountDownTimer.java (Android source code) it creates a mHandler inside the code which makes the caller should call the CountDownTimer class on UI thread which is not possible in my case. So I created a separate Timer class,

Timer cTimer = new Timer();
private final static int START_FROM = 60;

cTimer.scheduleAtFixedRate(new TimerTask() {
int i = START_FROM ;
public void run() {
Log.d(TAG, "Comparison will start in:" + i--);
if (i< 0) {
cTimer.cancel();
// Do something
}
}
}, 0, 1000);

Tuesday, October 25, 2011

How to enable/disable Mobile Data on Android 2.3

Today, colleague asked me whether i know how to enable and disable mobile internet on Android ? Actually, I was curious about this for sometime and never had the time to look into how to do this. So this is how to do it.

I tired it on Android 2.3 i tried this code and it worked! When I looked into Android source code I saw this method is available 2.2 R1 up.


  private boolean getMobileDataEnabled() {
        try {
            Method method = connectivityManager.getClass().getMethod("getMobileDataEnabled");
            return (Boolean)method.invoke(connectivityManager);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    private void setMobileDataEnabled(boolean on) {
        try {
            Method method = connectivityManager.getClass().getMethod("setMobileDataEnabled",
                    boolean.class);
            method.invoke(connectivityManager, on);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
If you are using 2.2 R1 or later try this code.


Wednesday, October 19, 2011

android.content.OperationApplicationException: wrong number of rows: 0

Today I got this error tying to update a contact in Android 2.3 Nexus S device which was working fine on Motorola Milestone (Android 2.1 - update 1). Reason was I was getting the "withExpectedCount" parameter as 1

ops.add(ContentProviderOperation. newInsert(addCallerIsSyncAdapterParameter(ContactsContract.Data.CONTENT_URI))
.withValue(ContactsContract.Data.RAW_CONTACT_ID, contact.getId())
.withValue(ContactsContract.Data.MIMETYPE, CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(CommonDataKinds.Phone.NUMBER, phone)
.withValue(CommonDataKinds.Phone.TYPE, cm.getType()).withExpectedCount(1).build());

When i removed it it worked fine .. Looks like if the original and updating content values are same it does not update the row :|