본문 바로가기

안드로이드 Android

[모바일프로그래밍] 11-3 외부 저장 공간(SD 카드) 사용

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="382dp"
        android:layout_height="301dp"
        android:layout_marginTop="48dp"
        android:background="@android:color/holo_blue_bright"
        android:ems="10"
        android:hint="memo sheet"
        android:inputType="textPersonName|text"
        android:singleLine="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.448"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:layout_marginTop="48dp"
        android:text="Read"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="48dp"
        android:layout_marginEnd="50dp"
        android:text="Save"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="68dp"
        android:text="Diary Example!"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

MainActivity.java

package com.example.myapplication;

import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity {

    EditText edtText;
    Button readButton, writeButton;
    int number = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED) == false) {
            Toast.makeText(this, "장착이 안 되어 있음", Toast.LENGTH_LONG).show();
        }

        edtText = (EditText) findViewById(R.id.editText);
        readButton = (Button) findViewById(R.id.button);
        writeButton = (Button) findViewById(R.id.button2);

        readButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    String filename = Environment.getExternalStorageDirectory().getAbsolutePath();
                    filename += "/DiaryKim" + number + ".txt";
                    InputStream is = new FileInputStream(filename);
                    byte[] buffer = new byte[is.available()];
                    is.read(buffer);
                    edtText.setText(new String(buffer));
                    is.close();
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
        });

        writeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    String filename = Environment.getExternalStorageDirectory().getAbsolutePath();
                    filename += "/DiaryKim" + number + ".txt";
                    OutputStream os = new FileOutputStream(filename);
                    os.write(edtText.getText().toString().getBytes());
                    os.close();
                    number++;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

 

2020/11/22 - [안드로이드 Android] - [모바일프로그래밍] 11-2 내부 저장 장소를 사용하는 경우

 

[모바일프로그래밍] 11-2 내부 저장 장소를 사용하는 경우

activity_main.xml MainActivity.java package com.example.myapplication; import android.content.Context; import android.os.Bundle; import android.view.View; impo..

comeths.tistory.com

원래대로라면 위 내용과 마찬가지로 Device File Explorer를 열고 sdcard 디렉토리에서 저장한 파일을 확인할 수 있다.

이유는 모르겠지만 파일이 생성되지 않았다..

Logcat을 확인해보니

E/Finsky:download_service: [135] mqd.a(11): read/write task failed.

라는 에러가 발생했는데 구글링해봐도 잘 모르겠다.

 

실제 기기에서 테스트해보고 싶은데 SD 카드가 없다ㅠㅠ