Write and Read Data from SD Card in Android Studio - Tutorial
Write and Read Data from SD Card in Android Studio
1. Create new Project with Basic Settings
it will take some time...
2. Drag and Drop Text-Plain Text and Buttons-Button from Design view
- align the units by attaching circles to corner as shown in vdo
3. Make Changes in XMl File to adjust
- size - keep same for all
- id ---- button1 , button2 , button3... check the parents id too.
- text - i left blank text in EditText
4. Give SD Card Permission in Manifest.xml !! Important !!
5. Write the java code inside
app/java/yourapp/MainActivity.java -- onCreate Function
Write the code below the super.onCreate call Important!!!!
6. To Auto Import Libraries use Altr + Enter
make sure all reds are gone!
7. Build , click on the hammer on top right corner
no errors
8. Connect your phone with file storage on and USB debugging enabled
9. You will see your mobile name in run button, Run
CODE Tutorial
1. Call the text box and button by id using findViewById(R.id.*****)
- **** is id you defined in XML file
2. Assign OnClickListner to each button with new View.OnClickListner
3. Importan notes:
- File is used to access file
- FileOutputStream for writing file
- FileInputStream and BufferedReader for reading the file
- Toast is just to notify ( can we ignore if not remebering )
after installation
// Give SD Card Permission to App before RUNNING!!!!! important
Java Code:
final EditText text = findViewById(R.id.editText);
Button write = findViewById(R.id.button1);
Button read = findViewById(R.id.button2);
Button clear = findViewById(R.id.button3);
write.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String data = text.getText().toString();
try{
File file = new File("/sdcard/myfile.txt");
file.createNewFile();
FileOutputStream fout = new FileOutputStream(file , true);
fout.write( data.getBytes() );
fout.close();
Toast.makeText(getBaseContext() , "DATA IS WRITTEN", Toast.LENGTH_LONG ).show();
}
catch ( Exception e ){
Toast.makeText(getBaseContext() , e.getMessage() , Toast.LENGTH_LONG).show();
}
}
});
read.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String data , buff = "";
try{
File file = new File("/sdcard/myfile.txt");
FileInputStream fin = new FileInputStream(file);
BufferedReader br = new BufferedReader( new InputStreamReader(fin));
while ( ( data = br.readLine() ) != null ){
buff += data;
}
text.setText(buff);
br.close();
fin.close();
Toast.makeText(getBaseContext() , "DATA IS READ", Toast.LENGTH_LONG ).show();
}
catch ( Exception e ){
Toast.makeText(getBaseContext() , e.getMessage() , Toast.LENGTH_LONG).show();
}
}
});
clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
text.setText("");
}
});
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Write and Read Data from SD Card in Android Studio - Tutorial», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.