0

Hello i found this method that creates a file and add strings in it

public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try {
    File root = new File(Environment.getExternalStorageDirectory(), "Notes");
    if (!root.exists()) {
        root.mkdirs();
    }
    File gpxfile = new File(root, sFileName);
    FileWriter writer = new FileWriter(gpxfile);
    writer.append(sBody);
    writer.flush();
    writer.close();
    Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
    e.printStackTrace();
}
}

My question is how to call this method ? i tried something like this

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String FILENAME = "hello_file";
    String string = "hello world!";
    generateNoteOnSD(Context ,FILENAME,string);
}

I don't understand the Context context part

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Kyriakos
  • 29
  • 4

4 Answers4

2

you need to call the getApplicationContext() if you are in an Activity

generateNoteOnSD(getApplicationContext(),FILENAME,string);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

use

generateNoteOnSD(YoureActivity.this,FILENAME,string);
Jai Khambhayta
  • 4,198
  • 2
  • 22
  • 29
0
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 String FILENAME = "hello_file";
 String string = "hello world!";
 generateNoteOnSD(YourActivityName.this ,FILENAME,string);
}
Akash
  • 961
  • 6
  • 15
  • 1
    **From review queue:** May I request you to please add some more context around your answer. Code-only answers are difficult to understand. It will help the asker and future readers both if you can add more information in your post. – help-info.de May 30 '17 at 18:09
0

If your using Fragment then do like this

generateNoteOnSD(getContext(),FILENAME,string);

if it is Activity do like this

generateNoteOnSD(YourActivityName.this,FILENAME,string);
T B
  • 24
  • 4