본문 바로가기
Android Studio

[Android Studio] 첫 안드로이드 앱 개발 시작해보기 - LIstView, SharedPreferences (6)

by jisayDeveloper 2023. 11. 1.
728x90
반응형

ListView

ListView는 스크롤 가능한 목록 형태의 데이터를 화면에 표시하는 데 사용합니다. 여러 항목을 수직으로 스크롤하며 볼 수 있고 다양한 방식으로 사용자와 상호 작용 가능합니다.

 

이제 ListView를 써보겠습니다. activity_main.xml을 보면

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

    <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />

</LinearLayout>

<ListView>를 만들고 id를 부여합니다.

 

이제 MainActivity를 보겠습니다.

package com.example.listexam;

import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView list;

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

        list = (ListView) findViewById(R.id.list);

        List<String> data = new ArrayList<>();

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data);

        list.setAdapter(adapter);

        data.add("jisay");
        data.add("developer");
        data.add("abc");

        adapter.notifyDataSetChanged();

    }
}

LIst 객체를 만들고 ArrayAdapter도 만드는 데 ListView는 이 Adapter가 꼭 필요합니다.

 

Adapter는 데이터 소스 간의 중간 역할을 하며, 데이터를 가져와 각 항목에 대한 뷰를 생성하고 ListView에 표시하는 작업을 담당합니다.

 

list에 adapter를 연결하고 data에 ListView에 출력할 데이터를 추가합니다.

 

notifyDataSetChanged() 메서드를 꼭 호출해야하는데 호출하지 않으면, 데이터가 변경되어도 ListView가 업데이트 되지 않습니다.

이렇게 ListView가 보이는걸 확인할 수 있습니다.


SharedPreferences

SharedPreferences는 간단한 데이털르 저장하고 관리하기 위한 API입니다. 앱이 종료되어도 데이터가 유지되며 앱 간에 데이터 공유할 수 있습니다. 주로 사용자 기본정보, 앱 상태 정보, 프로필 정보 등을 저장하는데 사용합니다.

 

그럼 SharedPreferences 예제를 보겠습니다. activity_main.xml을 보면

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

    <EditText
            android:id="@+id/save"
            android:layout_width="100dp"
            android:layout_height="wrap_content"/>

</LinearLayout>

<EditText>를 만들어서 입력받은 데이터를 앱이 꺼져도 데이터가 남아있게 하겠습니다.

package com.example.listexam;

import android.content.SharedPreferences;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;


public class MainActivity extends AppCompatActivity {

    EditText save;

    String shared = "file";

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

        save = (EditText) findViewById(R.id.save);

        SharedPreferences sharedPref = getSharedPreferences(shared,0);
        String value = sharedPref.getString("js","");
        save.setText(value);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        SharedPreferences sharedPreferences = getSharedPreferences(shared, 0);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        String value = save.getText().toString();
        editor.putString("js", value);
        editor.commit();
    }
}

shared를 초기화 한 이유는 SharedPreferences의 데이터를 저장할 xml 파일 이름으로 사용합니다.

 

그리고 SharedPreferences 객체를 만드는데 파라미터에 shared와 0이 들어가는데 0은 모드를 말하며 MODE_PRIVATE을 말합니다. 이건 현재 앱에서만 SharedPreferences를 쓰겠단 의미입니다.

 

그 다음 onDestroy 메서드를 만드는데 이건 앱이 종료될 때 실행되는 메서드입니다.

EditText에 저장하기 위해서 editor를 사용하고 commit()을 통해 완료됩니다.

 

그리고 다시 onCreate() 를 보면 String value에 SharedPreferences 에 저장된 "js"를 가져와서 setText해주면 앱이 실행할 때 출력하게 됩니다.

 

이렇게 처음 입력한 데이터가 앱이 꺼지고 다시 켜도 jisay가 남아있는 걸 볼 수 있습니다.

728x90
반응형