오랜만에 포스팅입니다. 지하철 역 클릭 시 이벤트 구현하기 1편은 여기에서 보실 수 있습니다.
https://hyongdoc.tistory.com/170
[안드로이드] 지하철 역 클릭 시 이벤트 구현하기 1편
대중교통을 이용하는 사람이라면 누구나 사용하는 지하철 앱. 지하철 앱을 사용하다보면, 지하철 노선도에서 각 역을 클릭하여 출발지 지정을 하는 것을 볼 수 있는데, 이번 포스팅에서는 바로 그 기능을 다루는..
hyongdoc.tistory.com
지하철역이 정말 많습니다. 이 기능을 이용해 앱을 제작할 때 일일이 노가다로 100개가 넘는 지하철 역을 모두 입력했는데요. 정~말 개고생에 개노가다라는 점 미리 말씀드립니다..
아무튼, sql파일로 데이터들이 다 저장되었다고 했을 때 이를 안드로이드에서 읽는 방법에 대해 알아보겠습니다. 맥북이 포맷되어버려서 상세히 다루기 어려운 점 역시 미리 말씀드립니다.
먼저 안드로이드 프로젝트의 assets폴더에 해당 sql파일을 복붙하여 붙여넣습니다. 그 후 구현할 페이지에 이미지뷰로 지하철 이미지를 삽입하고, 아래 코드를 붙여넣습니다.
이 과정에서, 이미지 크기가 깨지지 않게, 해당 좌표값을 유지하면서 삽입되어야하는 점 유의해주시면 됩니다.
참고로 이미지가 너무 크면 렉이 걸릴 수 있는데 이 부분은 관련 자료 찾아보시면 스택오버플로우에 아주 많으니 생략하겠습니다.
1. SubwayDatabaseHelper.java : sql연동시키는 클래스
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
|
package com.tistory.hyongdoc.threemen;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class SubwayDatabaseHelper extends SQLiteOpenHelper {
String DB_PATH = null;
private static String DB_NAME = "subwaystations"; // SQLLite 파일명 이름
private SQLiteDatabase myDataBase;
private final Context myContext;
public SubwayDatabaseHelper(Context context) {
super(context, DB_NAME, null, 10);
this.myContext = context;
this.DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
Log.e("Path 1", DB_PATH);
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[10];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion)
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) {
return myDataBase.query("subwayData", null, null, null, null, null, null);
}
}
|
cs |
2. MainActivity.java : 필요한 부분만 발췌했습니다. 원하시는 입맛대로 사용하시면 됩니다.
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
|
/////////////////////////////////////////////////////////////////////////////
Cursor c = null;
SubwayDatabaseHelper myDbHelper = new SubwayDatabaseHelper(MainActivity.this); // Reading SQLite database.
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
c = myDbHelper.query("subwayData", null, null, null, null, null, null); // SQLDataRead
final SubsamplingScaleImageView imageView = (SubsamplingScaleImageView) findViewById(R.id.subwayMap); // 지하철역 이미지뷰
//Refer to ID value.
final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() { // gesture 디텍팅으로 지하철 위치 읽기
@Override
public boolean onSingleTapUp(MotionEvent ev) {
if (imageView.isReady()) {
PointF sCoord = imageView.viewToSourceCoord(ev.getX(), ev.getY());
int x_cor = (int) sCoord.x;
int y_cor = (int) sCoord.y;
// Loop for finding the station.
if (c.moveToFirst()) {
do {
if ((x_cor > c.getInt(2)) && (x_cor < c.getInt(4)) && (y_cor > c.getInt(3)) && (y_cor < c.getInt(5))) {
String targetStation = c.getString(1)); // 유저가 클릭한 지하철역
} // send Station Name (column 1)
} while (c.moveToNext());
}
/////////////////////////////////////////////////////////////////////////////
}
return super.onSingleTapUp(ev);
}
});
|
cs |
'Developer > Android, Java' 카테고리의 다른 글
[안드로이드] Fragment 로 데이터 전달하기 (262) | 2019.05.23 |
---|---|
[안드로이드] Retrofit에 Header 추가하여 요청하기 (279) | 2019.05.23 |
[안드로이드] View 터치 시 터치 이벤트 구현하기 (266) | 2019.05.22 |
[안드로이드] ArrayList<Object> 인텐트 넘기는 방법 (284) | 2019.05.22 |
[안드로이드] ScrollView 안에 RecyclerView 을 넣을 수 있나요? (281) | 2019.05.22 |
댓글