0

I am beginner in programming in Android Studio. I want to make apk which work like described below:

  • press the button
  • the integer number 1 is saved to txt file
  • if I close apk and re-open and press button again, I get number 2 to txt file and this process repeat(3,4,5...ect).

What I need to do(in the program):

  1. Create file if not exist
  2. Look if txt. file have already some number inside and sub this number +1 and if no exist (txt file is empty) I need to add integer value 1 to txt. file.

    Below is my program, I have a problem with public void length() - when I was tested program with log.d always show empty file but I was check txt. file in Device file explorer and have number 1 inside txt.file. I was also trying with BufferdReader (br.readLine()) and get the same result. I don't know where is the problem...

public class MainActivity extends AppCompatActivity {

    Button btn;
    private static int Counter = 0;
    private static final String FILE_NAME = "data.txt";
    private static String TAG="MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Counter++;
                Log.d(TAG, "onClick: counter "+Counter);
                saveChec();
                Lengt();
                //load();
                // subSu();
            }
        });
    }

    private void subSu() {

    }

    public void Lengt(){
        long length = new File(getFilesDir().getAbsolutePath() + FILE_NAME).length();
        if (length == 0){
            //get alvays empty..
            Log.d(TAG, "Buff: empty ");
            save(); //add value 1 to txt file
            
        }else{
            Log.d(TAG, "Buff: full");
        }
    }

    public void saveChec() {

        FileOutputStream fos = null;

        try {
            fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
            Log.d(TAG, "saveChec: crated file ");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // return;

    }

    public void load() {

        FileInputStream fis = null;

        try {
            fis = openFileInput(FILE_NAME);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
           //get alvays null
            if (br.readLine() == null) {
                Log.d(TAG, "load: empty file ");
                fis.close();
                save();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void save() {

        FileOutputStream fos = null;

        try {
            fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
            int number = 1;
            String numberAsString = Integer.toString(number);
             fos.write(numberAsString.getBytes());
            Log.d(TAG, "save: numberAsString "+numberAsString);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
       // return;
    }
}

Thank you for answers!

Rohit Singh
  • 16,950
  • 7
  • 90
  • 88
vovkta1
  • 3
  • 2

2 Answers2

0

Use this Code Instead:-

public void SaveFile()
{
    try {
            //Getting Internal Storage
            File file = new File(Environment.getExternalStorageDirectory(),"");
            File dfile = new File(file+"/data.txt");
            FileWriter write = null;
            //if File Does Exists
            if (!dfile.exists()) {
                write = new FileWriter(file+"/data.txt");
                write.write("1");
                write.close();
            }
            else{
                FileReader read = new FileReader(dfile);
                BufferedReader br = new BufferedReader(read);
                String snum = br.readLine();
                if(snum!=null) {
                    //Converting Sring to Integer
                    int num = Integer.parseInt(snum);
                    num++;
                    write = new FileWriter(file+"/data.txt");
                    write.write(String.valueOf(num));
                    write.close();
                }
                else
                {                    
                    write = new FileWriter(file+"/data.txt");
                    write.write("1");
                    write.close();
                }
            }
        }catch (IOException ex){}
}

Add These permissions to Manifest File:-

<uses-permission android:name="READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="WRITE_EXTERNAL_STORAGE"></uses-permission>
GameChanger
  • 179
  • 11
  • I am very thankful for your comment :) I was tested your code on emulator and works fine, the numbers increasing but when I was testing this code-apk on my phone the code was not working and don't know why. I was use Toast to see what happens and first cursor go to **try** then go to **if (!dfile.exists())** and then jump to **catch** its maybe something more to do ? In manifest folder I have added `permission.WRITE_EXTERNAL_STORAGE` .... Thank you :) – vovkta1 Jan 19 '19 at 19:43
  • Have you added READ_EXTERNAL_STORAGE Permission in Manifest file? – GameChanger Jan 19 '19 at 20:03
  • Still don't working...I will be try to figure out to using Internal storage insted of External, maybe is there problem.. – vovkta1 Jan 19 '19 at 21:01
  • I was changing this `File file = new File(Environment.getExternalStorageDirectory(),"");` with this: `File file = new File(this.getFilesDir(), "");` and now working :)) – vovkta1 Jan 19 '19 at 22:01
0

Do you have to use a file? I would use Shared Preferences to store this value since it is just a primitive value.

Marty
  • 1