9 앱 개발 시작하시는 분들을 위해서/9 8 앱의 데이터를 저장하는 방법 3가지

기술노트

안드로이드로 앱을 개발할 때 값을 저장하는 방식은 크게 나누면 3가지가 있다. 환경 변수와 같은 값을 저장하는 것, 파일로 저장하는 것 그리고 데이터베이스를 이용하는 방법이 있다.

 1. 환경 변수 저장   

Preferences 데이터 저장

Preferences를 위한 데이터 저장 시 사용되는 자료구조는 Map 방식이다. 즉 키(key)-값(value) 한 쌍으로 이루어진 1~n개의 항목으로 구성된다. 키(key) 는 String 타입으로, 말 그대로 각 데이터에 접근할 수 있게 하는 유일한 구분자며, 값(Value)은 기본 자료형 (int, boolean, string 등) 기반의 데이터로 구성된다. 다음은 Map 데이터 구조의 한가지 예이다.


Preferences의 형태

안드로이드에서 Preferences는 ListView의 형태로 표현되며 쉬운 Preferences의 ㅁ구현을 위해 PreferenceActivity 클래스를 제공한다. PreferenceActivity 클래스는 XML 기반의 Preference 정의 문서를 통해 App 파일 저장소에 Preferences 파일을 생성하고 사용하는 방식으로 작동한다

 2. 파일 저장 

String FILENAME = "test.txt"; EditText edit;

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);


       edit = (EditText) findViewById(R.id.EditText01);
   Button readButton = (Button) findViewById(R.id.read);
   readButton.setOnClickListener(new View.OnClickListener() {
       public void onClick(View v) {
           try {
               FileInputStream fis = openFileInput(FILENAME);
               byte[] buffer = new byte[fis.available()];
               fis.read(buffer);
               edit.setText(new String(buffer));
               fis.close();
           } catch (IOException e) {
           }
       }
   });
   Button writeButton = (Button) findViewById(R.id.write);
   writeButton.setOnClickListener(new View.OnClickListener() {
       public void onClick(View v) {
           try {
               FileOutputStream fos = openFileOutput(FILENAME,
                       Context.MODE_PRIVATE);
               fos.write(edit.getText().toString().getBytes());
               fos.close();
           } catch (IOException e) {
           }
       }
   });
   

}

 3. DB 저장 

class DBHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "mycontacts.db";


   private static final int DATABASE_VERSION = 2;
   
   public DBHelper(Context context) {
       super(context, DATABASE_NAME, null, DATABASE_VERSION);
   }
   
   public void onCreate(SQLiteDatabase db) {
       db.execSQL("CREATE TABLE contacts ( _id INTEGER PRIMARY KEY" +
               " AUTOINCREMENT, name TEXT, tel TEXT);");
   }
   
   public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
       db.execSQL("DROP TABLE IF EXISTS contacts");
       onCreate(db);
   }
   

}

public void onCreate(Bundle savedInstanceState) {


       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       helper = new DBHelper(this);
       try {
           db = helper.getWritableDatabase();
       } catch (SQLiteException ex) {
           db = helper.getReadableDatabase();
       }
       edit_name = (EditText) findViewById(R.id.name);
       edit_tel = (EditText) findViewById(R.id.tel);
   }
   
   public void insert(View target) {
       String name = edit_name.getText().toString();
       String tel = edit_tel.getText().toString();
       db.execSQL("INSERT INTO contacts VALUES (null, '" + name + "', '" + tel
               + "');");
       Toast.makeText(getApplicationContext(), "성공적으로 추가되었음",
               Toast.LENGTH_SHORT).show();
       edit_name.setText("");
       edit_tel.setText("");
   }
   
   public void search(View target) {
       String name = edit_name.getText().toString();
       Cursor cursor;
       cursor = db.rawQuery("SELECT name, tel FROM contacts WHERE name='"
               + name + "';", null);
   
       while (cursor.moveToNext()) {
           String tel = cursor.getString(1);
           edit_tel.setText(tel);
       }
   }
   

개발자, 기술사, 삼성, 외국계 IT기업 20년차 기술노트 알렉이 직접 작성한 IT기업 기술 면접을 위한 CS + 면접 노하우 PDF <https://kmong.com/self-marketing/539751/LUA54VnQsP> 자주 나오는 CS 질문과 답변 그리고 100번 이상 면접관으로 참여하면서 느꼈던 면접자가 알아야 할 팁 13가지 포함

백엔드 개발자를 위한 클라우드 강의, AWS <https://inf.run/o1NX>

이제는 비전공자도, 일반이도 개발할 수 있다. ChatGPT를 이용한 누구나 앱개발 with 알렉 <https://inf.run/rpX4>

백엔드 직접 번역한 도서 <https://www.yes24.com/Product/Goods/122536127>

IT기술의 거의 모든 것을 다루는 기술노트with알렉 유투브 <https://www.youtube.com/c/%EA%B8%B0%EC%88%A0%EB%85%B8%ED%8A%B8with%EC%95%8C%EB%A0%89>