728x90


 1. 구상


1. 우선 이 어플의 목적은 

1) gps를 활용해서 자신의 위치를 가져오도록 하자.

2) 이 위치를 활용해 자신이 일정범위 안에 위치하는지, 그렇지 않는지 판단하는 것이 최종적인 목표이다.


뭐, 다 만들고 나서 이렇게 보니, 생각보다 쉽게 만들 수 있었을 것 같지만.... 처음 만들다보니 시간이 오래 걸렸네.


2. 그럼 어떤식으로 설계를 들어갈 지 구상을 해보았다.

1) 전체적인 관리를 하는 인터페이스를 만들어주자. 최상위 항목이고, 이 밑에 범위를 설정해주는 class, 지도를 보여주는 class, 자신이 설정한 범위를 list형식으로 보여주는 class를 구현하자.



위 그림은 처음 설계하면서 어림잡아 틀을 만든 것이다.

이해하기 쉽게 추가했다.




3. 이제 본격적으로 해부에 들어가보자.

1) 가장 기본이 되는 화면인 MainActivity 부분이다. 우선 이해를 위해 사진을 추가하였다.

메인은 간단하게 구성을 하였다. 버튼을 누르면 자신이 원하는 페이지로 이동하도록 만들었다. 

혹시 이후에 쓰일 수 있으니 상단에 메뉴도 구현해주었다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//MainActivitr.java
 
package com.example.newmap;
 
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
 
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
 
    public void moveMaps(View view) {
        startActivity(new Intent(this, MapsActivity.class));
    }
 
    public void moveMarkerAdd(View view) {
        startActivity(new Intent(this, MarkerAddActivity.class));
    }
 
    public void moveMarkerList(View view) {
        startActivity(new Intent(this, MarkerListActivity.class));
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_menu_1:
                Toast.makeText(this"첫 번째 메뉴", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(this, MarkerAddActivity.class));
                return true;
            case R.id.action_menu_2:
                Toast.makeText(this"두 번째 메뉴", Toast.LENGTH_SHORT).show();
                return true;
        }
 
        return super.onOptionsItemSelected(item);
    }
 
 
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!--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">
 
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="44dp"
        android:onClick="moveMarkerAdd"
        android:text="경계를 등록하러가자"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <Button
        android:id="@+id/listButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="16dp"
        android:onClick="moveMarkerList"
        android:text="경계 리스트"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="16dp"
        android:onClick="moveMaps"
        android:text="Map으로 이동"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/listButton" />
 
 
</androidx.constraintlayout.widget.ConstraintLayout>
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!--main_menu.xml-->
 
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
 
    <item
        android:id="@+id/action_menu_1"
        android:title="내 위치 변경하기"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_menu_2"
        android:title="좌표 제거하기"
        app:showAsAction="never" />
</menu>
cs






2) 다음은 경계를 관리하는 MarkerAddActivity부분이다.

모습은 아래와 같다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
//MarkerAddActivity.java
 
package com.example.newmap;
 
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
 
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
 
public class MarkerAddActivity extends AppCompatActivity {
    //화면에 적은 글자를 활용하도록 전역변수로 선언해준다.
    private EditText mTitleEditText;
    private EditText mLatEditText;
    private EditText mLngEditText;
    private long mMemoId = -1;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_marker_add);
        //위에 선언한 변수와 layout에 존재하는 edittext를 연결해준다.
        mTitleEditText = findViewById(R.id.title_edit);
        mLatEditText = findViewById(R.id.lat_edit);
        mLngEditText = findViewById(R.id.lng_edit);
 
        //이부분은 db를 연동하는 부분이다.
        Intent intent = getIntent();
        if(intent != null){
            
            //이후에 db에 데이터를 저장하면서 관리하기 쉽게 id를 부여해준다.
            mMemoId = intent.getLongExtra("id"-1);
            String title = intent.getStringExtra("title");
            String lat = intent.getStringExtra("lat");
            String lng = intent.getStringExtra("lng");
 
            mTitleEditText.setText(title);
            mLatEditText.setText(lat);
            mLngEditText.setText(lng);
        }
    }
 
    public void addMarker(View view) {
        //editText에 적혀있는 글을 string으로 읽어온다.
        String title = mTitleEditText.getText().toString();
        String lat = mLatEditText.getText().toString();
        String lng = mLngEditText.getText().toString();
 
        //db에 저장하는 형식으로 데이터를 변환해준다.
        ContentValues contentValues = new ContentValues();
        contentValues.put(MemoContract.MemoEntry.COLUMN_NAME_TITLE, title);
        contentValues.put(MemoContract.MemoEntry.COLUMN_NAME_LAT, lat);
        contentValues.put(MemoContract.MemoEntry.COLUMN_NAME_LNG, lng);
 
        //db를 write형식으로 가져오자.
        SQLiteDatabase db = MemoDbHelper.getInstance(this).getWritableDatabase();
 
        //이부분은 음... 수정을 위한 부분이다.
        if(mMemoId == -1){
            //db에 데이터를 넣어준다.
            long newRowId = db.insert(MemoContract.MemoEntry.TABLE_NAME,null, contentValues);
 
            //제대로 들어갔는지 toast메시지로 확인하자.
            if(newRowId == -1){
                Toast.makeText(this"저장에 문제가 발생하였습니다.", Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(this"경계가 추가되었습니다", Toast.LENGTH_SHORT).show();
                setResult(RESULT_OK);
 
                startActivity(new Intent(this, MarkerListActivity.class));
            }
        }
        else{
            //수정을 해주는 모습을 볼 수 있다.
            int count = db.update(MemoContract.MemoEntry.TABLE_NAME, contentValues, MemoContract.MemoEntry._ID + "=" + mMemoId, null);
 
            if(count == 0) {
                Toast.makeText(this"수정에 문제가 발생하였습니다.", Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(this"경계가 수정되었습니다", Toast.LENGTH_SHORT).show();
                setResult(RESULT_OK);
            }
        }
 
 
 
 
 
    }
 
    //메뉴 연결
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.marker_add_menu, menu);
        return true;
    }
 
    //메뉴 버튼이 눌리면 동작을 하도록
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.marker_add_menu_1:
                Toast.makeText(this"모든 경계가 삭제되었습니다.", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(this, MainActivity.class));
                return true;
            case R.id.marker_add_menu_2:
                Toast.makeText(this"두 번째 메뉴", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(this, MarkerListActivity.class));
                return true;
        }
 
        return super.onOptionsItemSelected(item);
    }
}
 
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<!--activity_marker_add.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=".MarkerAddActivity">
 
    <EditText
        android:id="@+id/title_edit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="32dp"
        android:ems="10"
        android:hint="title"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <EditText
        android:id="@+id/lat_edit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="위도"
        android:inputType="numberDecimal"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/title_edit" />
 
    <EditText
        android:id="@+id/lng_edit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="경도"
        android:inputType="numberDecimal"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/lat_edit" />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="140dp"
        android:layout_marginLeft="140dp"
        android:layout_marginTop="36dp"
        android:onClick="addMarker"
        android:text="경계 등록"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/lng_edit" />
 
</androidx.constraintlayout.widget.ConstraintLayout>
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!--marker_add_menu.xml-->
 
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
 
    <item
        android:id="@+id/marker_add_menu_1"
        android:title="모든 경계 삭제"
        app:showAsAction="never" />
    <item
        android:id="@+id/marker_add_menu_2"
        android:title="경계 리스트"
        app:showAsAction="never" />
</menu>
cs



우선 인터페이스는 위쪽의 코드와 같고, 이제 내부적으로 db를 구현하기 위해서 2개의 class를 더 만들어주었다.

이 db부분은 youtube를 참고하였다.(https://www.youtube.com/watch?v=lf6GOaTRCgA&t=84s)


하나는 db의 형식을 선언하는 class이다. db의 Column의 이름을 상수로 선언해주었다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//MemoContract.java
 
package com.example.newmap;
 
import android.provider.BaseColumns;
 
public final class MemoContract {
    private  MemoContract(){
 
    }
 
    public  static class MemoEntry implements BaseColumns {
        public static final String TABLE_NAME = "memo";
        public static final String COLUMN_NAME_TITLE = "title";
        public static final String COLUMN_NAME_LAT = "lat";
        public static final String COLUMN_NAME_LNG = "lng";
    }
}
 
cs


이제, 나머지 하나가 메인인데, 이 class는 데이터와 관련된 모든것의 중심이 되는 class이다.

사실 설명이 긴데, 이 설명을 그냥 하면 이해하기 힘들 것 같아서 주석에 설명을 적어놓았다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//MemoDbHelper.java
 
package com.example.newmap;
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
 
public class MemoDbHelper extends SQLiteOpenHelper {
    private static MemoDbHelper sInstance;
 
    //이 db version을 선언해준다. 사실 활용 할 일은 없었지만, 어떤식으로 이용되야 할 지는 감이 잡힌다.
    //test를 하면서 table에 개수가 변하게 된 적이 있었다. 그때, 아무리 테스트를 해도 저장에서 오류가 발생했었는데,
    //이때 해결은 app을 지우고 다시 설치하여 문제를 해결하였다.
    //허나, 이때, version을 한단계 올려주고, 내부적인 문제를 해결하도록 하는 방법이 있지 않았을까 싶다.
    private static final int DB_VERSION = 1;
    //db의 이름 선언
    private static final String DB_NAME = "Memo.db";
    //db에 담기는 형식을 결정해준다. 아래는 sql문법이라는데, 우선 활용할 부분만 찾아서 활용하였다.
    private static final String SQL_CREATE_ENTRIES =
            String.format("CREATE TABLE %s (%s INTEGER PRIMARY KEY AUTOINCREMENT, %s TEXT, %s TEXT, %s TEXT)",
                    MemoContract.MemoEntry.TABLE_NAME,
                    MemoContract.MemoEntry._ID,
                    MemoContract.MemoEntry.COLUMN_NAME_TITLE,
                    MemoContract.MemoEntry.COLUMN_NAME_LAT,
                    MemoContract.MemoEntry.COLUMN_NAME_LNG
            );
 
    //db에서 데이터를 불러올 때, MemoDbHelper dbHelper = MemoDbHelper.getInstance(this);
    //와 같은 방법으로 데이터를 가져오게 된다.
    public static MemoDbHelper getInstance(Context context){
        if (sInstance == null){
            sInstance = new MemoDbHelper(context);
        }
        return sInstance;
    }
    //db를 지우는 방식 구현
    private static final String SQL_DELETE_ENTRIES =
            "DROP TABLE IF EXISTS" + MemoContract.MemoEntry.TABLE_NAME;
 
    public MemoDbHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }
 
    //처음 활용할 때, sql을 만들어준다.
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(SQL_CREATE_ENTRIES);
    }
 
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        //업데이트가 됬을때 처리하는 부분.
        sqLiteDatabase.execSQL(SQL_DELETE_ENTRIES);
    }
}
 
cs




3) 이제 거의 마지막인데, 이 부분은 db의 데이터를 list로 보여주는 페이지이다.

이것도 위와 비슷하게 codesource에 주석으로 설명을 적어놓았다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
//MarkerListActivity.java
 
package com.example.newmap;
 
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
 
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
 
import com.google.android.material.floatingactionbutton.FloatingActionButton;
 
public class MarkerListActivity extends AppCompatActivity {
 
    private static final int REQUEST_CODE_INSERT = 1000;
 
