-1

So, I am porting my IRC Bot to run on my Tab, which uses 4.4.2 (API 19)

The function that is giving me problems for the last day now is the Quote Database, which adds quotes by users and stores them into files - they can be retrieved and displayed. Now, i am already biting my teeth out on creating a file. The method is as follows:

    public void createFile(String filenick){

        try {
           FileOutputStream os = MainActivity.context.openFileOutput(filenick, 0);
           os.close();
        } catch (FileNotFoundException e) {
            System.out.println("createFile "+filenick+" happened");
        } catch (IOException e) {
            System.out.println("IO error " + filenick + " happened");
        }


    }

The context is coming from

public class MainActivity extends Activity {

    public static Context context=new MainActivity().getApplication();

It compiles fine, and Android Studio isnt giving me any kind of errors. The Bot works with all his functions except this.

 java.lang.NullPointerException
    at com.coilworks.dreaddroid.QDBClass.createFile(QDBClass.java:175)
    at com.coilworks.dreaddroid.QDBClass.adder(QDBClass.java:57)

For Context: QDBClass.java:175 is the line starting with FileOutputStream.

57 is where createFile gets called.

I have so far, tried every possible iteration of Outputstreams and writers that the android documentation holds.

Maybe i just searched for the wrong terms?

mkobit
  • 43,979
  • 12
  • 156
  • 150
Scriver
  • 11
  • 1

2 Answers2

1

You should never instantiate an Activity directly. It is the framework's job to do that.

public static Context context=new MainActivity().getApplication();

That line is probably the root of many of the issues you are seeing. context will always be null in this case.

Emmanuel
  • 13,083
  • 4
  • 39
  • 53
0

First, never create an activity instance yourself (e.g., new Activity()).

Second, do not call methods on an activity instance until that activity has been created (i.e., is at least through the onCreate() implementation from Activity itself), unless specifically told otherwise.

Your context will always be null, given your code above.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491