简体   繁体   中英

Getting context in non-activity class comparator

I have to access my database from the comparator class from one of my entity-classes. For instancing the database connection I need an application context.

How do I get the application context in this case:

Entity - class with comparator

static public class CowLastInspectionComparator implements Comparator<Cow> {
    public int compare(Cow cow1, Cow cow2) {
        DbAdapter adapter = DbAdapter.getInstance(new MainView().getApplicationContext()); //this doesn't work
        List<Inspection> inspectionsCow1 = adapter.getInspectionByCow(cow1);
        List<Inspection> inspectionsCow2 = adapter.getInspectionByCow(cow2);

        return inspectionsCow1.get(0).getJob().getJobDate().compareTo(inspectionsCow2.get(0).getJob().getJobDate());
    }
}

Sorting in Activity:

 if (sortOption == "Name") Collections.sort(cows, new Cow.CowLastInspectionComparator());
static public class CowLastInspectionComparator implements Comparator<Cow> {
  private Context context;
  CowLastInspectionComparator(Context context){
    this.context=context;
  }
  public int compare(Cow cow1, Cow cow2) {
    DbAdapter adapter = DbAdapter.getInstance(context); //this doesn't work
    List<Inspection> inspectionsCow1 = adapter.getInspectionByCow(cow1);
    List<Inspection> inspectionsCow2 = adapter.getInspectionByCow(cow2);

    return inspectionsCow1.get(0).getJob().getJobDate().compareTo(inspectionsCow2.get(0).getJob().getJobDate());
  }
}

in Activity:

 if (sortOption == "Name"){
    Cow.CowLastInspectionComparator comparator=new Cow.CowLastInspectionComparator(this);
    Collections.sort(cows,comparator);
 } 

I have to access my database from the comparator class from one of my entity-classes

If by this you mean that you want to do database I/O in compare() , that is going to make your compare() calls slow and your sort() calls very slow. If you want to sort your, um, cows, and they are not all in memory, do a single database query with an ORDER BY clause to get them properly sorted.

For instancing the database connection I need an application context.

You need a Context . It would not necessarily have to be an Application .

How do I get the application context in this case

Supply one to the CowLastInspectionComparator , such as via a constructor parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM