Friday, December 26, 2014

The method getContentResolver() is undefined for the type...

Normally we will call getContentResolver() in our Activity or ActionBarActivity... to get a ContentResolver instance for your application's package. In case you try to call it at seperate class, you will be reported error of "The method getContentResolver() is undefined for the type...". You have to pass Context of your activity to the another class to call getContentResolver(), as shown in the video.

This example also show different ContentResolver return with different context passed.
package com.example.androidhello;

import android.content.ContentResolver;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

 protected void onCreate(Bundle savedInstanceState) {
  TextView tv = new TextView(this);
  ContentResolver contentResolverA = getContentResolver();
  //same ContentResolver returned
  ContentResolver contentResolverB = AnotherClass.tryGetContentResolver(this);
  //ContentResolver contentResolverB = AnotherClass.tryGetContentResolver(MainActivity.this);
  //ContentResolver contentResolverB = AnotherClass.tryGetContentResolver(tv.getContext());
  //ContentResolver contentResolverB = AnotherClass.tryGetContentResolver(getBaseContext());

  //not same
  //ContentResolver contentResolverB = AnotherClass.tryGetContentResolver(getApplicationContext());
  String msg = this +"\n"
    + MainActivity.this + "\n"
    + tv.getContext() + "\n"
    + getBaseContext() + "\n"
    + getApplicationContext() + "\n\n";
  if(contentResolverA == contentResolverB){
   msg += "contentResolverA == contentResolverB\n"
    + contentResolverB;
   msg += "contentResolverA != contentResolverB\n"
    + contentResolverA + "\n"
    + contentResolverB;

package com.example.androidhello;

import android.content.ContentResolver;
import android.content.Context;

public class AnotherClass {
 static public ContentResolver tryGetContentResolver(Context c){
  ContentResolver contentResolver = c.getContentResolver();
  return contentResolver;


No comments: