简体   繁体   中英

Need to use SQLiteOpenHelper in a Jersey REST service but I cannot pass required Android context

I am trying to replace in-memory data with data from a database, which will be the data that is used in a REST API. The API is a service running on an Android box. In order to use SQLiteOpenHelper I must pass a Context to the class that extends it. Unfortunately, the thread that handles the REST API does not instantiate a class to which I can pass down Context, rather it configures the API as such:

public static void createServer(){
    new Thread(new Runnable() {
        @Override
        public void run() {
            URI baseUri = UriBuilder.fromUri("http://localhost/").port(8080).build();
            ResourceConfig config = new ResourceConfig(ThingResource.class);
            config.register(GsonMessageBodyHandler.class);
            config.register(AndroidFriendlyFeature.class);
            JettyHttpContainerFactory.createServer(baseUri, config);
        }
    }).start();
}

Here's the class that requires Context for me to use:

public class DbHelper extends SQLiteOpenHelper {
    private final String DB_NAME = DatabaseContract.DATABASE_NAME;
    private SQLiteDatabase db;

    public DbHelper(Context context) {
        super(context, DatabaseContract.DATABASE_NAME, null, DatabaseContract.DATABASE_VERSION);
    }

    //rest of class handles db methods
}

Here is where createServer() is called:

public class RoomStatus extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        JerseyBootstrap.createServer();
        //rest of method/class set up main screen
    }
}

How can I either pass Context to the REST service so I can use DbHelper or use some other method to get data from SQLite database?

Why dont you try this:

public static void createServer(Context context){
    new Thread(new Runnable() {
        @Override
        public void run() {
            URI baseUri = UriBuilder.fromUri("http://localhost/").port(8080).build();
            ResourceConfig config = new ResourceConfig(ThingResource.class);
            config.register(GsonMessageBodyHandler.class);
            config.register(AndroidFriendlyFeature.class);
            JettyHttpContainerFactory.createServer(baseUri, config);
        }
    }).start();
}

And call it this way:

public class RoomStatus extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        JerseyBootstrap.createServer(this);
        //rest of method/class set up main screen
    }
}

由于ThingResource是静态类,因此我仅从主要活动中设置上下文。

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