I have implemented a kind of cache in which when app is not connected with internet I write the data on file, but once it gets internet and send all the data to server, I want to remove all the content from the file. I open that file in append mode and it seems like it is not removing content from file. Here is my code....
if (!(isNetworkAvailable())) {
try {
firstConnect = true;
outputStream = ctx.openFileOutput("cache.txt", Context.MODE_APPEND);
outputStream.write(new String().getBytes());
outputStream.write(data.getBytes());
outputStream.write("new_data".getBytes());
outputStream.flush();
outputStream.close();
Log.d(TAG, "OCIUFNF");
} catch (IOException exception) {
exception.printStackTrace();
}
This code is executed everytime I collect data and there is no connectivity.
Here is my broadcast reciever that triggers on connectivity change
class NetworkReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
String action = intent.getAction();
connectionManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo net = connectionManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
sendFileData();
}
}
}
protected void sendFileData() {
StringBuilder total = new StringBuilder();
if(firstConnect) {
try {
FileInputStream inputStream = service.openFileInput("cache.txt");
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
r.close();
inputStream.close();
} catch (IOException exception) {
exception.printStackTrace();
}
String[] parts = total.toString().split("new_data");
for (int i = 1; i < parts.length; i++) {
if(!(parts[i].toString().equals(parts[i-1]))) {
Intent cacheIntent = new Intent(ctx, serviceRequest.class);
cacheIntent.putExtra("Data", parts[i]);
ctx.startService(cacheIntent);
}
}
try {
FileOutputStream writer = new FileOutputStream("cache.txt");
writer.write(new String().getBytes());
writer.close();
Log.d(TAG, "ddjdbdjhd");
//outputStream.write(new String().getBytes());
}catch (IOException exception){
exception.printStackTrace();
}
firstConnect = false;
}
}
but it is not working, any idea where I am doing wrong or good solution thanks