Search code examples
javaandroidsavefilewriter

Empty saved text file


There's a problem i'm fighting with for two days. Using FileWriter I try to save data into txt file. File is saved by an application but it's always empty.

b1.setOnClickListener(new View.OnClickListener(){

       @Override
        public void onClick(View v) {

           try {

               boolean usunieto = true;
               boolean stworzono = false;

               String t_magazyn = e_magazyn.getText().toString();
               String nazwa = e_nazwa.getText().toString();

               if(!t_magazyn.trim().equals("")){

                   @SuppressLint("SdCardPath") File plik = new File("/sdcard/"+nazwa+".txt");

                   // jeśli plik nie istnieje, stwórz go

                   if(plik.exists()){

                       usunieto = plik.delete();
                       Toast.makeText(getApplicationContext(),"Plik został usunięty!",Toast
                               .LENGTH_SHORT).show();

                   }
                   if(usunieto){

                       stworzono = plik.createNewFile();
                       Toast.makeText(getApplicationContext(),"Plik utworzony!",Toast
                               .LENGTH_SHORT).show();

                   }
                   if(!usunieto||!stworzono){

                       Toast.makeText(getApplicationContext(),"Apka dalej cie olewa xD",Toast
                               .LENGTH_SHORT).show();

                   }

                   //THIS PART DOESN'T WORK AS INTENDED

                   FileWriter wpis = new FileWriter(plik.getName(),true);
                   BufferedWriter bufor = new BufferedWriter(wpis);
                   bufor.write(e_magazyn.getText().toString());
                   i_e_magazyn.setText(e_magazyn.getText().toString());
                   bufor.close();



               }
           }
           catch(IOException e) {

               e.printStackTrace();

           }

           }

    });

e_magazyn,e_nazwa are EditText fields and i_e_magazyn is TextView field

In b2 button which isn't visible here this line of code works.

i_e_magazyn.setText(e_magazyn.getText().toString());

I tried a lot of actions to update data into file but it looks like after creating a new FileWriter variables are made empty

How do i make it work?


Solution

  • You just need to write this line

    FileWriter wpis = new FileWriter(plik,true);
    

    Instead of

    FileWriter wpis = new FileWriter(plik.getName(),true);