    private MemoAdapter mAdapter;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_marker_list);
 
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(MarkerListActivity.this, MarkerAddActivity.class), REQUEST_CODE_INSERT);
            }
        });
 
        //쿼리 항목을 리스트로 표현하기 위해서, xml에 있는 리스트 id에 등록을 하자.
        ListView listView = findViewById(R.id.memo_list);
 
        //쿼리를 가져오자.
        Cursor cursor = getMemoCursor();
        //query 항목을 처리를 해주자.
        mAdapter = new MemoAdapter(this, cursor);
        //처리한 데이터를 리스트에 등록한다.
        listView.setAdapter(mAdapter);
 
        //이 아이템이 눌리면, 수정을 하러 들어가자.
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Intent intent = new Intent(MarkerListActivity.this, MarkerAddActivity.class);
 
                //데이터를 Cursor에 담아 가져오자. 이때, 아이템은 position을 통해 원하는 것을 골라 가져온다.
                Cursor cursor = (Cursor) mAdapter.getItem(position);
 
                //가져온 데이터의 TITLE, LAT, LNG을 string에 담아
                String title = cursor.getString(cursor.getColumnIndexOrThrow(MemoContract.MemoEntry.COLUMN_NAME_TITLE));
                String lat = cursor.getString(cursor.getColumnIndexOrThrow(MemoContract.MemoEntry.COLUMN_NAME_LAT));
                String lng = cursor.getString(cursor.getColumnIndexOrThrow(MemoContract.MemoEntry.COLUMN_NAME_LNG));
 
                //intent 내부에 넣어준다.(editText 부분)
                intent.putExtra("id", id);
                intent.putExtra("title", title);
                intent.putExtra("lat", lat);
                intent.putExtra("lng", lng);
 
                startActivityForResult(intent, REQUEST_CODE_INSERT);
            }
        });
 
        //리스트를 삭제하자.
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
                final long deleteId = id;
                //리스트를 삭제하는것은 알람 팝업을 따로 구현하여 추가적인 확인을 구하자.
                AlertDialog.Builder builder = new AlertDialog.Builder(MarkerListActivity.this);
                //내부에 들어갈 글을 적어주자.
                builder.setTitle("메모 삭제");
                builder.setMessage("메모를 삭제하시겠습니까?");
                //yes버튼이 눌리면
                builder.setPositiveButton("삭제"new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //db를 write 형식으로 수정이 가능하도록 가져온 다음.
                        SQLiteDatabase db = MemoDbHelper.getInstance(MarkerListActivity.this).getWritableDatabase();
                        //삭제할 id부분을 지워주자.(MemoDbHelper에 구현이 되어있다.)
                        //이때, return 값은 삭제한 data의 개수로 1이 반환이 된다.
                        int deletedCount = db.delete(MemoContract.MemoEntry.TABLE_NAME, MemoContract.MemoEntry._ID + " = " + deleteId, null);
 
                        //만일 삭제가 되지 않았다면 오류
                        if(deletedCount == 0){
                            Toast.makeText(MarkerListActivity.this"삭제에 문제가 발생하였습니다.", Toast.LENGTH_SHORT).show();
                        }
                        else{
                            //
                            mAdapter.swapCursor(getMemoCursor());
                            Toast.makeText(MarkerListActivity.this"삭제되었습니다.", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                builder.setNegativeButton("취소"null);
                builder.show();
                return true;
            }
        });
    }
 
 
    //쿼리를 가져오는 메소드
    private  Cursor getMemoCursor(){
        //db에서 instance를 가져온다.
        MemoDbHelper dbHelper = MemoDbHelper.getInstance(this);
        //query를 전부 가져오자.
        //MemoContract.MemoEntry._ID + "DESC"(마지막 순서에 적으면, 내림차순으로 정렬한다고 하는데, 어디에 이용할 지는 아직 고려중.)
        return dbHelper.getReadableDatabase().query(MemoContract.MemoEntry.TABLE_NAME, nullnullnull,null,null,null,null);
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_CODE_INSERT && resultCode == RESULT_OK){
            //swapCursor는 cursor를 교체해주는 역할을 하는데,
            //지워져서 사라진 부분이 생기면 list를 다시 불러오는 기능을 한다.
            mAdapter.swapCursor(getMemoCursor());
        }
    }
 
    //cursor을 처리해주는 내부 클래스를 만들자.
    private static class MemoAdapter extends CursorAdapter{
        //가져온 데이터를 뿌려주기 위해서 cursor을 가져온다.
        public MemoAdapter(Context context, Cursor c) {
            super(context, c, false);
        }
 
        @Override
        public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
            //안드로이드 기본 리스트를 사용한다.
            return LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, viewGroup, false);
        }
 
        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            //textView에 연결해준다.
            TextView titleText = view.findViewById(android.R.id.text1);
            //커서에 담긴 항목중, title값을 가져와서 추가한다.
            titleText.setText(cursor.getString(cursor.getColumnIndexOrThrow(MemoContract.MemoEntry.COLUMN_NAME_TITLE)));
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!--activity_marker_list-->
 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MarkerListActivity">
 
    <ListView
        android:id="@+id/memo_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
 
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        app:useCompatPadding="true"
        android:clickable="true"
        app:srcCompat="@drawable/ic_add_black_24dp"
        app:fabSize="auto"
        android:layout_alignParentRight="true" />
 
 
</RelativeLayout>
cs




4) 드디어 마지막이다.

이 부분은 구글맵 api를 활용해서 구현을 하였다. 와.... 지금 다시보는데, 외부 라이브러리를 활용이 제대로 이루어지지 않아서 Convex Hull algorithm을 활용하였다.

뭐 지금와서 생각해보니, 오히려 쓸모없는 데이터를 생략할 수 있게 된 것 같다.


여기서 설명하기에는 양이 조금 많아서 이 또한 주석으로 자세~하게 설명해놓았으니, 읽어 볼 사람은 읽어보면 도움이 될 것이라고 생각한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
//MapsActivity.java
 
package com.example.newmap;
 
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
 
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
 
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.tasks.OnSuccessListener;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Stack;
//import JTS; 음.... jts라는 라이브러리를 활용하면 간단하게 영역 외부, 내부 판단이 가능할 것 같은데,
//지금은 어떤식으로 활용하는지 모르겠어서, 우선 알고리즘을 직접 구현하자.
 
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMarkerClickListener, GoogleMap.OnInfoWindowClickListener {
 
    private static final int REQUEST_CODE_PERMISSIONS = 1000;
    private GoogleMap mMap;
    private FusedLocationProviderClient mFusedLocationClient;
    Marker mMarker;
    private EditText editPlace;
    private boolean boundaryIsOn = false;
    //마지막 활용을 위해서 변수 선언
 
 
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        editPlace = findViewById(R.id.editPlace);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
 
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    }
 
 
    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
 
        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(37.2664398126.9994077);
        mMap.addMarker(new MarkerOptions().position(sydney).title("it's me!!"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f));
        mMap.getUiSettings().setZoomControlsEnabled(true);
 
//       mMap.setOnMarkerClickListener(this);
        //마커 클릭에 대한 리스너를 등록한다.
//        mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
//            @Override
//            public void onInfoWindowClick(final Marker marker) {
//                final GoogleMap.OnInfoWindowClickListener context = this;
//                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder((Context) context);
//
//                alertDialogBuilder.setTitle("마커 삭제");
//
//                alertDialogBuilder
//                        .setMessage("마커를 삭제하시겠습니까?")
//                        .setCancelable(false)
//                        .setPositiveButton("삭제",
//                                new DialogInterface.OnClickListener() {
//                                    public void onClick(
//                                            DialogInterface dialog, int id) {
//                                        marker.remove();
//                                    }
//                                })
//                        .setNegativeButton("취소",
//                                new DialogInterface.OnClickListener() {
//                                    public void onClick(
//                                            DialogInterface dialog, int id) {
//                                        // 다이얼로그를 취소한다
//                                        dialog.cancel();
//                                    }
//                                });
//
//
//                // 다이얼로그 생성
//                AlertDialog alertDialog = alertDialogBuilder.create();
//
//                // 다이얼로그 보여주기
//                alertDialog.show();
//            }
//        });
        mMap.setOnInfoWindowClickListener(this);
    }
 
    @Override
    public void onInfoWindowClick(Marker marker) {
        Toast.makeText(this"Info window clicked",
                Toast.LENGTH_SHORT).show();
    }
 
 
    //gps버튼을 누르면 내 위치로 이동하도록 만들어준다.
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void onLastLocationButtonClicked(View view) {
        //gps버튼을 눌렀을 때, 권한이 획득되었는지 확인하자.
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    Activity#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for Activity#requestPermissions for more details.
            ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE_PERMISSIONS);
            return;
        }
        mFusedLocationClient.getLastLocation().addOnSuccessListener(thisnew OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if(location != null){
                    LatLng myLocation = new LatLng(location.getLatitude(), location.getLongitude());
                    mMap.addMarker(new MarkerOptions().position(myLocation).title("현재 위치").snippet(location.getLatitude() + "/" + location.getLongitude()));
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
                }
                else{
//                    Toast.makeText(this,"권한 체크 거부됨",Toast.LENGTH_SHORT).show();
                    mMap.animateCamera(CameraUpdateFactory.zoomTo(10.0f));
                }
            }
        });
    }
 
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            //만일 사용자가 요청을 거부하였다면, 토스트 메시지를 띄운다.
            case REQUEST_CODE_PERMISSIONS:
                if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(this,"권한 체크 거부됨",Toast.LENGTH_SHORT).show();
                }
        }
 
    }
 
    public void moveMainActivity(View view) {
        //뒤로가기 버튼으로 메뉴로 귀환시킨다.
        super.onBackPressed();
    }
 
    //영역을 보기 좋게 마커로 표시해준다.
    public void onBoundaryMarkerButtonClicked(View view) {
        //db와 연동을 해서 데이터를 가져온다.
        MemoDbHelper dbHelper = MemoDbHelper.getInstance(this);
 
        Cursor cursor =  dbHelper.getReadableDatabase().query(MemoContract.MemoEntry.TABLE_NAME, nullnullnull,null,null,null,null);
 
        //한번 클릭하면 마커를 만들고, 두번 클릭하면 마커를 제거하는 구현을 하려하였으나, 음... 일단 이후에 추가적으로 구현하자.
//        if(boundaryIsOn){
//            while(cursor.moveToNext()){
//                String lat = cursor.getString(cursor.getColumnIndexOrThrow(MemoContract.MemoEntry.COLUMN_NAME_LAT));
//                String lng = cursor.getString(cursor.getColumnIndexOrThrow(MemoContract.MemoEntry.COLUMN_NAME_LNG));
//                LatLng sydney = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
//                mMarker = mMap.addMarker(new MarkerOptions().position(sydney).title("boundary"));
//                if(mMarker != null){
//                    mMarker.remove();
//                }
//            }
//            Toast.makeText(this,"경계가 제거되었습니다.",Toast.LENGTH_SHORT).show();
//            boundaryIsOn = false;
//        }
//        else{
            while(cursor.moveToNext()){
                String lat = cursor.getString(cursor.getColumnIndexOrThrow(MemoContract.MemoEntry.COLUMN_NAME_LAT));
                String lng = cursor.getString(cursor.getColumnIndexOrThrow(MemoContract.MemoEntry.COLUMN_NAME_LNG));
                LatLng sydney = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
                mMap.addMarker(new MarkerOptions().position(sydney).title("boundary").snippet(lat + "/" + lng));
            }
//
//            Toast.makeText(this,"경계가 추가되었습니다.",Toast.LENGTH_SHORT).show();
//            boundaryIsOn = true;
//        }
 
 
//        Toast.makeText(this,"경계가 추가되었습니다.",Toast.LENGTH_SHORT).show();
    }
 
    //내가 원하는 위치를 찾아서 마커로 등록하는 버튼의 onClick을 구현해주었다.
    public void searchButtonClicked(View view) {
        //찾는 위치는 editText에 담겨있고, 그 데이터를 가져온다.
        String place = editPlace.getText().toString();
        //구글의 Geocoder을 활용해 그 데이터의 정보를 가져온다.
        Geocoder coder = new Geocoder(getApplicationContext());
        //리스트에 담아주고,
        List<Address> list = null;
        try{
            list = coder.getFromLocationName(place,1);
        } catch(IOException e){
            e.printStackTrace();
        }
        //그 정보의 좌표값을 가져온다.
        Address addr = list.get(0);
        double lat = addr.getLatitude();
        double lng = addr.getLongitude();
        //이제 등록을 하여서
        LatLng geoPoint = new LatLng(lat,lng);
        //카메라를 줌해주고
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(geoPoint, 15));
        //마커를 등록해준다.
        MarkerOptions marker = new MarkerOptions();
        marker.position(geoPoint);
        marker.title(place).snippet(lat + "/" + lng);
        mMap.addMarker(marker);
    }
 
    //마커가 클릭되었을때, 마커를 지우기 위해서 만들어 주었지만, 활용하기 까다로워 패스하였다.
    @Override
    public boolean onMarkerClick(final Marker marker) {
        //builder 안에 사용하기 위해서 선언을 하기는 하였지만, 쓰임세를 잘 모르겠다....
//        final Context context = this;
//        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
//
//        alertDialogBuilder.setTitle("마커 삭제");
//
//        alertDialogBuilder
//                .setMessage("마커를 삭제하시겠습니까?")
//                .setCancelable(false)
//                .setPositiveButton("삭제",
//                        new DialogInterface.OnClickListener() {
//                            public void onClick(
//                                    DialogInterface dialog, int id) {
//                                marker.remove();
//                            }
//                        })
//                .setNegativeButton("취소",
//                        new DialogInterface.OnClickListener() {
//                            public void onClick(
//                                    DialogInterface dialog, int id) {
//                                // 다이얼로그를 취소한다
//                                dialog.cancel();
//                            }
//                        });
//        AlertDialog.Builder alertDialogBuilder2 = new AlertDialog.Builder(context);
//
//        alertDialogBuilder2.setTitle("마커 등록");
//
//        alertDialogBuilder2
//                .setMessage("경계에 등록 하시겠습니까?")
//                .setCancelable(false)
//                .setPositiveButton("등록",
//                        new DialogInterface.OnClickListener() {
//                            public void onClick(
//                                    DialogInterface dialog, int id) {
//                                marker.remove();
//                            }
//                        })
//                .setNegativeButton("취소",
//                        new DialogInterface.OnClickListener() {
//                            public void onClick(
//                                    DialogInterface dialog, int id) {
//                                // 다이얼로그를 취소한다
//                                dialog.cancel();
//                            }
//                        });
//
//
//        // 다이얼로그 생성
//        AlertDialog alertDialog = alertDialogBuilder.create();
//        AlertDialog alertDialog2 = alertDialogBuilder2.create();
//
//// 다이얼로그 보여주기
//        alertDialog.show();
//// 다이얼로그 보여주기
//        alertDialog2.show();
 
        return true;
    }
 
 
 
    //이제 마지막이다. convex hull 알고리즘을 활용해보았다.
    //http://woowabros.github.io/experience/2018/03/31/hello-geofence.html(이 부분을 참고하면, 비슷한 방식의 문제해결 방법을 볼 수 있다.)
    static int N = 0;
    static Point[] POINTS = new Point[20];
 
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void jugementClicked(View view) {
        //클릭할때마다 초기화를 해주자.
        POINTS = new Point[20];
        N = 0;
        //나의 현재 위치를 가져오자.
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE_PERMISSIONS);
            return;
        }
        mFusedLocationClient.getLastLocation().addOnSuccessListener(thisnew OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if(location != null){
                    //가져온 위치를 배열에 저장한다.
                    POINTS[N++= new Point(location.getLatitude() * 10000, location.getLongitude()*10000);
                }
                else{
                    mMap.animateCamera(CameraUpdateFactory.zoomTo(10.0f));
                }
            }
        });
 
 
        //데이터베이스의 위치를 가져오자.
        MemoDbHelper dbHelper = MemoDbHelper.getInstance(this);
        //커서에 담아서
        Cursor cursor =  dbHelper.getReadableDatabase().query(MemoContract.MemoEntry.TABLE_NAME, nullnullnull,null,null,null,null);
        //전체를 배열에 담아준다.
        while(cursor.moveToNext()){
            String lat = cursor.getString(cursor.getColumnIndexOrThrow(MemoContract.MemoEntry.COLUMN_NAME_LAT));
            String lng = cursor.getString(cursor.getColumnIndexOrThrow(MemoContract.MemoEntry.COLUMN_NAME_LNG));
            POINTS[N++= new Point(Double.parseDouble(lat) * 10000, Double.parseDouble(lng) * 10000);
        }
 
        //내 위치는 따로 저장해준다.
        Point MY_POINTS = POINTS[0];
        //y를 우선으로 '/'처럼 아래에서 위로 쭉 정렬을 해준다.
        Arrays.sort(POINTS,0 , N, new Comparator<Point>() {
            @Override
            public int compare(Point a, Point b) {
                if (a.y != b.y) {
                    if(a.y < b.y){
                        return -1;
                    }
                    else{
                        return 1;
                    }
                }
                if(a.x < b.x)
                    return -1;
                return 1;
            }
        });
 
        //이제 0을 기준으로 상대 위치를 새롭게 정의해준다.(이를 위해서 아래를 우선적으로 정렬한 것이다.
        for (int i = 1; i < N; i++) {
            POINTS[i].p = POINTS[i].x - POINTS[0].x;
            POINTS[i].q = POINTS[i].y - POINTS[0].y;
        }
 
        //이제 기준점 0 을 제외한 것들을 상대위치를 활용하여 정렬
        Arrays.sort(POINTS,1 , N-1new Comparator<Point>() {
            @Override
            public int compare(Point a, Point b) {
                if(a.q*b.p != a.p*b.q){
                    if(a.q*b.p < a.p*b.q)
                        return -1;
                    else
                        return 1;
                }
                if (a.y != b.y) {
                    if(a.y < b.y){
                        return -1;
                    }
                    else{
                        return 1;
                    }
                }
                if(a.x < b.x)
                    return -1;
                return 1;
            }
        });
 
        //스택에는 데이터를 절약하기 위해서 index만 담아준다.
        Stack<Integer> stack = new Stack<>();
        stack.add(0);
        stack.add(1);
 
        //모든 데이터가 스택에 들어갈 수 있도록 전체 반복
        for (int i = 2; i < N; i++) {
            //사이즈가 2보다 크면
            while(stack.size() >= 2){
                int first = stack.pop();
                int second = stack.peek();
                //들어있는 점들을 확인하여서 가장 외부의 점인지를 확인한다.
                long ccw = find_ccw(POINTS[first], POINTS[second], POINTS[i]);
                if (ccw > 0) {
                    //맞으면 stack에 담아준다.
                    stack.add(first);
                    break;
                }
            }
            stack.add(i);
        }
        
        //이제 나의 위치가 영역의 내부인지 외부인지 확인을 해주자.
        boolean isInside = true;
        for(int i=0;i<stack.size();i++){
            if(POINTS[stack.get(i)].x == MY_POINTS.x && POINTS[stack.get(i)].y == MY_POINTS.y){
                isInside = false;
            }
        }
 
        
        //아래는 위의 bool 값을 활용해서 메시지 창을 띄우는 부분이다.
        if(isInside){
            final Context context = this;
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
 
            alertDialogBuilder.setTitle("위험경보");
 
            alertDialogBuilder
                    .setMessage("위험지역에 위치하였습니다.")
                    .setCancelable(false)
                    .setPositiveButton("삭제",
                            new DialogInterface.OnClickListener() {
                                public void onClick(
                                        DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            })
                    .setNegativeButton("취소",
                            new DialogInterface.OnClickListener() {
                                public void onClick(
                                        DialogInterface dialog, int id) {
                                    // 다이얼로그를 취소한다
                                    dialog.cancel();
                                }
                            });
 
            // 다이얼로그 생성
            AlertDialog alertDialog = alertDialogBuilder.create();
            alertDialog.show();
        }
        else{
            final Context context = this;
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
 
            alertDialogBuilder.setTitle("경보 아님");
 
            alertDialogBuilder
                    .setMessage("경보가 아니에요")
                    .setCancelable(false)
                    .setPositiveButton("삭제",
                            new DialogInterface.OnClickListener() {
                                public void onClick(
                                        DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            })
                    .setNegativeButton("취소",
                            new DialogInterface.OnClickListener() {
                                public void onClick(
                                        DialogInterface dialog, int id) {
                                    // 다이얼로그를 취소한다
                                    dialog.cancel();
                                }
                            });
 
            // 다이얼로그 생성
            AlertDialog alertDialog = alertDialogBuilder.create();
            alertDialog.show();
        }
    }
 
    protected static long find_ccw(Point a, Point b, Point c) {
        return (long)(b.x - a.x) * (long)(c.y - a.y) - (long)(c.x - a.x) * (long)(b.y - a.y);
    }
 
    static class Point {
        long x, y;
        //기준점으로부터의 상대 위치
        long p,q;
 
        public Point(double x, double y) {
            this.x = (long) x;
            this.y = (long) y;
            p=1;
            q=0;
        }
 
        public Point(double x, double y, long p, long q){
            this.x = (long) x;
            this.y = (long) y;
            this.p=p;
            this.q=q;
        }
 
        public Point(long x, long y) {
            this.x = x;
            this.y = y;
            p=1;
            q=0;
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<!--activity_maps.xml-->
 
<?xml version="1.0" encoding="utf-8"?>
 
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_height="match_parent"
    android:layout_width="match_parent"
    >
 
    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="88dp"
        android:onClick="jugementClicked"
        android:text="경계 내부 체크"
        map:layout_constraintBottom_toBottomOf="parent"
        map:layout_constraintEnd_toEndOf="parent" />
 
    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:onClick="onLastLocationButtonClicked"
        android:text="GPS"
        map:layout_constraintBottom_toTopOf="@+id/button4"
        map:layout_constraintEnd_toEndOf="parent" />
 
    <Button
        android:id="@+id/boundaryMarkerButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:onClick="onBoundaryMarkerButtonClicked"
        android:text="경계 보기"
        map:layout_constraintBottom_toTopOf="@+id/button3"
        map:layout_constraintEnd_toEndOf="parent" />
 
    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginBottom="8dp"
        android:onClick="moveMainActivity"
        android:text="돌아가기"
        map:layout_constraintBottom_toBottomOf="parent"
        map:layout_constraintStart_toStartOf="parent" />
 
    <fragment
        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"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="0dp" />
 
    <EditText
        android:id="@+id/editPlace"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:ems="12"
        android:hint="찾는 장소"
        map:layout_constraintStart_toStartOf="parent"
        map:layout_constraintTop_toTopOf="parent" />
 
    <Button
        android:id="@+id/button6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="검색"
        android:onClick="searchButtonClicked"
        map:layout_constraintEnd_toEndOf="parent"
        map:layout_constraintStart_toEndOf="@+id/editPlace"
        map:layout_constraintTop_toTopOf="parent" />
 
</androidx.constraintlayout.widget.ConstraintLayout>
 
cs





+) 추가적으로 AndroidManifest.xml에서 상위 하위 화면을 나눠주었는데, android:parentActivity를 활용해서 부모 Activity를 선언함으로서 화면간 이동이 조금은 더 편하게 해줄 수 있었다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!--AndroidManifest-->
 
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.newmap">
    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 
    <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=".MarkerListActivity"
            android:parentActivityName=".MainActivity" />
        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />
 
        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps"></activity>
        <activity
            android:name=".MarkerAddActivity"
            android:parentActivityName=".MainActivity" />
        <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>
cs


 2. 소스코드


https://github.com/kyun1016/algorithm/tree/master/NewMap


 3. 참고


* 안드로이드 생존코딩

- db 활용

https://www.youtube.com/watch?v=lf6GOaTRCgA&t=84s

- 레이아웃 활용하는 방법

https://youtu.be/rXnbsB_TPPU

- 메뉴 구현하기

https://youtu.be/DT9OL98q6Qw

-구글 api 활용하는 방법

https://youtu.be/OUrqMB7iNPo


* Programming Experts

- Removing markers

https://youtu.be/krFjb-gJeTw


* LifeSoft

- 검색을 통해 위치 가져오는 방법

https://youtu.be/VvddqHsdBvQ


* 우아한형제들 박민철

- Geo-fence 관련한 라이브러리(JTS)

http://woowabros.github.io/experience/2018/03/31/hello-geofence.html


* 백준(BOJ)

- 볼록 껍질(Convex Hull) 알고리즘

https://www.acmicpc.net/problem/1708

https://www.crocus.co.kr/1288



+ Recent posts