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):
- Create file if not exist
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!