-1

I created DBHelper.java class in my android project. In my OnCreate() method I create tables to my database, but I also want to insert rows to these tables. So I made file - script.sql, that contains my insert queries. Everything would work fine, but I cannot solve one problem - context.

This is my code I put in DBHelper class:

   private void executeScript()
{
    InputStream inputStream = this.getResources().openRawResource(R.raw.script); // I get error here.
    byte[] buffer = new byte[7844];
    String queries = "";
    try {
        inputStream.read(buffer);
        queries =  new String(buffer,"UTF-8");
    } catch (Exception e) {
        Log.e("Error", e.toString());
    }
    for (String query : queries.split(";")) {
        Log.e("Query", query);
    }

}

I get error in line : this.getResources()... I know that I can't use this, but what can I do instead? I know this code just displays logs, but I'll add execSQL later.

ktos1234
  • 197
  • 1
  • 6
  • 22
  • 1
    Am I right in thinking you basically want this? http://stackoverflow.com/questions/2002288/static-way-to-get-context-on-android – Michael Dec 12 '16 at 22:32
  • I tried it but I got some errors I can't handle with. Maybe there's another way to execute my script that I don't need to use context – ktos1234 Dec 12 '16 at 22:39
  • 1
    If you want to get a resource you generally need a Context. What are the errors you're getting when you do the above? – Michael Dec 12 '16 at 22:43
  • I tried again, I got errors because I wrote MyApplication class in current activity. This time I create new MyApplication.java class in my project and it seems to be working. I am just not sure that method like that is good solution. There has to be better solution for this. Anyways, thank you, I've been trying to solve this problem for 2 hours... – ktos1234 Dec 12 '16 at 22:55
  • 2
    I tend to agree. You should avoid a static getter if you possible can. Ideally you want to propagate the Context down and pass it as an argument to `void executeScript(Context context)` – Michael Dec 12 '16 at 22:58

1 Answers1

0

Pass the text of the script into executeScript(), by having the caller retrieve the R.raw.script resource value.

Or, pass a Resources into executeScript(), so it can call openRawResource().

Or, pass a Context into executeScript(), so it can call getResources() on the Context.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • TLDR: dependency injection. – Michael Dec 12 '16 at 22:35
  • I want to keep all text of the script in one file, because it will be bigger and I don't want to put all of these in code. What do you mean pass resources into executeScript?? Can you write how would it look in my code. Thank you – ktos1234 Dec 12 '16 at 22:42