Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how use getContentResolver in a class without activity?

Tags:

android

my class looks like this:

public class sendInformation{

  public void test() throws Exception {
    Uri uri = SuspiciousActivityTable.CONTENT_URI;
    getContentResolver().update(uri, values2, where,new String[]{"Null"});
    }
  }
}

but it say getContentResolver() doesn't exist, I know I need a Context or Activity to make this work but how do I get the correct Context here?

like image 730
user2033349 Avatar asked Feb 25 '13 22:02

user2033349


2 Answers

You will need to pass off a Context, even the ContentResolver class needs a valid context to be instantiated.

Simplest way is as an argument to the method:

public void test(Context context) throws Exception {
    Uri uri = SuspiciousActivityTable.CONTENT_URI;
    context.getContentResolver().update(uri, values2, where,new String[]{"Null"});
  }

And to call: (assuming that the class that contains test is instantiated and your Activity's name is MyActivity <- Replace with the Activity name you're calling test() from)

try{
    sendInformationInstanceVariable.test (MyActivity.this);
}
catch (Exception e)
{
 e.printStackTrace();
}

MyActivity.this can be shortened to just this if you're not calling test() from inside an anonymous inner class.

Also, if your class really doesn't have a good reason to be instantiated, consider making test() a static method, like this:

public static void test(Context context) throws Exception {
        Uri uri = SuspiciousActivityTable.CONTENT_URI;
        context.getContentResolver().update(uri, values2, where,new String[]{"Null"});
      }

Then from your Activity, you call this method without needing an instance:

try{
    sendInformation.test (MyActivity.this);
}
catch (Exception e)
{
 e.printStackTrace();
}

Lastly, throwing Exception is bad practice, do don't do it without good reason and if you do have a good reason, be as specific as possible.

like image 139
A--C Avatar answered Nov 06 '22 04:11

A--C


Somewhere between where your application starts (and you have access to getApplicationContext()) and the point where you call test(), you'll need to pass in a Context to your sendInformation class. I would look at what lifecycle your sendInformation class has and compare it to the various Android components (Application, Activity, Fragment) and use the appropriate context from there:

  • Application: getApplicationContext()

  • Activity: this (as Activity extends Context)

  • Fragment: getActivity()
like image 36
ianhanniballake Avatar answered Nov 06 '22 05:11

ianhanniballake