简体   繁体   中英

Writing to a file with context - Android

I created a button which should write the selected item from two dropdown-spinners into a txt-file.

To do this I am using this method:

    public static void save(Context ctx) {
    FileOutputStream fos;
    try {

        fos = ctx.openFileOutput("config.txt", Context.MODE_PRIVATE);


        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(MyActivity.klasse);
        oos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }catch(IOException e){
        e.printStackTrace();
    }
}

This is my onClickListener:

btnSave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

                String text = sp_jahrgang.getSelectedItem().toString() + sp_klasse.getSelectedItem().toString();
                System.out.println("JAHRGANG:"+text);

                MyActivity.klasse = text;
                System.out.println("TEST:"+MyActivity.klasse);
                save();
        }
    });

The problem is that I do not really understand the concept of "context". I do not know what kind of context I have to use. What do I have to put into the brackets for the method save?

Any help is appreciated

You need to pass the context of the activity in the brackets of save method. While using this method you need to pass context in following manner,

  • If you are accessing the method from fragment then pass getActivity() inside the bracket

    ie save(getActivity());

  • If you are calling this method from any activity then you can simply put this (not very safe to store reference to context but good enough for many tasks) or getApplicationContext() in the brackets.

    ie save(getApplicationContext())

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