0

I am getting this error at openFileOutput(FILENAME, Context.MODE_PRIVATE);

I used this code before, I don't know why it's not working now. The error reads: Method openFileOutput(String, int) is undefined for the type SaveProjects

package com.example.musicvideomaker;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

import android.content.Context;
import android.util.Log;

import com.example.musicvideomaker.Projects;

public class SaveProjects {

FileOutputStream fos;

public ArrayList<Projects> Projects;


public void saveProject(Projects project, String FILENAME)
{
    this.Projects.add(project);
    try
    {
    fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
    ObjectOutputStream os = new ObjectOutputStream(fos);
    os.writeObject(this);
    os.close();
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
}

}
  • Can you please paste the error from logcat ? – empr777 Jul 02 '14 at 18:46
  • you have moved the method `saveProject` from an activity to this new class, and `openFileOutput` is a method of `Context`. You need to pass a `Context` as a parameter, and call `openFileOutput` on it. – njzk2 Jul 02 '14 at 18:47
  • A syntax error shows up. The red underline is under openFileOutput – user3798867 Jul 02 '14 at 18:48
  • 1
    @user3798867 check this link http://stackoverflow.com/a/3626033/3469370 To this method you can pass your Service or Activity – empr777 Jul 02 '14 at 18:52
  • I created a new projects and it works. This project can't find the context at all. – user3798867 Jul 02 '14 at 19:15

1 Answers1

0

Since you're not in an activity, you need to use the Context to call "openFileOutput". Although your Context would either need to be statically declared in an Application file, or if you call the SaveProject class from an Activity, you could pass in the context as a parameter of the class (although it is bad practice). Then you could try this:

public class SaveProjects {

private Context context;

FileOutputStream fos;


public ArrayList<Projects> Projects;

public SaveProjects(Context context) {
    this.context = context;
}

public void saveProject(Projects project, String FILENAME)
{
    this.Projects.add(project);
    try
    {
    fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
    ObjectOutputStream os = new ObjectOutputStream(fos);
    os.writeObject(this);
    os.close();
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
}

}
aProperFox
  • 2,114
  • 2
  • 20
  • 21