-
-
Save hmuskan/c62e43fe03e975515d5d25e2112c8118 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.muskanhussain.honeydolist; | |
import android.content.Context; | |
import android.support.v7.app.AppCompatActivity; | |
import android.os.Bundle; | |
import android.view.View; | |
import android.widget.Button; | |
import android.widget.EditText; | |
import java.io.BufferedReader; | |
import java.io.FileNotFoundException; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.io.OutputStreamWriter; | |
public class MainActivity extends AppCompatActivity { | |
private EditText todoText; | |
private Button saveButton; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
todoText = findViewById(R.id.todoText); | |
saveButton = findViewById(R.id.saveButton); | |
saveButton.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
if(!todoText.getText().toString().equals("")) | |
{ | |
String message = todoText.getText().toString(); | |
writeToFile(message); | |
Toast.makeText(MainActivity.this, "Saved!", Toast.LENGTH_LONG).show(); | |
} | |
} | |
}); | |
try { | |
if(readFromFile() != null) | |
{ | |
todoText.setText(readFromFile()); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
private void writeToFile(String message) | |
{ | |
try { | |
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("todolist.txt", | |
Context.MODE_PRIVATE)); | |
outputStreamWriter.write(message); | |
outputStreamWriter.close(); | |
} catch(FileNotFoundException e) | |
{ | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
private String readFromFile() throws IOException { | |
String result = ""; | |
InputStream inputStream = openFileInput("todolist.txt"); | |
if(inputStream != null) | |
{ | |
InputStreamReader inputStreamReader = new InputStreamReader(inputStream); | |
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); | |
String temp = ""; | |
StringBuilder stringBuilder = new StringBuilder(); | |
while((temp = bufferedReader.readLine()) != null) | |
{ | |
stringBuilder.append(temp); | |
stringBuilder.append("\n"); | |
} | |
inputStream.close(); | |
result = stringBuilder.toString(); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment