1.   비트 연산자

  • 피연산자를 비트단위로 논리 연산
  • 비트 : 0과 1을 저장 → 1바이트 = 8비트
  • 10진수 / 16진수 / 2진수 변환 참조 (https://reversecore.com/96)
| (OR연산자)
피연산자 중 한 쪽의 값이 1이면 1을 결과로 얻는다. 그 외 0
& (AND연산자)
피연산자 양쪽이 모두 1이어야만 1을 결과로 얻는다. 그 외 0
^ (XOR연산자)
피연산자 값이 서로 다를 때만 1을 결과로 얻는다. 같을때 0
public class Exam011 {

	public static void main(String[] args) {
		
        /* 비트 연산자
         * 10진수를 2진수로 변경해서 연산하고, 그 후에 10진수로 변환
         */
		
		int a = 15; // 1111
		int b = 5; // 0101
		
		System.out.println(a | b); // 1111 -> 15
		System.out.println(a & b ); // 0101 -> 5
		System.out.println(a ^ b ); // 1010 -> 10
		
		System.out.println(a>>2); // 1111 -> 0011 -> 3
		System.out.println(b<<4); // 0101 -> 01010000 -> 80
	}

}

 


2.   제어문 - 조건문

💌  ' 제어문(control statement) '  프로그램의 흐름(flow)을 바꾸는 역할을 하는 문장들

1)  if 문 ; 조건에 따라 다른 문장이 실행

if (조건식) {
    // 조건식이 참(true)일 때 수행될 문장들을 적는다.
}
 
  • 조건식의 결과는 true 아니면 false
  • 연산자들은 조건문에 자주 쓰임.
  • 블럭 {} : 여러 문장을 하나의 단위로 묶을 수 있음

💡  블럭 내의 문장들은 탭(tab)으로 들여쓰기(indentation)를 해서 블럭 안에 속한 문장이라는 것을 알기 쉽게 해주는 것이 좋다

public class Exam015 {
	public static void main(String[] args) {
		
        int a = 3;
        
        if (a >= 3) { // if (조건식) 조건식 : 결과값이 boolean
        	// 조건식이 참일 때 실행
            System.out.println("a는 3보다 큽니다");
        } // if 구문의 끝
        
        // 조건식과 상관없이 무조건 실행
        System.out.println("검사가 끝났습니다.");

	}
}

 


2) if - else 문

 

'else' 그 밖의 다른 이라는 뜻이므로 조건식의 결과가 참이 아닐 때, 즉 거짓일 때 else 블럭의 문장을 수행하라는 뜻

실행할 명령문이 간단하면 삼항연산자로 변경 가능

public static void main(String[] args) {
		
    int age = 15;
		
	if (age > 19) {
	    System.out.println("성인입니다");
		System.out.println("성인요금이 적용됩니다");
	} else { // 위의 조건이 거짓일 때만 실행
	    System.out.println("청소년입니다.");
		System.out.println("청소년요금이 적용됩니다.");
	}
	System.out.println("결제를 진행해 주세요.");
}

 

삼항연산자 적용시 
public static void main(String[] args) {
    /* Exam016을 삼항 연산자를 사용하는 방식으로 변경 
	 * if else 문이고, 실행할 명령문이 간단한 경우 삼항연산자로 변경 가능 */
		
     int age = 15;
		
	 System.out.println(age > 19 ? "성인입니다. \n성인요금이 적용됩니다."
	     : "청소년입니다. \n청소년 요금이 적용됩니다.");
	 System.out.println("결제를 진행해 주세요.");
}


3) if - else if 문

 

  👾  처리해야 할 경우의 수가 셋 이상인 경우 한 문장에 여러 개의 조건식을 쓸 수 있음

  👾  마지막에는 else 블럭으로 끝나며, 위의 어느 조건식도 만족하지 않을 때 수행될 문장들을 적는다.

 

처리 순서 
  • 결과가 참인 조건식을 만날 때까지 첫 번째 조건식부터 순서대로 평가한다.
  • 참인 조건식을 만나면, 해당 블럭 {}의 문장들을 수행한다.
  • if-else if문 전체를 빠져나온다.
public static void main(String[] args) {
    /* 놀이공원의 요금 나이 기준
	* 성인 : 20세 이상
	  청소년 : 14 ~ 19
	  어린이 : 9 ~13
	  유아 : 0 ~8 */
		
    int age;
	   
	Scanner scanner = new Scanner(System.in);
	System.out.println("나이를 입력해주세요. >>");
	age = scanner.nextInt();
	   
	// 조건이 거짓이면 다음 조건으로 넘어감.
	// 조건이 참이 되면 다음 조건을 검사하지 않음.
		
	if (age > 19) { // 20 ~
	    System.out.println("성인입니다.");
		System.out.println("성인요금이 적용됩니다.");
	}
	else if (age > 13) { // 14 ~ 19
		System.out.println("청소년입니다.");
		System.out.println("청소년요금이 적용됩니다.");
	}
	else if (age > 8) { // 9 ~13
		System.out.println("어린이입니다.");
		System.out.println("어린이요금이 적용됩니다.");
	}
	else { // 0~ 8
		System.out.println("유아입니다.");
		System.out.println("유아요금이 적용됩니다.");
	}
		
	System.out.println("결제를 진행해주세요.");
	scanner.close();
}

오름차순으로 나이 적용시
public static void main(String[] args) {
		
    Scanner scanner = new Scanner(System.in);
	int age;
		
	System.out.println("나이를 입력해주세요.");
    age = scanner.nextInt();
        
    /* 놀이공원의 요금 나이 기준
     * 성인 : 20세 이상
     * 청소년 : 14 ~ 19
     * 어린이 : 9 ~ 13
     * 유아 : 0 ~ 8
     */
        
    // 첫번째 조건에 해당 되지 않으면 다음 조건으로 넘어감.
    // 그렇기 때문에 두번째 조건에서 첫번째 조건과 겹치는 범위는 적지 않아도 됨.
        
    if (age <= 8) { // 0~8
        System.out.println("유아입니다.");
        System.out.println("유아요금이 적용됩니다.");
    }
    else if (age <= 13) { // 9 ~ 13
        System.out.println("어린이입니다.");
        System.out.println("어린이요금이 적용됩니다.");
    }
    else if (age <= 19) { // 14 ~ 19
        System.out.println("청소년입니다.");
        System.out.println("청소년요금이 적용됩니다.");
    }
    else { // 20 ~
        System.out.println("성인입니다.");
        System.out.println("성인요금이 적용됩니다.");
    }
        
    System.out.println("결제를 진행해주세요."); 
        
    // 삼항 연산자를 중첩해서 사용하면 동일한 기능 가능.
    System.out.println(age <= 8 ? "유아입니다. \n유아요금이 적용됩니다." :
        age <= 13 ? "어린이입니다. \n어린이요금이 적용됩니다." :
        age <= 19 ? "청소년입니다. \n청소년요금이 적용됩니다." :
         "성인입니다. \n성인요금이 적용됩니다.");
    
    scanner.close();
}
 
 
 

4) 중첩 if문

  👾  if 문 블럭 내에 또 다른 if문을 포함시키는 것

  👾  내부 if 문은 외부의 if 문보다 안쪽으로 들여쓰기를 해서 두 if 문의 범위가 명확히 구분될 수 있도록 작성

public static void main(String[] args) {
    /* 중첩 if문 : if문 안에 if가 있는 경우
		 
	아이디, 비밀번호를 입력받아서 로그인 처리.
	id : java, pw : 1234
	아이디가 맞는 경우에는 비밀번호를 입력 받음.
	아이디가 틀린 경우에는 에러메시지 출력.
	*/
		
	String id, password;
	Scanner scanner = new Scanner(System.in);
	System.out.println("아이디를 입력해 주세요:");
	id = scanner.nextLine();
		 
	if (id.equals("java")) { // 아이디가 맞는 경우 비밀번호를 입력받음
	    System.out.println("아이디 일치");
		System.out.println("비밀번호를 입력해 주세요 : ");
		password = scanner.nextLine();
		if (password.equals("1234")) {
		    System.out.println("비밀번호 일치");
			System.out.println("로그인 성공");
		} else {
			System.out.println("비밀번호 불일치");
		}
	} else {
	    System.out.println("아이디 불일치");
	}
	scanner.close();
}
 

(출처 ; 학원강의 및 java의 정석 3rd)


📌  구글 플레이 서비스의 Google Maps API를 사용하면 구글 지도 데이터를 기반으로 앱에 지도를 추가할 수 있음

      -  구글 지도는 Google Maps Platform 서비스 중의 하나이며, 교통정보 기반의 경로 찾기와 장소 정보, 검색 등의 기능을 제공.
      -  국내에서는 구글 지도의 경로찾기 메뉴중 버스만 사용할 수 있음.

 

1.  구글 지도 시작하기

 

 

안드로이드 스튜디오는 구글 지도를 쉽게 사용할 수 있도록 프로젝트 생성 시 프로젝트의 종류를 선택하는 메뉴에서 Google Maps Activity를 제공

 

  ➡️  MainActivity 대신 MapsActivity가 생성됨

 

 

 

 

 

 

 

Google Maps API 키 설정


구글 지도를 포함한 구글 플레이 서비스에 엑세스하려면 구글 플레이 서비스의 API 키가 필요
이전에는 google_maps_api.xml 파일이 자동 생성되고, 해당 파일에 API키를 입력했으나, 범블비와 칩멍크 버전 부터는 AndroidManifest.xml에 API키를 입력하도록 변경이 됨

<!--
    TODO: Before you run your application, you need a Google Maps API key.

    To get one, follow the directions here:

    https://developers.google.com/maps/documentation/android-sdk/get-api-key

    Once you have your API key (it starts with "AIza"), define a new property in your
    project's local.properties file (e.g. MAPS_API_KEY=Aiza...), and replace the
    "YOUR_API_KEY" string in this file with "${MAPS_API_KEY}".
-->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="YOUR_API_KEY" />

 

 

키를 입력 후에 안드로이드 스튜디오에서 앱을 빌드하고 시작하면, 시드니에 마커가 표시된 지도를 표시

 

  📍 지도가 안 뜨면 구글 cloud 접속 하여 API key 수정에서 패키지를 추가해주면 됨 !  ▶️ 패키지명은 무조건 소문자 !!

 

 


2.  구글 지도 코드 살펴보기

activity_maps.xml의 SupportMapFragment

 

프로젝트를 생성하면 activity_maps.xml 파일이 자동 생성됨. 코드를 보면 android:name에 "com.google.android.gms.maps.SupportMapFragment"가 설정되어 있음.

Google Maps API는 SupportMapFragment에 구글 지도를 표시.

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity" />

 

 

MapsActivity.kt의 SupportMapFragment.getMapAsync
 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMapsBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }

 

MapsActivity.kt 파일을 열면 onCreate() 메서드 블록 안에서는 supportFragmentManager의 findFragmentById() 메서드로 id가 map인 SupportMapFragment를 찾은 후 getMapAsync()를 호출해서 안드로이드에 구글 지도를 그려달라는 요청을 함.

 

MapsActivity.kt의 OnMapReadyCallback

 

class MapsActivity : AppCompatActivity(), OnMapReadyCallback { }

 

안드로이드는 구글 지도가 준비되면 OnMapReadyCallback 인터페이스의 onMapReady() 메서드를 호출하면서 파라미터로 준비된 GoogleMap을 전달해 줌.

override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

        // Add a marker in Sydney and move the camera
        val sydney = LatLng(-34.0, 151.0)
        mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
    }

 

메서드 안에서 미리 선언된 mMap 프로퍼티에 GoogleMap을 저장해두면 액티비티 전체에서 맵을 사용할 수 있음.
구글에서 기본으로 제공하는 시드니의 좌표 코드가 있음.

 

* API Level 12 이하 버전에서의 호환성이 필요없다면 SupportMapFragment 대신 MapFragment를 사용할 수 있음.
* 스마트폰에 구글 플레이 서비스가 설치되어 있지 않으면 사용자가 구글 플레이 서비스를 설치할 때까지 onMapReady() 메서드가 호출되지 않음.

 


3.  카메라와 지도 뷰

구글 지도에서는 카메라를 통해 현재 화면의 지도 뷰를 변경할 수 있음.
  ✓  지도 뷰는 평면에서 아래를 내려다 보면서 모델링 되며 카메라의 포지션은 위도/경도, 방위, 기울기 및 확대/축소 속성으로 지정
  ✓  카메라의 위치는 CameraPosition 클래스에 각종 옵션을 사용해서 조절할 수 있음

CameraPosition.Builder().옵션1.옵션2.build()

Target


    카메라의 목표 지점 Target은 지도 중심의 위치이며 위도 및 경도 좌표로 지정

CameraPosition.Builder().target(LatLng(-34.0, 151.0))

 


Zoom

 

  ✓  카메라의 줌 Zoom (확대/축소) 레벨에 따라 지도의 배율이 결정. 줌 레벨이 높을 수록 더 자세한 지도를 볼 수 있는 반면, 줌 레벨이 작을수록 더 넓은 지도를 볼 수 있음.

CameraPosition.Builder().zoom(15.5f)

 

 

📍  줌 레벨이 0인 지도의 배율은 전 세계의 너비가 약 256dp가 되며 레벨의 범위는 다음과 같음

레벨 설명
1.0 세계
5.0 대륙
10.0 도시
15.0 거리
20.0 건물

 


Bearing


  ✓  카메라의 베어링 Bearing은 지도의 수직선이 북쪽을 기준으로 시계 방향 단위로 측정되는 방향.

CameraPosition.Builder().bearing(300f)

Tilt


  ✓  카메라의 기울기 Tilt는 지도의 중앙 위치와 지구 표면 사이의 원호에서 카메라 위치를 지정
  ✓  기울기로 시야각을 변경하면 멀리 떨어진 지형이 더 작게 나타나고 주변 지형이 더 켜져 맵이 원근으로 나타남

CameraPosition.Builder().tilt(50f)

 


4.  소스 코드에서 카메라 이동하기

옵션을 이용해서 CameraPosition 객체를 생성하고 moveCamera() 메서드로 카메라의 위치를 이동시켜 지도을 변경할 수 있음.
  ➡️  MapsActivity.kt 파일의 onMapReady() 메서드 안에 작성.

CameraPosition.Builder 객체로 카메라 포지션을 설정


  📍  build() 메서드를 호출해서 CameraPosition 객체를 생성

val cameraPosition = CameraPosition.Builder()
    .target(LATLNG)
    .zoom(15.0f)
    .build()

 

CameraUpdateFactory.newCameraPosition() 메서드에 CameraPosition 객체를 전달하면 카메라 포지션에 지도에서 사용할 수 있는 카메라 정보가 생성
val cameraUpdate =
    CameraUpdateFactory.newCameraPosition(cameraPosition)

 

변경된 카메라 정보를 GoogleMap의 () 메서드에 전달하면 카메라 포지션을기준으로 지도의 위치, 배율, 기울기 등이 변경되어 표시
mMap.moveCamera(cameraUpdate)

 


5.  마커

마커 Marker는 지도에 위치를 표시. 아이콘의 색상, 이미지, 위치를 변경할 수 있으며 대화식으로 설계되었기 때문에 마커를 클릭하면 정보창을 띄우거나 클릭리스너처럼 클릭에 대한 코드 처리를 할 수 있음.

 

마커 표시하기

 

  1. mMap = googleMap 코드 아래에 특정 장소의 위도와 경도 좌표값으로 LatLng 객체를 생성

val LATLNG = LatLng(35.8715, 128.6017)

 

  2.  마커를 추가하려면 마커의 옵션을 정의한 MarkerOptions 객체가 필요.

        MarkerOptions 객체를 생성하고 머커의 좌표와 제목을 설정.

val markerOptions = MarkerOptions()
    .position(LATLNG)
    .title("Marker")

 

  3. GoogleMap 객체의 addMarker() 메서드에 MarkerOptions를 전달하면 구글 지도에 마커가 추가.

mMap.addMarker(markerOptions)

 

  4. 카메라를 마커의 좌표로 이동하고 줌을 거리 레벨로 확대

val cameraPosition = CameraPosition.Builder()
    .target(LATLNG)
    .zoom(15.0f)
    .build()

val cameraUpdate =
    CameraUpdateFactory.newCameraPosition(cameraPosition)
    mMap.moveCamera(cameraUpdate)

 

  5. MarkerOptions 객체의 title(), snippet() 메서드로 정보 창을 수정할 수 있으며 마커를 클릭하면 정보창이 표시

val markerOptions = MarkerOptions()
    .position(LATLNG)
    .title("Daegu City Hall")
    .snippet("35.8715, 128.6017")

 

 

마커 아이콘 변경하기

 

마커 아이콘은 기본적으로 제공되는 아이콘뿐만 아니라 비트맵 이미지로 변경할수 있음.
PNG 이미지 파일을 프로젝트에 추가하고 비트맵으로 변환해서 아이콘으로 변경.

 

  1. drawable 디렉토리에 마커 아이콘으로 적용할 PNG 이미지 파일을 추가

  2. onMapReady() 안에 아래의 코드를 추가

val bitmapDrawable: BitmapDrawable

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    bitmapDrawable = getDrawable(R.drawable.marker) as BitmapDrawable
} else {
    bitmapDrawable = resources.getDrawable(R.drawable.marker) as BitmapDrawable
}

 

  3. BitmapDescriptorFactory.fromBitmap() 메서드에 BitmapDrawable의 비트맵 객체를 전달하는 마커 아이콘을 위한
BitmapDescriptor 객체를 생성하고 import

var discriptor =
    BitmapDescriptorFactory.fromBitmap(bitmapDrawable.bitmap)

 

  4. MarkerOptions 객체의 icon() 메서드를 호출해서 BitmapDescriptor 객체의 아이콘을 마커에 적용하도록 수정

val markerOptions = MarkerOptions()
    .position(LATLNG)
    .icon(discriptor)
mMap.addMarker(markerOptions)

 

  * 아이콘의 크기가 클 경우 Bitmap.createScaledBitmap() 메서드를 호출해서 크기를 줄인 비트맵 객체를 반환받아야 함

 


6.  현재 위치 검색하기

스마트폰처럼 모바일 환경에서는 사용자가 위치를 이동하고 그 위치를 기반으로하는 서비스를 제공할 수 있음.
  ✓  앱에서 스마트폰의 현재 위치를 검색하려면 위치 권한이 필요
  ✓  안드로이드 플랫폼은 현재 위치를 검색하는 FusedLocationProviderClinet API를 제공
        ➡️  FusedLocationProviderClinet API는 GPS Global Positioning System 신호 및 와이파이와 통신사 네트워크 위치를 결합해서 최소한의 배터리 사용량으로 빠르고 정확하게 위치를 검색

 

Google Play Service 의존성 추가하기


  FusedLocationProviderClinet API를 사용하기 위해서 build.gradle 파일에 구글 플레이 서비스의 Loacation 라이브러리 의존성을 추가. Location 라이브러리는 Maps 라이브러리와 버전이 같아야 함. Location 라이브러리와 같아지도록 Maps의 라이브러리 버전을 맞춰줌.

implementation 'com.google.android.gms:play-services-location:18.2.0'
implementation 'com.google.android.gms:play-services-maps:18.2.0'

 

권한을 명세하고 요청/ 처리하기

 

  스마트폰의 위치 기능에 접근하기 위해 AndroidManifest.xml 파일에 위치 권한을 선언. 위치 권한은 두 가지가 있으며 기능은 다음과 같음.

<!-- 도시 블록 내에서 정확한 위치 (네트워크 위치) -->
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<!-- 정확한 위치 확보 (네트워크 위치 + GPS 위치) -->
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"/>

 

  MapsActivity에 OnMapReadyCallback 인터페이스를 상속 받음.

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {}

 

  권한 처리를 위해서 onCreate() 메서드 위에 런처를 선언. 여기서는 한 번에 2개의 권한에 대한 승인을 요청하기 때문에 Contract로 RequestMultiplePermissions()를 사용해야 함. 따라서 런처의 제네릭은 문자열 배열인 <Array<String>>이 됨

lateinit var locationPermission: ActivityResultLauncher<Array<String>>

 

  onCreate() 메서드 아래에 빈 startProcess() 메서드를 미리 만들어 둠. 

fun startProcess() {
    // 승인 후 실행할 코드를 입력
}

 

  onCreate() 메서드 안에 런처를 생성하는 코드를 작성하고 앞에서 선언해 둔 변수에 저장.

locationPermission =
    registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { 
        results -> if (results.all{ it.value }) {
                       startProcess()
                   } else {
                       Toast.makeText(this, "권한 승인이 필요합니다.",
                       Toast.LENGTH_LONG).show()
                   }
    }

 

  바로 아래줄에 런처를 실행해서 권한 승인을 요청. 2개의 권한을 파라미터에 전달해야되기 때문에 arrayOf()를 사용해서 권한 2개를 같이 launch()의 파라미터로 입력.

locationPermission.launch(arrayOf(
    Manifest.permission.ACCESS_COARSE_LOCATION,
    Manifest.permission.ACCESS_FINE_LOCATION
))

 

  위치 권한이 승인되면 startProcess() 메서드에서 구글 지도를 준비하는 작업을 진행하도록 코드를 수정. onCreate()에 작성되어 있는 val mapFragment 로 시작하는 세 줄을 잘라내기 한 후 startProcess() 메서드 안에 붙여넣기 하면 됨.

fun startProcess() {
    // 승인 후 실행할 코드를 입력
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    val mapFragment = supportFragmentManager
        .findFragmentById(R.id.map) as SupportMapFragment
         mapFragment.getMapAsync(this)
}

 

  이제 권한이 모두 승인되고 맵이 준비되면 onMapReady() 메서드가 정상적으로 호출.

 


현재 위치 검색하기

 

 1. onCreate() 위에 onMapReady() 위치를 처리하기 위한 변수 2개를 선언
     ✓  fusedLocationClient는 위치값을 사용하기 위해서 필요하고, locationCallback은 위칫값 요청에 대한 갱신 정보를 받는 데 필요

private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var locationCallback: LocationCallback

 

 2. onMapReady() 안의 시드니 좌표 코드를 삭제한 다음, 위치 검색 클라이언트를 생성하는 코드를 추가하고 updateLocation() 메서드를 호출

override fun onMapReady(googleMap: GoogleMap) {
    mMap = googleMap
    fusedLocationClient =
        LocationServices.getFusedLocationProviderClient(this)
    updateLocation()
}

 

 3. updateLocation() 메서드를 작성.

  • 위치 정보를 요청할 정확도와 주기를 설정할 locationRequest를 먼저 생성하고, 해당 주기마다 반환받을 locationCallback을 생성
  • onMapReady에서 생성한 위치 검색 클라이언트의 requestLocationUpdates()에 앞에서 생성한 2개와 루퍼 정보를 넘겨줌
  • 이제 1초(1,000밀리초)에 한 번씩 변화된 위치정보가 LocationCallback의 onLocationResult()로 전달이 됨.
  • onLocationResult()는 반환받은 정보에서 위치 정보를 setLastLoation()으로 전달.
  • fusedLocationClient.requestLocationUpdates 코드는 권한 처리가 필요한데 현재 코드에서는 확인할 수 없음.
  • 따라서 메서드 상단에 해당 코드를 체크하지 않아도 된다는 의미로 @SuppressLint("MissingPermission") 애너테이션을 달아줌.
@SuppressLint("MissingPermission")
fun updateLocation() {
    val locationRequest = LocationRequest.create()
    locationRequest.run {
        priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        interval = 1000
    }

locationCallback = object: LocationCallback() {
    override fun onLocationResult(locationResult: LocationResult?) {
        locationResult?.let {
            for ((i, location) in it.locations.withIndex()) {
                Log.d("Location", "$i ${location.latitude}, ${location.longitude}")
                setLastLoation(location)
            }
        }
    }
}

fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper())

 

 

4. updateLocation() 메서드 아래에 위치 정보를 받아서 마커를 그리고 화면을 이동하는 setLastLoation()을 작성

fun setLastLoation(lastLocatin: Location) { }

 

5. 전달받은 위치 정보로 좌표를 생성하고 해당 좌표로 마커를 생성

fun setLastLoation(lastLocatin: Location) {
    val LATLNG = LatLng(lastLocatin.latitude, lastLocatin.longitude)
    val markerOptions =
        MarkerOptions().position(LATLNG).title("Here!")
}

 

6. 카메라 위치를 현재 위치로 세팅하고 마커에 함께 지도에 반영.

    ✓  마커를 지도에 반영하기 전에 mMap.clear()를 호출해서 이전에 그려진 마커가있으면 지움

fun setLastLoation(lastLocatin: Location) {
    val LATLNG = LatLng(lastLocatin.latitude, lastLocatin.longitude)
    val markerOptions =
        MarkerOptions().position(LATLNG).title("Here!")

    val cameraPosition =
        CameraPosition.Builder().target(LATLNG).zoom(15.0f).build() 
    mMap.clear()
    mMap.addMarker(markerOptions)

    mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)
}

 

 

 

 

[ 내용 참고 : IT 학원 강의 ]

 


1.  SQLite 프로그래밍

안드로이드에서 사용하는 SQLite는 관계형 데이터베이스

 

1) 안드로이드 앱 개발을 위한 SQLite 동작 방식

 

 

  🐰  안드로이드 앱에서 SQLite를 사용할 때는 일반적으로 SQLiteOpenHelper 클래스, SQLiteDatabase 클래스, Cursor 인터페이스를 이용

 

 

 

 

 

  • SQLiteOpenHelper 클래스를 상속받아 새로운 클래스를 생성
  • 생성한 클래스에는 데이터베이스 파일과 테이블을 생성하는 내용을 코딩 
  • SQLiteOpenHelper 클래스의 getWritableDatabase()를 사용하면 SQLiteDatabase를 반환받고execSQL() 또는 rawQuery() 등으로 SQL문을 실행 
  • 특히 SELECT문은 Cursor 인터페이스를 반환받은 후에 반복해서 테이블의 행 데이터에 접근

각 클래스에서 자주 사용되는 메서드
클래스 또는 인터페이스 메서드 주요 용도
SQLiteOpenHelper 클래스 생성자 DB 생성
  onCreate() 테이블 생성
  onUpgrade() 테이블 삭제 후 다시 생성
  getReadableDatabase() 읽기 전용 DB 열기. SQLiteDatabase 반환
  getWritableDatabase() 읽고 쓰기용 DB 열기. SQLiteDatabase 반환
SQLiteDatabase 클래스 execSQL() SQL문 (insert / update / delete) 실행
  close() DB 닫기
  query(), rawQuery() select 실행 후 커서 반환
Cursor 인터페이스 moveToFirst() 커서의 첫 행으로 이동
  moveToLast() 커서의 마지막 행으로 이동
  moveToNext() 현재 커서의 다음 행으로 이동

 


2.  가수 그룹의 이름과 인원을 데이터베이스에 입력하고 조회하는 응용 프로그램 작성

xml 코드

 

바깥 리니어 레이아웃 안에 리니어레이아웃(수평) 4개를 만들고 다음과 같이 화면 구성.
리니어 레이아웃 1 ~ 3은 layout_weight를 1로, 리니어 레이아웃 4는 8로 설정.

  • 리니어 레이아웃 1 : 텍스트뷰 1개, 에디트 텍스트 1개 (editName)
  • 리니어 레이아웃 2 : 텍스트뷰 1개, 에디트 텍스트 1개 (editNumber)
  • 리니어 레이아웃 3 : 버튼 3개 (btnInit, btnInsert, btnSelect)
  • 리니어 레이아웃 4 : 에디트 텍스트 2개 (editNameResult, editNumberResult)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/layout01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="이름"
            android:textSize="20dp"/>

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editName" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/layout02"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="인원"
            android:textSize="20dp"/>

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editNumber" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/layout03"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="horizontal"
        android:gravity="center_horizontal">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:text="초기화"
            android:id="@+id/btnInit" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:text="입력"
            android:id="@+id/btnInsert" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="조회"
            android:id="@+id/btnSelect" />


    </LinearLayout>

    <LinearLayout
        android:id="@+id/layout04"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_weight="8"
        android:gravity="center_vertical"
        android:background="#FBF4D1">

        <EditText
            android:id="@+id/editNameResult"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"/>

        <EditText
            android:id="@+id/editNumberResult"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"/>

    </LinearLayout>

</LinearLayout>

 


MainActivity
class MainActivity : AppCompatActivity() {
    lateinit var myHelper: MyDBHelper
    lateinit var editName: EditText
    lateinit var editNumber: EditText
    lateinit var editNameResult: EditText
    lateinit var editNumberResult: EditText
    lateinit var btnInit: Button
    lateinit var btnInsert: Button
    lateinit var btnSelect: Button
    lateinit var sqlDB: SQLiteDatabase

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setTitle("가수 그룹 관리 DB")

        editName = findViewById(R.id.editName)
        editNumber = findViewById(R.id.editNumber)
        editNameResult = findViewById(R.id.editNameResult)
        editNumberResult = findViewById(R.id.editNumberResult)

        btnInit = findViewById(R.id.btnInit)
        btnInsert = findViewById(R.id.btnInsert)
        btnSelect = findViewById(R.id.btnSelect)

        myHelper = MyDBHelper(this)

        btnInit.setOnClickListener {
            sqlDB = myHelper.writableDatabase
            myHelper.onUpgrade(sqlDB, 1, 2)
            sqlDB.close()
        }

        btnInsert.setOnClickListener {
            sqlDB = myHelper.writableDatabase
            sqlDB.execSQL("INSERT INTO `groupTBL` VALUES ('${editName.text.toString()}', " +
                    "${editNumber.text.toString()});")
            sqlDB.close()
            Toast.makeText(applicationContext, "입력됨", Toast.LENGTH_SHORT).show()
        }

        btnSelect.setOnClickListener {
            sqlDB = myHelper.writableDatabase
            val cursor: Cursor
            cursor = sqlDB.rawQuery("SELECT * FROM groupTBL;", null)

            var names = "그룹이름 \r\n ---------- \r\n"
            var numbers = "인원 \r\n ---------- \r\n"

            while(cursor.moveToNext()) {
                names += cursor.getString(0) + "\r\n"
                numbers += cursor.getString(1) + "\r\n"
            }

            editNameResult.setText(names)
            editNumberResult.setText(numbers)

            cursor.close()
            sqlDB.close()
        }
    }

    inner class MyDBHelper(context: Context): SQLiteOpenHelper(context, "groupDB", null, 1) {
        override fun onCreate(db: SQLiteDatabase?) {
            db!!.execSQL("CREATE TABLE `groupTBL`(`gName` CHAR(20) PRIMARY KEY, `gNumber` INTEGER);")
        }

        override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
            db!!.execSQL("DROP TABLE IF EXISTS `groupTBL`;")
            onCreate(db)
        }
    }
}

 

onCreate() 메서드 밖에 SQLiteOpenHelper 클래스에서 상속받는 내부 클래스를 정의한 후 생성자를 수정

 

inner class MyDBHelper(context: Context): SQLiteOpenHelper(context, "groupDB", null, 1) {}

 

super의 두 번째 파라미터에는 새로 생성될 데이터베이스의 파일명을 지정
마지막 파라미터는 데이터베이스 버전으로 처음에는 1을 지정


MyDBHelper 클래스의 onCreate()와 onUpgrade() 메서드를 코딩
override fun onCreate(db: SQLiteDatabase?) {
    db!!.execSQL("CREATE TABLE `groupTBL`(`gName` CHAR(20) PRIMARY KEY, 
        `gNumber` INTEGER);")

}


  테이블을 생성하는 SQL문.
  onUpgrade()에서 호출되거나 데이터를 입력할 때 혹은 테이블이 없을 때 처음 한 번 호출.

override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
    db!!.execSQL("DROP TABLE IF EXISTS `groupTBL`;")
    onCreate(db)
}

 

  테이블을 삭제하고 새로 생성. 초기화 할 때 호출

 


초기화 버튼를 클릭했을 때 동작하는 리스너 코딩
myHelper = MyDBHelper(this)


  생성자가 실행되어 groupDB 파일이 생성

sqlDB = myHelper.writableDatabase
myHelper.onUpgrade(sqlDB, 1, 2)
sqlDB.close()


  groupDB를 쓰기용 데이터베이스로 열고, onUpgrade() 메서드를 호출. groupTBL 테이블이 있으면 삭제한 후 새로 생성. 이후 데이터베이스를 닫음.
  onUpgrade()의 두번째 파라미터에는 이전 버전을, 세 번째 파라미터는 새버전을 입력하는데 파라미터를 받은 다음 사용하지 않았으므로 아무 숫자나 넣어도 됨.


입력 버튼를 클릭했을 때 동작하는 리스너 코딩

 

sqlDB = myHelper.writableDatabase


  groupDB를 쓰기용으로 열기

 

sqlDB.execSQL("INSERT INTO `groupTBL` VALUES ('${editName.text.toString()}'," +
    " ${editNumber.text.toString()});")

 

  insert 문을 생생 후 execSQL() 메서드로 실행


조 버튼를 클릭했을 때 동작하는 리스너 코딩
while (cursor.moveToNext()) {
    names += cursor.getString(0) + "\r\n"
    numbers += cursor.getString(1) + "\r\n"
}


  행 데이터의 개수만큼 반복. moveToNext() 메서드는 커서 변수의 다음 행으로 넘어감.
  만약 다음행이 없다면 false를 반환하여 while문이 끝남.
  getString(열번호)는 현재 커서의 열 번호 데이터 값을 반환하여 문자열 변수에 계속 누적.
  0은 0번째 열 (그룹이름 열), 1은 1번째 열(인원).

 

 

 

 

 

[ 내용 참고 : IT 학원 강의 ]


1.  양방향 액티비티

메인 액티비티에서 세컨드 액티비티로 데이터를 넘긴 후에 세컨드 액티비티에서 메인 액티비티로 데이터를 돌려주는 경우

 

1)  메인 액티비티에서 putExtra()로 인텐트에 데이터를 넣는 것은 동일하지만, 세컨드 액티비티에서 데이터를 돌려 받으려면 액티비티를 호출할 때startActivityForResult() 메서드를 사용해야 함
2) 그리고 세컨드 액티비티에서 finish()로 끝내기 전에 메인 액티비티에 돌려줄 인텐트를 생성하여 putExtra()로 데이터를 넣은 다음 setResult()로 돌려줌.
3) 메인 액티비티에서는 onActivityResult() 메서드를 오버라이딩하고 오버라인딩된 메서드 안에서 getExtra()로 돌려 받은 데이터를 사용.

 

 

 

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical">

    <EditText
        android:id="@+id/editNum1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/editNum2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnNewActivity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="더하기" />
    
</LinearLayout>

 

activity_second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".SecondActivity"
    android:orientation="vertical">

    <Button
        android:id="@+id/btnReturn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="돌아가기" />

</LinearLayout>

 

MainActivity.kt
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        title = "메인 액티비티"

        val editNum1 = findViewById<EditText>(R.id.editNum1)
        val editNum2 = findViewById<EditText>(R.id.editNum2)
        val btnNewActivity = findViewById<Button>(R.id.btnNewActivity)
        btnNewActivity.setOnClickListener {
            val intent = Intent(applicationContext, SecondActivity::class.java)
            intent.putExtra("num1", editNum1.text.toString().toInt())
            intent.putExtra("num2", editNum2.text.toString().toInt())
            startActivityForResult(intent, 0)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            val sum = data!!.getIntExtra("sum", 0)
            Toast.makeText(applicationContext, "합계 :  ${sum}", Toast.LENGTH_SHORT).show()
        }
    }
}

 

  📍  startActivityForResult(intent, 0);

       값을 돌려받기 위해 startActivityForResult()를 사용. 두 번째 파라미터에는 돌려받을 값이 있는 경우에 0이상을 사용.
       여러 액티비티를 쓰는 경우, 어떤 Activity인지 식별하는 값.

  📍  onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
        세컨드 액티비티에서 setResult()로 값을 돌려주면 오버라이딩한 onActivityResult() 메서드가 실행

   📍  if (resultCode == RESULT_OK) 
         setResult()에서 보낸 값이 RESULT_OK이면 인텐트에서 돌려받은 값을 토스트 메시지로 화면에 출력

 

SecondActivity.kt
class SecondActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)

        title = "Second 액티비티"

        // 인텐트 관련 처리
        val intent = intent
        val sum = intent.getIntExtra("num1", 0) + intent.getIntExtra("num2", 0)

        val btnReturn = findViewById<Button>(R.id.btnReturn)
        btnReturn.setOnClickListener {
            val intentResult = Intent(applicationContext, MainActivity::class.java)
            intentResult.putExtra("sum", sum)
            setResult(Activity.RESULT_OK, intentResult)
            finish()
        }
    }
}

 

  📍 val intent = intent
        val sum = intent.getIntExtra("num1", 0) + intent.getIntExtra("num2", 0)

 

      메인 액티비티로부터 받은 두 값을 더함

  📍 val intentResult = Intent(applicationContext, MainActivity::class.java)
       intentResult.putExtra("sum", sum)
       setResult(Activity.RESULT_OK, intentResult)

      setResult()로 메인 액티비티에 돌려줌. 메인 액티비티의 onActivityResult() 메서드가 실행

 

 

 


2.  암시적 인텐트

명시적 인텐트의 개념이 두 액티비티를 사용자가 직접 생성하고 코딩하는 것이라면, 암시적 인텐트 implicit intent는 약속된 액션을 지정하여 '안드로이드에서 제공하는 기존 응용 프로그램을 실행하는 것'
  예를 들어 전화번호를 인텐트로 넘긴 후에 전화 걸기 응용 프로그램이 실행되는 것.

 

  ⚡️  메인 액티비티에서 인텐트를 생성할 때 실행하고자 하는 액션을 지정하고 액션의 데이터 값을 설정하면 기존의 안드로이드 응용 프로그램이 실행됨

   

119에 응급 전화를 거는 형식의 예
Intent intent = new Intent(Intent.ACTION_DIAL, Url.parse("tel:/119"));
startActivity(intent);

 

전화 걸기와 구글 맵을 사용하려면 AndroidManifest.xml의 <application 위에 다음과 같이 권한을 추가
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"/>

 

암시적 인텐트의 XML 파일
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical">

    <Button
        android:id="@+id/btnDial"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="전화 걸기" />

    <Button
        android:id="@+id/btnWeb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="홈 페이지 열기" />

    <Button
        android:id="@+id/btnGoogle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="구글 맵 열기" />

    <Button
        android:id="@+id/btnSearch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="구글 검색하기" />

    <Button
        android:id="@+id/btnSms"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="문자 보내기" />

    <Button
        android:id="@+id/btnPhoto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="사진 찍기" />

</LinearLayout>

 

암시적 인텐트의 Kotlin 코드
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        title = "암시적 인텐트 예제"
        val btnDial = findViewById<Button>(R.id.btnDial)
        val btnWeb = findViewById<Button>(R.id.btnWeb)
        val btnGoogle = findViewById<Button>(R.id.btnGoogle)
        val btnSearch = findViewById<Button>(R.id.btnSearch)
        val btnSms = findViewById<Button>(R.id.btnSms)
        val btnPhoto = findViewById<Button>(R.id.btnPhoto)

        btnDial.setOnClickListener {
            val tel = Uri.parse("tel:010-1234-5678")
            startActivity(Intent(Intent.ACTION_DIAL, tel))
        }

        btnWeb.setOnClickListener {
            val uri = Uri.parse("http://daum.net")
            startActivity(Intent(Intent.ACTION_VIEW, uri))
        }

        btnGoogle.setOnClickListener {
            val uri = Uri.parse("https://maps.google.com/maps?q="
                + 35.886606 + "," + 128.5938 + "&z=15" )
            startActivity(Intent(Intent.ACTION_VIEW, uri))
        }

        btnSearch.setOnClickListener {
            val intent = Intent(Intent.ACTION_WEB_SEARCH)
            intent.putExtra(SearchManager.QUERY, "안드로이드")
            startActivity(intent)
        }

        btnSms.setOnClickListener {
            val intent = Intent(Intent.ACTION_SENDTO)
            intent.putExtra("sms_body", "안녕하세요?")
            intent.setData(Uri.parse("smsto:010-1234-5678"))
            startActivity(intent)
        }

        btnPhoto.setOnClickListener {
            startActivity(Intent(MediaStore.ACTION_IMAGE_CAPTURE))
        }

    }
}

 

  📍  val uri = Uri.parse("tel:010-1234-5678")
        startActivity(Intent(Intent.ACTION_DIAL, uri))

      전화를 걸기 위해 URI 문자열을 'tel:전화번호'형식으로 사용. 액션으로 ACTION_DIAL을 사용하면 전화 걸기 창이 열림.

  📍  val uri = Uri.parse("http://daum.net")
        startActivity(Intent(Intent.ACTION_VIEW, uri))

       웹브라우저를 열기 위해 URI 문자열을 'http://웹 주소'형식으로 사용. 액션은 ACTION_VIEW를 사용.

  📍  val uri = Uri.parse("https://maps.google.com/maps?q=" + 35.86606 + "," + 128.5938 + "&z=15" )
        startActivity(Intent(Intent.ACTION_VIEW, uri))

      구글 맵을 열기 위해 URI 문자열을 구글 맵 주소과 경위도 형식으로 사용. 액션은 ACTION_VIEW를 사용

  📍  val intent = Intent(Intent.ACTION_WEB_SEARCH)
        intent.putExtra(SearchManager.QUERY, "안드로이드")

       구글 검색을 열기 위해 액션은 ACTION_WEB_SEARCH를 사용. 검색을 위해 putExtra()로 넘기는데, 첫 번째 파라미터로 SearchManager.QUERY를 사용하고 두 번째 파라미터에는 검색할 단어를 넘김.

  📍  val intent = Intent(Intent.ACTION_SENDTO)
         intent.putExtra("sms_body", "안녕하세요?")

       문자 메시지를 보내기 위해 액션은 ACTION_SENDTO를 사용. 보낼 문자는 putExtra()로 넘기는데, 첫 번째 파라미터에는 'sms_body'를 넣고 두 번째 파라미터에 보낼 문자를 넣음. setData()도 설정해야 함.

  📍  startActivity(Intent(MediaStore.ACTION_IMAGE_CAPTURE))

      카메라를 열기 위해 액션은 MediaStore.ACTION_IMAGE_CAPTURE를 사용.

 

 

 

 

 

 

 

 

 

[ 내용 참고 : IT 학원 강의 ]


1.  activity_main.xml

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

    <LinearLayout
        android:id="@+id/layout01"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="3">

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic1" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic2" />

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic3" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/layout02"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="3">

        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic4" />

        <ImageView
            android:id="@+id/imageView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic5" />

        <ImageView
            android:id="@+id/imageView6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic6" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/layout03"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="3">

        <ImageView
            android:id="@+id/imageView7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic7" />

        <ImageView
            android:id="@+id/imageView8"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic8" />

        <ImageView
            android:id="@+id/imageView9"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic9" />

    </LinearLayout>

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="투표 종료" />

</LinearLayout>

 

  • 바깥 리니어레이아웃 안에 리니어레이아웃 3개, 버튼 1개를 생성하고 layout_weight를 3:3:3:1로 함
  • 3개의 레이아웃에 각각 3개의 이미지뷰를 넣음. 각 이미지뷰의 layout_weight는 1:1:1로 함. 필요에 따라 이미지뷰에 적당한 layout_margin을 적용. (예 : 5dp)
  • 이미지뷰 9개의 아이디는 imageView1 ~ imageView9, 버튼의 아이디는 btnResult.


2.  result.xml

서브 액티비티에서 사용할 result.xml을 res - layout 폴더에 생성

바깥은 테이블레이아웃으로 설정하고 stretchColumns 속성을 0으로 함

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:stretchColumns="0">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="15dp"  />

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <TableRow>

        <TextView
            android:id="@+id/textView1"
            android:layout_gravity="center_vertical"
            android:text="그림1"
            android:textSize="15dp" />

        <RatingBar
            android:id="@+id/ratingBar1"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_gravity="right" />
    </TableRow>

    <TableRow>

        <TextView
            android:id="@+id/textView2"
            android:layout_gravity="center_vertical"
            android:text="그림2"
            android:textSize="15dp" />

        <RatingBar
            android:id="@+id/ratingBar2"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_gravity="right" />
    </TableRow>

    <TableRow>

        <TextView
            android:id="@+id/textView3"
            android:layout_gravity="center_vertical"
            android:text="그림3"
            android:textSize="15dp" />

        <RatingBar
            android:id="@+id/ratingBar3"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_gravity="right" />
    </TableRow>

    <TableRow>

        <TextView
            android:id="@+id/textView4"
            android:layout_gravity="center_vertical"
            android:text="그림4"
            android:textSize="15dp" />

        <RatingBar
            android:id="@+id/ratingBar4"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_gravity="right" />
    </TableRow>

    <TableRow>

        <TextView
            android:id="@+id/textView5"
            android:layout_gravity="center_vertical"
            android:text="그림5"
            android:textSize="15dp" />

        <RatingBar
            android:id="@+id/ratingBar5"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_gravity="right" />
    </TableRow>

    <TableRow>

        <TextView
            android:id="@+id/textView6"
            android:layout_gravity="center_vertical"
            android:text="그림6"
            android:textSize="15dp" />

        <RatingBar
            android:id="@+id/ratingBar6"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_gravity="right" />
    </TableRow>

    <TableRow>

        <TextView
            android:id="@+id/textView7"
            android:layout_gravity="center_vertical"
            android:text="그림7"
            android:textSize="15dp" />

        <RatingBar
            android:id="@+id/ratingBar7"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_gravity="right" />
    </TableRow>

    <TableRow>

        <TextView
            android:id="@+id/textView8"
            android:layout_gravity="center_vertical"
            android:text="그림8"
            android:textSize="15dp" />

        <RatingBar
            android:id="@+id/ratingBar8"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_gravity="right" />
    </TableRow>

    <TableRow>

        <TextView
            android:id="@+id/textView9"
            android:layout_gravity="center_vertical"
            android:text="그림9"
            android:textSize="15dp" />

        <RatingBar
            android:id="@+id/ratingBar9"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_gravity="right" />
    </TableRow>

    <TableRow>

        <Button
            android:id="@+id/btnReturn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_span="2"
            android:text="돌아가기" />
    </TableRow>
</TableLayout>

 

  • 각 <TableRow>에는 텍스트뷰 1개, 레이팅바 1개를 생성.
  • 마지막 <TableRow>에는 '돌아가기'를 생성.
  • 텍스트뷰의 아이디는 textView1 ~ textView9, 레이팅바의 아이디는 ratingBar1 ~ ratingBar9, 버튼의 아이디는 btnReturn.


3.  Kotlin 코드 작성 및 수정

MainActivity.kt
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_01)

        title = "명화 선호도 투표"

        // 그림을 클릭할 때마다 투표수를 저장할 9개짜리 배열을 선언하고 0으로 초기화
        val voteCounts = IntArray(9)

        // 이미지뷰 위젯을 저장할 9개짜리 배열을 선언
        val images = arrayOfNulls<ImageView>(9)

        // 이미지 버튼 Id 배열
        val imageIds = arrayOf(R.id.imageView1, R.id.imageView2, R.id.imageView3,
            R.id.imageView4, R.id.imageView5, R.id.imageView6,
            R.id.imageView7, R.id.imageView8, R.id.imageView9)

        // 이미지 이름 문자열 배열
        val imageNames = arrayOf("독서하는 소녀", "꽃장식 모자 소녀", "부채를 든 소녀",
            "이레느깡 단 베르양", "잠자는 소녀", "테라스의 두 자매",
            "피아노 레슨", "피아노 앞의 소녀들", "해변에서")

        // 각 이미지뷰에 대한 클릭 이벤트리스너를 생성. 이미지뷰가 9개나 되므로 반복문을 사용
        for (i in imageIds.indices) {
            images[i] = findViewById(imageIds[i]
            images[i]!!.setOnClickListener {
                voteCounts[i]++  // 그림을 클릭하면 해당 그림의 투표수가 증가
                Toast.makeText( // 그림을 클릭할 때마다 그림의 제목과 누적된 투표수를 토스트 메시지로 보여줌
                    applicationContext,
                    "${imageNames[i]} : 총${voteCounts[i]} 표",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }

        // '투표 종료'에 대해 클릭 이벤트 리스너를 생성
        val btnResult = findViewById<Button>(R.id.btn)
        // 인텐트를 생성하고 인텐트에 투표수 배열과 그림 제목 배열을 넣은 후 결과 액티비티를 호출
        btnResult.setOnClickListener {
            val intent = Intent(applicationContext, ResultActivity::class.java)
            intent.putExtra("voteCounts", voteCounts)
            intent.putExtra("imageNames", imageNames)
            startActivity(intent)
        }

    }
}

 

intent.putExtra("voteCounts", voteCounts)
intent.putExtra("imageNames", imageNames)


  정수형 voteCount 배열을 VoteCounts라는 이름으로 넘김. 이것을 액티비티에서는 getIntArrayExtra() 메서드로 받음.
  문자열 배열인 imageNames을 지정한 imageNames은 getStringArrayExtra() 메서드로 받음.

 

ResultActivity.kt
class ResultActivity: AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.result)

        // MainActivity에서 보낸 투표 결과 값을 받음
        title = "투표결과"
        
        val intent = intent
        val voteCounts = intent.getIntArrayExtra("voteCounts")
        val imageNames = intent.getStringArrayExtra("imageNames")

        // 가장 많은 투표를 받은 이미지와 제목을 나타내는 변수
        val mainText = findViewById<TextView>(R.id.textView)
        val mainImg = findViewById<ImageView>(R.id.imageView)

        // 9개의 TextView, RatingBar 객체 배열
        val ratingBars = arrayOfNulls<RatingBar>(9)
        val textViews = arrayOfNulls<TextView>(9)

        // 9개의 TextView, RatingBar id 배열
        val textViewIds = arrayOf(R.id.textView1, R.id.textView2, R.id.textView3,
                      R.id.textView4, R.id.textView5, R.id.textView6,
                      R.id.textView7, R.id.textView8, R.id.textView9)

        val ratingBarIds = arrayOf(R.id.ratingBar1, R.id.ratingBar2, R.id.ratingBar3,
                        R.id.ratingBar4, R.id.ratingBar5, R.id.ratingBar6,
                        R.id.ratingBar7, R.id.ratingBar8, R.id.ratingBar9)

        val imageIds = arrayOf(R.drawable.pic1, R.drawable.pic2, R.drawable.pic3,
                       R.drawable.pic4, R.drawable.pic5, R.drawable.pic6,
                       R.drawable.pic7, R.drawable.pic8, R.drawable.pic9)

        var maxVotesIndex = 0
        for (i in 1 until voteCounts!!.size) {
            if (voteCounts[i] > voteCounts[maxVotesIndex]) {
                maxVotesIndex = i
            }

            mainText.text = imageNames!![maxVotesIndex]
            mainImg.setImageResource(imageIds[maxVotesIndex])
        }

        for (i in voteCounts!!.indices) {

            textViews[i] = findViewById(textViewIds[i])
            textViews[i]!!.text = imageNames!![i]

            ratingBars[i] = findViewById(ratingBarIds[i])
            ratingBars[i]!!.rating = voteCounts[i].toFloat()
            ratingBars[i]!!.stepSize = 1f

        }

        // 버튼을 클릭하면 서브 액티비티를 종료. 메인 액티비티로 돌아감.
        val btnReturn = findViewById<Button>(R.id.btnReturn)
        btnReturn.setOnClickListener {
            finish()
        }

    }
}

 

 

 

 

 

 

[ 내용 참고 : IT 학원 강의 ]


1.  안드로이드의 4대 컴포넌트

안드로이드의 4대 컴포넌트는 액티비티 · 서비스 · 브로드캐스트 리시버 · 콘텐트 프로바이더


1)  액티비티 Activity

 화면을 구성하는 가장 기본적인 컴포넌트

 

2)  서비스 service

  눈에 보이는 화면(액티비티)과 상관없이 백그라운드에서 동작하는 컴퍼넌트. 백신 프로그램처럼 눈에 보이지는 않지만 계속 동작
  -  로컬에서 동작하는 서비스는 다음과 같이 세 단계를 거침
      서비스 생성 ▶️ 서비스 시작 ▶️ 서비스 종료

 

3)  브로드캐스트 리시버

  -  안드로이드는 여러 응용 프로그램이나 장치에 메시지를 전달하기 위해 방송 broadcasting 메시지를 사용
  -  안드로이드는 문자 메시지 도착, 배터리 방전, SD 카드 탈부착, 네트워크 환경 변화가 발생하면 전체 응용 프로그램이 알 수 있도록 방송 신호를 보냄 그리고 브로드캐스트 리시버 Broadcast Receiver는 이러한 방송 신호가 발생하면 반응함

 

4)  콘텐트 프로바이더

 콘텐트 프로바이더 Content Provider는 응용 프로그램 사이에 데이터를 공유하기 위한 컴포넌트
  -  안드로이드 응용 프로그램은 데이터에 자신만 접근할 수 있으므로 자신의 데이터를 외부에 공유하려면 콘텐트 프로바이더를 만들어야 함. 콘텐트 프로바이더에서 처리된 데이터는 일반적으로 데이터베이스 또는 파일로 저장

 


2.  액티비티의 개요

액티비티는 안드로이드폰에 나타나는 화면 하나하나를 말함. 액티비티는 사용자에게 보여주는 화면을 만들기 때문에 안드로이드의 4개 컴포넌트 중 가장 핵심적인 요소.

 

  • 안드로이드 프로젝트를 생성할 때 activity_main.xml과 MainActivity.kt 파일이 생성
  • activity_main.xml은 화면을 구성하는 코드로 되어 있지만 activity_main.xml이 아니라 MainActivity.kt가 액티비티에 해당
  • 일반적으로 액티비티 하나당 XML 파일 하나를 만들어서 사용
activity_main.xml 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btnNewActivity"
        android:text="새 화면 열기" />


</LinearLayout>

 

second.xml 

 

    [res] - [layout] 에 second.xml 생성

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#CDE4F6">

    <Button
        android:id="@+id/btnReturn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="돌아가기" />

</LinearLayout>

 

SecondActivity.kt
class SecondActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.second)

        val btnReturn: Button = findViewById(R.id.btnReturn)
        btnReturn.setOnClickListener {
            finish()
        }

    }
}

 

  📍  finish()가 호출되면 현재 액티비티를 종료. 세컨드 액티비티는 메인 액티비티에서 호출할 것이므로 세컨드 액티비티를 종료하면 다시 메인 액티비티가 나타남

 

MainActivity.kt
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val btnNewActivity = findViewById<Button>(R.id.btnNewActivity)
        btnNewActivity.setOnClickListener {
            val intent = Intent(applicationContext, SecondActivity::class.java)
            startActivity(intent)
        }
    }
}

 

val intent = Intent(applicationContext, SecondActivity::class.java)

 

  -  인텐트를 생성. Intent의 첫 번째 파라미터 applicationContext는 메인 클래스의 컨텍스트를 반환
  -  applicationContext 대신 this@MainActivity 도 가능
  -  두 번째 파라미터로 이 인텐트에 포함될 액티비티 SecondActivity를 넘겨줌. ::class.java를 붙여야 한다는 것을 주의.

 

startActivity(intent)


  -  startActivity() : 새로운 액티비티를 화면에 출력. 파라미터로 인텐트를 받음.

 

AndroidManifest.xml
<activity
    android:name=".MainActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
         category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity android:name=".SecondActivity" />

 

  📍  안드로이드는 사용될 액티비티를 AndroidManifest.xml에 반드시 등록. 프로젝트를 생성할 때 메인 액티비티는 자동으로 등록되지만, 추가한 세컨드 액티비티는 별도로 등록해야 함.

 


3.  명시적 인텐트

인텐트 Intent는 안드로이드의 4대 컴포넌트가 서로 데이터를 주고받기 위한 메시지 객체.

명시적 인텐트와 암시적 인텐트로 구분


1)  명시적 인텐트와 데이터 전달

  🐰  명시적 인텐트 explicit intent는 다른 액티비티의 이름을 명확히 지정할 때 사용

val intent = Intent(applicationContext, SecondActivity::class.java)
startActivity(intent)


  ✓  Intent() 생성자의 두 번째 파라미터에서는 액티비티 클래스를 넘길 수 있는데, 위의 코드에서는 그 전에 생성한 SecondActivity로 정확히 지정. 그리고 생성한 인텐트를 넘겨서 세컨드 액티비티를 실행

  ✓  이처럼 명확하게 액티비티의 이름을 지정했기 때문에 명시적 인텐트가 됨. 일반적으로 명시적 인텐트는 사용자가 새로운 액티비티를 직접 생성하고 호출할 때 사용

  🐰  인텐트에 데이터를 담아서 넘기는 것도 가능. 메인 액티비티에서 인텐트에 데이터를 실어서 넘긴 다음 세컨드 액티비티에게 받은 데이터를 처리

 

 

1)  putExtra()를 이용해서 필요한 만큼 데이터를 인텐트에 넣음
2)  startActivity()로 인텐트를 다른 액티비티에 넘김
3)  인텐트를 받은 액티비티에서 getStringExtra(), getIntExtra(), getBooleanExtra() 등의 메서드로 넘어온 데이터에 접근

 

 

 


2)  레이팅바

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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RatingBar
        android:id="@+id/ratingBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <RatingBar
        android:id="@+id/ratingBar2"
        style="?android:attr/ratingBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="10"
        android:stepSize="1" />

    <RatingBar
        android:id="@+id/ratingBar3"
        style="?android:attr/ratingBarStyleIndicator"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:rating="1.5" />

    <Button
        android:id="@+id/btnIncrease"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="증가시키기" />

    <Button
        android:id="@+id/btnDecrease"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="감소시키기" />

</LinearLayout>

 

style="?android:attr/ratingBarStyleSmall"
style="?android:attr/ratingBarStyleIndicator"

 

  -  레이팅바의 스타일을 지정. 작은 모양과 중간 모양을 표시.

android:stepSize="1"


  -  한 번에 증가될 크기를 별 1개로 지정. 소수점으로 설정할 수 있으며 디폴트는 0.5.

android:numStars="10"


  -  별의 개수를 지정. 디폴트는 5개.

 

android:rating="1.5"


  -  초깃값을 설정. 1.5개가 채워진 상태로 표현.

 

kotlin 코드
val ratingBar1 = findViewById<RatingBar>(R.id.raingBar1)
val ratingBar2 = findViewById<RatingBar>(R.id.raingBar1)
val ratingBar3 = findViewById<RatingBar>(R.id.raingBar1)
val btnIncrease = findViewById<RatingBar>(R.id.btnIncrease)
val btnDecrease = findViewById<RatingBar>(R.id.btnDecrease)

btnDecrease.setOnClickListener {
    ratingBar1.rating = ratingBar1.rating + ratingBar1.stepSize
    ratingBar2.rating = ratingBar2.rating + ratingBar2.stepSize
    ratingBar3.rating = ratingBar3.rating + ratingBar3.stepSize
}    

btnIncrease.setOnClickListener {
    ratingBar1.rating = ratingBar1.rating + ratingBar1.stepSize
    ratingBar2.rating = ratingBar2.rating + ratingBar2.stepSize
    ratingBar3.rating = ratingBar3.rating + ratingBar3.stepSize
}

 

  -  rating으로 레이팅바에 채워진 개수와 stepSize로 레이팅바에 설정된 stepSize 속성의 증가 크기 (디폴트는 0.5)를 더하거나 뺌

 

 

 

 

[ 내용참고 : IT 학원 강의 ]

 

+ Recent posts