안드로이드 개발 질문/답변
(글 수 45,052)
안드로이드인데요
전체적으로 위치를 눌렀을때 위치와 좌표를 찍고
저장을 눌렀을때 디비가 열리고 위치가 저장 되는건데
디비 부분에
07-05 16:28:59.583: ERROR/Database(30199): Failure 1 (table users
already exists) on 0x1d1c10 when preparing 'create table users(ln
double,lo double);'.
07-05 16:28:59.583: ERROR/Database(30199): Failure 1 (unrecognized token: "'0.0);") on 0x1d1c10 when preparing 'insert into users values('0.0','0.0);'.
이렇게 두줄이 표시되는데 뭔가 값이 잘못설정된거같은데 어떻게 고치면 되는지요?^^
package com.android.location1;
import java.io.*;
import java.util.*;
import android.app.*;
import android.os.Bundle;
import android.content.*;
import android.graphics.drawable.Drawable;
import android.location.*;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.content.Intent;
import android.view.View.OnClickListener;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
//import android.widget.ViewFlipper;
public class LocationDemo extends MapActivity implements LocationListener,
OnClickListener {
protected static final String T_NAME = null;
// MapActivity 상속, implements 상속 사용
// final MapView mapView = (MapView)findViewById(R.id.mapview);
// mapView.setBuiltInZoomControls(true);
private MapController mapController; // map에 관한 컨트롤
private LocationManager locManager; // gps 위치 매니저
Geocoder geoCoder; // 위치값 주소로 변경
private Location myLocation = null;
double latPoint = 0;
double lngPoint = 0;
SQLiteDatabase _DB;
public BaseAdapter Adapter = null;
private Activity _Activity = null;
Cursor c;
public ArrayList<HashMap<String, String>> _DataSource = new ArrayList<HashMap<String, String>>();
// Intent intent; //레이아웃을 사용하기 위한 INTENT
// float speed = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// LocationListener의 핸들을 얻음
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// GPS로 부터 위치정보를 업데이트 요청, 1초마다
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,
0, this);
// 기지국으로 부터 위치정보를 업데이트 요청
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10,
0, this);
// 주소를 확인하기 위한 Geocoder KOREA 와 KOREAN 둘다 가능
geoCoder = new Geocoder(this, Locale.KOREAN);
final Button gpsButton = (Button) findViewById(R.id.gpsButton); // id를
// 이용해
// 버튼 사용
gpsButton.setOnClickListener(new Button.OnClickListener() { // 버튼 클릭시
// 이벤트
public void onClick(View v) {
GetLocations(); // GetLocations()실행
Log.d("location", "button pressed");
}
});
Button ok_btn = (Button) findViewById(R.id.ok_btn); // 보기 버튼
ok_btn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) { // GpsView클레스 호출
Toast.makeText(LocationDemo.this, "button pressed.", 3).show();
Log.e("", "=====>");
Intent intent = new Intent(LocationDemo.this, GpsView.class);
// startActivity(intent);
startActivityForResult(intent, 1);
}
});
Button next_btn = (Button) findViewById(R.id.next_btn);
next_btn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) { // GpsView클레스 호출
Toast.makeText(LocationDemo.this, "button pressed.", 3).show();
// edit_id=(EditText)findViewById(R.id.edit_id);
// edit_pw=(EditText)findViewById(R.id.edit_pw);
// btn_login=(Button)findViewById(R.id.btn_login);
// btn_login.setOnClickListener(this);
openDatabase();
insertDatabase();
loginQuery();
}
});
}
/*
* public void TodoList(Activity AActivity) {
*
* _Activity = AActivity; _DB = _Activity.openOrCreateDatabase("M_mode",
* Context.MODE_PRIVATE,null); // 데이터베이스 생성
*
* createTable(); // 테이블 생성 메소드 호출 Adapter = new SimpleAdapter(_Activity,
* _DataSource, android.R.layout.simple_list_item_multiple_choice, new
* String[] { "ID", "Title", "longitude", "longitude" }, new int[] {
* android.R.id.text1, android.R.id.text2 }); Refresh(); }
*
* public void Append(double latPoint, double lngPoint) { // TodoList라는 테이블에
* 텍스트값, 위도, 경도값 저장 _DB.execSQL("Insert into TodoList values('"+ latPoint +
* "', '" + lngPoint + "')"); }
*
* // Add.java에서 입력한 텍스트값과 위도, 경도값을 받아 데이터베이스에 저장 public void Delete(int
* index) { String str = String.valueOf(index); String sql = "DELETE FROM ";
* sql += T_NAME; sql += " WHERE _id = "; sql += str; }
*
* // 삭제 메소드 list.java 파일에서 체크된 리스트 아이템을 찾아 삭제 명령을 내림 public void Refresh()
* { Cursor _Cursor = _DB.rawQuery("Select * from TodoList", null); if
* (_Cursor.moveToFirst()) { do { HashMap<String, String> _Item = new
* HashMap<String, String>(); _Item.put("ID",
* _Cursor.getString(0).toString()); _DataSource.add(_Item); } while
* (_Cursor.moveToNext()); } Adapter.notifyDataSetChanged(); // 리스트 뷰 변경을
* 갱신. }
*
* // ListView와 연동해 화면에 뿌려주는 메소드 private void createTable() { // TODO
* Auto-generated method stub String sql = "create table "; sql += T_NAME;
* sql += "(_id integer primary key autoincrement, " + "Title varchar," +
* "latPoint double, " + "lngPoint double)"; try { _DB.execSQL(sql); } catch
* (SQLException se) { } }
*
* // 만들어진 데이터베이스에 테이블을 생성
*/
void openDatabase() {
try {
_DB = this.openOrCreateDatabase("users", MODE_PRIVATE, null);
// _DB = SQLiteDatabase.openDatabase("data/data/com.db.dbt/TestDB1",
// null, SQLiteDatabase.CREATE_IF_NECESSARY);
Toast.makeText(LocationDemo.this, "DB was opened!", 1).show();
} catch (Exception e) {
// TODO: handle exception
}
}
void insertDatabase() {
// TODO Auto-generated method stub
_DB.beginTransaction(); // 복수의 data를 insert할때 속도 향상을 위해서 사용하는
// method
try {
_DB.execSQL("create table users(" + "ln double," + "lo double);");
_DB.setTransactionSuccessful(); // 복수의 data를 insert할때 속도 향상을
// 위해서 사용하는 method
} catch (Exception e) {
// TODO: handle exception
} finally {
_DB.endTransaction();
}
//
_DB.beginTransaction();
try {
// ('" + ATitle + "', '" + latitude + "', '"+longitude +"')");
_DB.execSQL("insert into users values('" + latPoint + "','"
+ lngPoint + ");");
_DB.setTransactionSuccessful();
// Toast.makeText(this, "id일치!!", Toast.LENGTH_LONG).show();
}
catch (Exception e) {
// TODO: handle exception
Toast.makeText(LocationDemo.this, e.getMessage(), 1).show();
} finally {
_DB.endTransaction();
}
}
public void loginQuery() {
// String userid = edit_id.getText().toString();
// String userpass = edit_pw.getText().toString();
String[] columns = { "ln", "lo" };
c = _DB.rawQuery("SELECT ln, lo FROM users", null);
String result = "";
Toast.makeText(LocationDemo.this, "ddddddddddddddddddddddddddddddddd",
Toast.LENGTH_LONG);
try {
c.moveToFirst();
columns[0] = c.getString(0);
columns[1] = c.getString(1);
result = ("위도:" + columns[0] + "경도:" + columns[1] + "\n");
Toast.makeText(LocationDemo.this, result, Toast.LENGTH_SHORT)
.show();
// Toast.makeText(this, userpass, Toast.LENGTH_LONG).show();
// if (userid.equals(columns[0])) {
// Toast.makeText(this, "id일치!!", Toast.LENGTH_LONG)
// .show();
// if (userpass.equals(columns[1])) {
// Toast.makeText(this, "pw일치!!", Toast.LENGTH_LONG)
// .show();
//
// } else {
// Toast.makeText(this, "pw불일치", Toast.LENGTH_LONG)
// .show();
// }
// } else {
// Toast.makeText(this, "불일치", Toast.LENGTH_LONG).show();
// }
c.moveToNext();
// columns[0] = c.getString(0);
// columns[1] = c.getString(1);
// result = ("id:"+columns[0]+"pw:"+columns[1]+"\n");
// Toast.makeText(this, result , Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// Toast.makeText(this, e.getMessage(), 1).show();
}
c.close();
_DB.close();
}
void GetLocations() {
// 텍스트뷰를 찾음
TextView latText = (TextView) findViewById(R.id.tvLatitude);
TextView lngText = (TextView) findViewById(R.id.tvLongitude);
// TextView speedText = (TextView) findViewById(R.id.tvSpeed);
TextView jusoText = (TextView) findViewById(R.id.tvAddress);
StringBuffer juso = new StringBuffer();
if (myLocation != null) { // 위도값,경도값 저장
latPoint = myLocation.getLatitude();
lngPoint = myLocation.getLongitude();
// speed = (float)(myLocation.getSpeed() * 3.6);
// ======================================== 마커 표시부분
MapView mapView = (MapView) findViewById(R.id.mapview); // 맵을 불러온다
mapView.setBuiltInZoomControls(true); // 줌컨트롤을 활성
List<Overlay> mapOverlays = mapView.getOverlays(); // 오버레이 사용
Drawable drawable = this.getResources().getDrawable(R.drawable.ese); // 이미지
// 파일
// 등록
MyItemizedOverlay itemizedoverlay = new MyItemizedOverlay(drawable,
this); // 오버레이에// 등록
GeoPoint point = new GeoPoint((int) (latPoint * 1E6),
(int) (lngPoint * 1E6));
OverlayItem overlayitem = new OverlayItem(point, "", "dd"); // 오버레이
// 클릭할시
itemizedoverlay.addOverlay(overlayitem);
mapController = mapView.getController();
mapController.setCenter(point); // 맵을 가운데로 움직여준다
mapController.setZoom(15); // 줌을 해줌
mapController.animateTo(point); // 이미지를 표시해줌
mapOverlays.add(itemizedoverlay);
// ======================================== 마커 표시부분
try {
// 위도,경도를 이용하여 현재 위치의 주소를 가져온다.
List<Address> addresses;
addresses = geoCoder.getFromLocation(latPoint, lngPoint, 1);
for (Address addr : addresses) {
int index = addr.getMaxAddressLineIndex();
for (int i = 0; i <= index; i++) {
juso.append(addr.getAddressLine(i));
juso.append(" ");
}
juso.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 받아온 값을 텍스트에 보여준다
latText.setText(String.valueOf(latPoint));
lngText.setText(String.valueOf(lngPoint));
// speedText.setText(String.valueOf(speed));
jusoText.setText(String.valueOf(juso));
}
public void onLocationChanged(Location location) {
GetLocations();
myLocation = location;
}
public void onProviderDisabled(String s) {
}
public void onProviderEnabled(String s) {
}
public void onStatusChanged(String s, int i, Bundle bundle) {
}
// 메뉴버튼 누를경우
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, 1, 0, "소개");
menu.add(0, 2, 0, "종료");
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
new AlertDialog.Builder(this)
.setTitle("안드로이드과제")
.setMessage("과제어플입니다.\n" + "미완성입니다.\n" + "www.diycad.com")
.setIcon(R.drawable.icon)
.setPositiveButton("닫기",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
}).show();
return true;
case 2:
finish();
System.exit(0);
return true;
}
return false;
}
@Override
// 키 버튼 처리
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) { // 뒤로가기 버튼 입력시 종료
case KeyEvent.KEYCODE_BACK:
_DB.close();
finish();
System.exit(0);
case KeyEvent.KEYCODE_HOME: // 홈키 엑티비티 종료
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
am.restartPackage(getPackageName());
}
return super.onKeyDown(keyCode, event);
}
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}




07-05 16:28:59.583: ERROR/Database(30199): Failure 1 (table users already exists) on 0x1d1c10 when preparing 'create table users(ln double,lo double);'.
users 라는 테이블이 이미 만들어져있네요.
07-05 16:28:59.583: ERROR/Database(30199): Failure 1 (unrecognized token: "'0.0);") on 0x1d1c10 when preparing 'insert into users values('0.0','0.0);'.
(0.0,0.0) 값을 넣으려고 하는데 0.0을 못 알아 먹겠데요.