添加标记从SQLite和中心映射/变焦适合他们(Android版) [英] Add markers to map from SQLite, and center/fit them in zoom (Android)

查看:149
本文介绍了添加标记从SQLite和中心映射/变焦适合他们(Android版)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的需要帮助填充与存储在我的数据库坐标标记的地图。我从SQLite的填充列表视图的工作,我可以添加标记到地图,但我无法弄清楚如何从SQLite数据库添加标记。另外,如果我能得到一些帮助,中心屏幕上的标记,并在他们都适合缩放,这将是真棒!我的继承人code迄今:

* 更新code 的*

ALLMAPACTIVITY

 公共类allmapactivity扩展MapActivity {
GeoPoint的GeoP;
图形页面mapV;
私人SQLiteAdapter mySQLiteAdapter;
公众的ArrayList<整数GT;纬度=新的ArrayList<整数GT;();
公众的ArrayList<整数GT;经度=新的ArrayList<整数GT;();@覆盖
保护无效的onCreate(捆绑savedInstanceState){
 // TODO自动生成方法存根
 super.onCreate(savedInstanceState);
 的setContentView(R.layout.map);
 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
 requestWindowFeature(Window.FEATURE_NO_TITLE);
 mapV =(图形页面)findViewById(R.id.mapview);
 mapV.displayZoomControls(真);
 mapV.setBuiltInZoomControls(真);
 mapV.setSatellite(假);最终MapController mController = mapV.getController();清单<&叠加GT; mapOverlays = mapV.getOverlays();
可绘制可绘制= this.getResources()getDrawable(R.drawable.pin)。mySQLiteAdapter =新SQLiteAdapter(getApplicationContext());如果(!mySQLiteAdapter.isEmpty())
{
光标initcursor = mySQLiteAdapter.queueAll5();
initcursor.moveToFirst();
的for(int i = 0; I< initcursor.getCount();我++)
{
    HelloItemizedOverlay itemizedoverlay =
             新HelloItemizedOverlay(绘制,allmapactivity.this);
    INT纬度=(INT)(initcursor.getDouble(initcursor.getColumnIndex(Content11))* 1E6);
    INT LON =(INT)(initcursor.getDouble(initcursor.getColumnIndex(Content12))* 1E6);
        latitude.add(LAT);
        longitude.add(LON);
    GeoPoint对象的GeoPoint =新的GeoPoint(纬度,经度);
    串savedtitle = initcursor.getString(initcursor.getColumnIndex(Content9));
    串savedtext = initcursor.getString(initcursor.getColumnIndex(Content10));
     OverlayItem overlayitem =新OverlayItem(GeoPoint对象,savedtitle,savedtext);
     itemizedoverlay.addOverlay(overlayitem);
     mapOverlays.add(itemizedoverlay);
     initcursor.moveToNext();
  }
  }        INT latSum = 0;
双latAverage = 0; 对于(整数latitudeValue:纬度)
 {
  latSum = latSum + latitudeValue;
 } latAverage =(双)latSum / latitude.size();
 INT lonSum = 0;
 双lonAverage = 0;对于(整数longitudeValue:经度)
{
 lonSum = lonSum + longitudeValue;
}lonAverage =(双)lonSum / longitude.size();    GeoPoint的中心=新的GeoPoint((int)的latAverage,(INT)lonAverage);    mController.animateTo(中心);
}@覆盖
保护布尔isRouteDisplayed(){   // TODO自动生成方法存根返回false;
}}

SQLITEADAPTER

 公共类SQLiteAdapter { 公共静态最后弦乐MYDATABASE_NAME =MY_DATABASE; 公共静态最后弦乐MYDATABASE_TABLE =MY_TABLE; 公共静态最终诠释MYDATABASE_VERSION = 1; 公共静态最后弦乐KEY_ID =_id; 公共静态最后弦乐KEY_CONTENT1 =内容1; 公共静态最后弦乐KEY_CONTENT3 =Content3; 公共静态最后弦乐KEY_CONTENT4 =Content4; 公共静态最后弦乐KEY_CONTENT5 =Content5; 公共静态最后弦乐KEY_CONTENT6 =Content6; 公共静态最后弦乐KEY_CONTENT7 =Content7; 公共静态最后弦乐KEY_CONTENT8 =Content8; 公共静态最后弦乐KEY_CONTENT9 =Content9; 公共静态最后弦乐KEY_CONTENT10 =Content10; 公共静态最后弦乐KEY_CONTENT11 =Content11; 公共静态最后弦乐KEY_CONTENT12 =Content12;
 私有静态最后弦乐SCRIPT_CREATE_DATABASE =  CREATE TABLE+ MYDATABASE_TABLE +(  + KEY_ID +整数主键自动增量  + KEY_CONTENT1 +文本不为空,  + KEY_CONTENT3 +文本不为空,  + KEY_CONTENT4 +文本不为空,  + KEY_CONTENT5 +文本不为空,  + KEY_CONTENT6 +文本不为空,  + KEY_CONTENT7 +文本不为空,  + KEY_CONTENT8 +文本不为空,  + KEY_CONTENT9 +文本不为空,  + KEY_CONTENT10 +文本不为空,  + KEY_CONTENT11 +文本不为空,  + KEY_CONTENT12 +文字NOT NULL);;私有静态最后弦乐足迹= NULL;私人SQLiteHelper sqLiteHelper;私人SQLiteDatabase sqLiteDatabase;私人上下文的背景下;公共SQLiteAdapter(上下文C){上下文= C;} 公共SQLiteAdapter openToRead()抛出android.database.SQLException {  sqLiteHelper =新SQLiteHelper(背景下,MYDATABASE_NAME,空,MYDATABASE_VERSION);  sqLiteDatabase = sqLiteHelper.getReadableDatabase();  返回此; } 公共SQLiteAdapter openToWrite()抛出android.database.SQLException {  sqLiteHelper =新SQLiteHelper(背景下,MYDATABASE_NAME,空,MYDATABASE_VERSION);  sqLiteDatabase = sqLiteHelper.getWritableDatabase();  返回此; } 公共无效的close(){  sqLiteHelper.close(); } 众长插入(字符串内容1,字符串content3,
                字符串content4,字符串content5,字符串content6,字符串content7,
                字符串content8,字符串content9,字符串content10,字符串content11,字符串content12){  ContentValues​​ contentValues​​ =新ContentValues​​();  contentValues​​.put(KEY_CONTENT1,内容1);  contentValues​​.put(KEY_CONTENT3,content3);  contentValues​​.put(KEY_CONTENT4,content4);  contentValues​​.put(KEY_CONTENT5,content5);  contentValues​​.put(KEY_CONTENT6,content6);  contentValues​​.put(KEY_CONTENT7,content7);  contentValues​​.put(KEY_CONTENT8,content8);  contentValues​​.put(KEY_CONTENT9,content9);  contentValues​​.put(KEY_CONTENT10,content10);  contentValues​​.put(KEY_CONTENT11,content11);  contentValues​​.put(KEY_CONTENT12,content12);  返回sqLiteDatabase.insert(MYDATABASE_TABLE,空,contentValues​​); } 公众诠释deleterow(){
 共享preferences设置= context.getShared preferences(足迹,0);
 串的itemId = settings.getString(columnvalue5,);  返回sqLiteDatabase.delete(MYDATABASE_TABLE,KEY_CONTENT1 +=+,新的String [] {}的itemId?); }
 公众诠释deleterow2(){
 共享preferences设置= context.getShared preferences(足迹,0);
 串的itemId = settings.getString(columnvalue6,);
 串itemId2 = settings.getString(columnvalue7,);  返回sqLiteDatabase.delete(MYDATABASE_TABLE,
          KEY_CONTENT1 +=? +和+ KEY_CONTENT3 +=?,新的String [] {的itemId,itemId2}); }
 公众诠释deleterow3(){
 共享preferences设置= context.getShared preferences(足迹,0);
 串的itemId = settings.getString(columnvalue8,);  返回sqLiteDatabase.delete(MYDATABASE_TABLE,KEY_ID +=+,新的String [] {}的itemId?); }
 公共光标queueAll(){ 的String [] =列新的String [] {KEY_ID,KEY_CONTENT1,和(+ KEY_CONTENT6 +),KEY_CONTENT9}; 光标光标= sqLiteDatabase.query(MYDATABASE_TABLE,列, NULL,NULL,KEY_CONTENT1,空,KEY_CONTENT9 +DESC);
  返回游标; } 公共光标queueAll2(){ 共享preferences设置= context.getShared preferences(足迹,0);
 串的itemId = settings.getString(columnvalue1,);  的String [] =列新的String [] {KEY_ID,KEY_CONTENT1,KEY_CONTENT3,和(+ KEY_CONTENT6 +),KEY_CONTENT9,KEY_CONTENT10};  光标光标= sqLiteDatabase.query(MYDATABASE_TABLE,列,          KEY_CONTENT1 +=+,新的String [] {}的itemId,KEY_CONTENT3,空,KEY_CONTENT9 +降序),?;
  返回游标; } 公共光标queueAll3(){ 共享preferences设置= context.getShared preferences(足迹,0);
 串的itemId = settings.getString(columnvalue1,);
 串itemId2 = settings.getString(columnvalue2,);  的String [] =列新的String [] {KEY_ID,KEY_CONTENT1,KEY_CONTENT3,KEY_CONTENT4,KEY_CONTENT5,KEY_CONTENT6,
                                  KEY_CONTENT7,KEY_CONTENT8,KEY_CONTENT9,KEY_CONTENT11,KEY_CONTENT12};  光标光标= sqLiteDatabase.query(MYDATABASE_TABLE,列,          KEY_CONTENT1 +=? +和+ KEY_CONTENT3 +=? ,新的String [] {的itemId,itemId2},NULL,NULL,KEY_CONTENT9 +DESC);
  返回游标; }
 公共光标queueAll4(){  的String [] =列新的String [] {KEY_ID,和(+ KEY_CONTENT6 +),KEY_CONTENT9,KEY_CONTENT10};  光标光标= sqLiteDatabase.query(MYDATABASE_TABLE,列,          NULL,NULL,KEY_CONTENT10,空,KEY_CONTENT9 +DESC);
  返回游标; } 公共光标queueAll5(){  的String [] =列新的String [] {KEY_CONTENT9,KEY_CONTENT10,KEY_CONTENT11,KEY_CONTENT12};  光标光标= sqLiteDatabase.query(MYDATABASE_TABLE,列,          NULL,NULL,NULL,NULL,NULL);
  返回游标; } 公共布尔的isEmpty()
 {
 尝试{
 游标检查= sqLiteDatabase.query(MY_TABLE,新的String [] {Content11},NULL,NULL,NULL,NULL,NULL);
 }
 赶上(NullPointerException异常E)
 {
     返回true;
 }
 返回false;
 }
 公共类SQLiteHelper扩展SQLiteOpenHelper {  公共SQLiteHelper(上下文的背景下,字符串名称, CursorFactory工厂,诠释的版本){  超(背景下,名称,厂家,版本);  }  @覆盖  公共无效的onCreate(SQLiteDatabase DB){   // TODO自动生成方法存根  db.execSQL(SCRIPT_CREATE_DATABASE); }  @覆盖  公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){   // TODO自动生成方法存根  } }}

不幸的是,我得到一个强制关闭的错误与此code :(继承人的logcat的:

  07-22 19:14:33.918:E / AndroidRuntime(1330):致命异常:主要
07-22 19:14:33.918:E / AndroidRuntime(1330):了java.lang.RuntimeException:无法启动活动ComponentInfo {com.inn.footprint / com.inn.footprint.allmapactivity}:android.util.AndroidRuntimeException:requestFeature ()必须在添加内容之前调用
07-22 19:14:33.918:E / AndroidRuntime(1330):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
07-22 19:14:33.918:E / AndroidRuntime(1330):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
07-22 19:14:33.918:E / AndroidRuntime(1330):在android.app.ActivityThread.access $ 1500(ActivityThread.java:117)
07-22 19:14:33.918:E / AndroidRuntime(1330):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:931)
07-22 19:14:33.918:E / AndroidRuntime(1330):在android.os.Handler.dispatchMessage(Handler.java:99)
07-22 19:14:33.918:E / AndroidRuntime(1330):在android.os.Looper.loop(Looper.java:130)
07-22 19:14:33.918:E / AndroidRuntime(1330):在android.app.ActivityThread.main(ActivityThread.java:3683)
07-22 19:14:33.918:E / AndroidRuntime(1330):在java.lang.reflect.Method.invokeNative(本机方法)
07-22 19:14:33.918:E / AndroidRuntime(1330):在java.lang.reflect.Method.invoke(Method.java:507)
07-22 19:14:33.918:E / AndroidRuntime(1330):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:839)
07-22 19:14:33.918:E / AndroidRuntime(1330):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-22 19:14:33.918:E / AndroidRuntime(1330):在dalvik.system.NativeStart.main(本机方法)
07-22 19:14:33.918:E / AndroidRuntime(1330):android.util.AndroidRuntimeException:致requestFeature()必须添加内容之前调用
07-22 19:14:33.918:E / AndroidRuntime(1330):在com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:181)
07-22 19:14:33.918:E / AndroidRuntime(1330):在android.app.Activity.requestWindowFeature(Activity.java:2729)
07-22 19:14:33.918:E / AndroidRuntime(1330):在com.inn.footprint.allmapactivity.onCreate(allmapactivity.java:36)
07-22 19:14:33.918:E / AndroidRuntime(1330):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-22 19:14:33.918:E / AndroidRuntime(1330):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
07-22 19:14:33.918:E / AndroidRuntime(1330):11 ...更多


解决方案

下面NotesDbAdapter改编自记事本教程developer.android.com,认为它是一个数据库包装。我已经添加了额外的字段,如纬度,经度,这将是主键,即如何访问一个标记,你的标记将被存储的位置。然后按照这个code,我还提供了一个修改你的类allmapactivity是让所有的注意事项即标记在你的数据库,然后用它们来填充地图。这code肯定会工作,我已经测试过了!让我知道如果你需要进一步的建议!

干杯

  / *
*版权所有(C)2008年谷歌公司
*
*在Apache许可,2.0版(以下简称许可证);你不可以
*使用这个文件除了在遵守许可。您可能获得的副本
*许可在
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*除非适用法律要求或书面同意,软件
*许可下发布的分布在原样的基础,没有
*担​​保或任何形式的条件,无论是前preSS或暗示的保证。查看
*许可证特定语言的管理许可和限制下
*许可证。
* /
进口android.content.ContentValues​​;
进口android.content.Context;
进口android.database.Cursor;
进口android.database.SQLException;
进口android.database.sqlite.SQLiteDatabase;
进口android.database.sqlite.SQLiteOpenHelper;
进口android.util.Log;/ **
*简单的Notes数据库访问辅助类。定义了基本的CRUD操作
*在记事本的例子,并给出列出所有的笔记以及能力
*检索或修改特定的音符。
*
*本已经从通过本教程的第一个版本改进
*增加了更好的错误处理和利用也返回一个指针,而不是
采用内部类的集合(这是可扩展性较少而不是*
* 推荐的)。
* /
公共类NotesDbAdapter {公共静态最后弦乐KEY_TITLE =称号;
公共静态最后弦乐KEY_BODY =身体;
公共静态最后弦乐KEY_LAT =纬度;
公共静态最后弦乐KEY_LON =经度;私有静态最后弦乐TAG =NotesDbAdapter;
公共DatabaseHelper mDbHelper;
公共SQLiteDatabase MDB;/ **
 *数据库创建的SQL语句
 * /
私有静态最后弦乐DATABASE_CREATE =
    CREATE TABLE笔记(LAT REAL,REAL经度,标题为varchar(60),机身为varchar(300),PRIMARY KEY(纬度,经度));;私有静态最后弦乐DATABASE_NAME =数据;
私有静态最后弦乐DATABASE_TABLE =注意事项;
私有静态最终诠释DATABASE_VERSION = 2;私人最终上下文mCtx;私有静态类DatabaseHelper扩展SQLiteOpenHelper {    DatabaseHelper(上下文的背景下){
        超(背景下,DATABASE_NAME,空,DATABASE_VERSION);
    }    @覆盖
    公共无效的onCreate(SQLiteDatabase DB){        db.execSQL(DATABASE_CREATE);
    }    @覆盖
    公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
        Log.w(TAG,从版本升级数据库+ oldVersion +到
                + NEWVERSION +,这将摧毁所有旧数据);
        db.execSQL(DROP TABLE IF EXISTS笔记);
        的onCreate(DB);
    }
}/ **
 *构造函数 - 需要上下文允许数据库是
 *打开/创建
 *
 * @参数CTX在其中工作的上下文
 * /
公共NotesDbAdapter(上下文CTX){
    this.mCtx = CTX;
    打开();
}/ **
 *打开Notes数据库。如果不能打开,尝试创建一个新的
 *数据库的实例。如果它不能被创建,抛出异常来
 *信号故障
 *
 返回:此(自基准,允许这在被链接
 *初始化调用)
 * @throws SQLException - 如果该数据库可以既打开或创建
 * /
公共NotesDbAdapter的open()抛出的SQLException {
    mDbHelper =新DatabaseHelper(mCtx);
    MDB = mDbHelper.getWritableDatabase();
    返回此;
}公共无效的close(){
    mDbHelper.close();
}
/ **
 *使用提供标题和正文新的笔记。如果备忘
 *创建成功返回新的ROWID为笔记,否则返回
 * -1表示失败。
 *
 *参数标题注释的标题
 * @参数体的说明身体
 * @返回ROWID或-1,如果失败
 * /
众长createNote(双纬度,双LON,标题字符串,字符串体){
    ContentValues​​ initialValues​​ =新ContentValues​​();
    initialValues​​.put(KEY_LAT,LAT);
    initialValues​​.put(KEY_LON,LON);
    initialValues​​.put(KEY_TITLE,职称);
    initialValues​​.put(KEY_BODY,体);    返回mDb.insert(DATABASE_TABLE,空,initialValues​​);
}/ **
 *删除备忘与给定ROWID
 *
 * @参数ROWID值得注意的ID删除
 返回:如果是真的删除,否则为false
 * /
公共布尔deleteNote(双纬度,双LON){    返回mDb.delete(DATABASE_TABLE,KEY_LAT +=+纬度+和+ KEY_LON +=+经度,空)GT; 0;
}/ **
 *返回光标放在所有音符的数据库列表
 *
 * @返回光标在所有笔记
 * /
公共光标fetchAllNotes(){
    返回mDb.query(票据,新的String [] {KEY_LAT,KEY_LON,
            KEY_TITLE,KEY_BODY},NULL,NULL,NULL,NULL,NULL);
}/ **
 *返回位于给定ROWID配注游标
 *
 * @参数ROWID值得注意的ID检索
 * @返回光标定位匹配的注意,如果发现
 *抛出:SQLException - 如果音符无法找到/检索
 * /
公共光标fetchNote(双纬度,双LON){    尝试{
    光标mCursor =        mDb.query(真,DATABASE_TABLE,新的String [] {KEY_LAT,KEY_LON,
                KEY_TITLE,KEY_BODY},KEY_LAT +=+纬度+和+ KEY_LON +=+经度,空
                NULL,NULL,NULL,NULL);
    如果(mCursor!= NULL){
        mCursor.moveToFirst();
    }
    返回mCursor;
    }
    赶上(的SQLException SQLE)
    {
        返回null;
    }
}/ **
 *更新使用提供的详细的说明。要更新的音符
 *指定使用ROWID,它被改变为使用标题和正文
 *值传递
 *
 * @参数ROWID注意ID更新
 *参数标题值来设置笔记标题
 * @参数值身体要注意身体设为
 返回:true,如果该说明已成功更新,否则为false
 * /
公共布尔updateNote(双纬度,双LON,标题字符串,字符串体){
    ContentValues​​ ARGS =新ContentValues​​();
    args.put(KEY_TITLE,职称);
    args.put(KEY_BODY,体);    返回mDb.update(DATABASE_TABLE,指定参数时,KEY_LAT +=+纬度+和+ KEY_LON +=+经度,空)GT; 0;
}公共布尔的isEmpty()
{
    尝试{
    游标检查= mDb.query(票据,新的String [] {纬度},NULL,NULL,NULL,NULL,NULL);
    }
    赶上(NullPointerException异常E)
    {
        返回true;
    }
    返回false;
}
}

-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/

现在,code为类allmapactivity:

-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/

 公共类allmapactivity扩展MapActivity {
MapController mControl;
GeoPoint的GeoP;
图形页面mapV;
光标光标;
私人NotesDbAdapter mDbHelper;
公众的ArrayList<整数GT;纬度=新的ArrayList<整数GT;();
公众的ArrayList<整数GT;经度=新的ArrayList<整数GT;();@覆盖
保护无效的onCreate(捆绑savedInstanceState){
 // TODO自动生成方法存根
 super.onCreate(savedInstanceState);
 的setContentView(R.layout.map);
 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
 mapV =(图形页面)findViewById(R.id.mapview);
 mapV.displayZoomControls(真);
 mapV.setBuiltInZoomControls(真);
 mapV.setSatellite(假);最终MapController mController = mapV.getController();清单<&叠加GT; mapOverlays = mapV.getOverlays();
可绘制可绘制= this.getResources()getDrawable(R.drawable.pin)。mDbHelper =新NotesDbAdapter(getApplicationContext());    如果(!mDbHelper.isEmpty())
    {
    initcursor = mDbHelper.fetchAllNotes光标();
    initcursor.moveToFirst();
    的for(int i = 0; I< initcursor.getCount();我++)
    {
        HelloItemizedOverlay itemizedoverlay =
                 新HelloItemizedOverlay(绘制,allmapactivity.this);
        INT纬度=(INT)(initcursor.getDouble(initcursor.getColumnIndex(纬度))* 1E6);
        INT LON =(INT)(initcursor.getDouble(initcursor.getColumnIndex(LON))* 1E6);
            latitude.add(LAT);
            longitude.add(LON);
        GeoPoint对象的GeoPoint =新的GeoPoint(纬度,经度);
        字符串savedtitle = initcursor.getString(initcursor.getColumnIndex(称号);
        字符串savedtext = initcursor.getString(initcursor.getColumnIndex(身体));
         OverlayItem overlayitem =新OverlayItem(GeoPoint对象,savedtitle,savedtext);
         itemizedoverlay.addOverlay(overlayitem);
         mapOverlays.add(itemizedoverlay);
         initcursor.moveToNext();
    }
    }        字符串mapCenter = getMapCenter(纬度,经度);
        INT latCenter =(int)的(mapCenter.split(,)[0] * 1E6);
        INT lonCenter =(int)的(mapCenter.split(,)[1] * 1E6);
        GeoPoint的中心=新的GeoPoint(latCenter,lonCenter);        mController.animateTo(中心); //这将在地图焦点移动到功能getMapCenter发现的标记的中心点();}
 公共字符串getMapCenter(ArrayList的<整数GT; latitudeList,ArrayList的<整数GT; longitudeList)
 {
  //这个函数,顾名思义将返回的纬度,通过取标记的纬度和经度值的平均值中找到的标志物的中心点的经度
  INT latSum = 0;
  INT lonSum = 0;
  双latAverage = 0;
  双lonAverage = 0;
  字符串结果; 对于(整数latitudeValue:latitudeList)
 {
  latSum = latSum + latitudeValue;
 }
 对于(整数longitudeValue:longitudeList)
 {
  lonSum = lonSum + longitudeValue;
 } latAverage =(双)latSum / latitudeList.size();
 lonAverage =(双)lonSum / longitudeList.size(); 结果= latAverage +,+ lonAverage;
 返回结果;
}@覆盖
保护布尔isRouteDisplayed(){   // TODO自动生成方法存根返回false;
}}

I really need help populating a map with markers from coordinates stored in my database. I've worked with populating listviews from SQLite, and I can add markers to a map, but I cannot figure out how to add markers from an SQLite database. Also, if I could get some help with centering the markers on screen and zooming in where they all fit, that would be awesome! Heres my code so far:

*Updated Code*

ALLMAPACTIVITY

public class allmapactivity extends MapActivity {
GeoPoint GeoP;
MapView mapV;
private SQLiteAdapter mySQLiteAdapter;
public ArrayList<Integer> latitude = new ArrayList<Integer>();
public ArrayList<Integer> longitude = new ArrayList<Integer>();

@Override
protected void onCreate(Bundle savedInstanceState) {
 // TODO Auto-generated method stub
 super.onCreate(savedInstanceState);
 setContentView(R.layout.map);
 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
 requestWindowFeature(Window.FEATURE_NO_TITLE);


 mapV = (MapView) findViewById(R.id.mapview);
 mapV.displayZoomControls(true);
 mapV.setBuiltInZoomControls(true);
 mapV.setSatellite(false);

final MapController mController = mapV.getController();

List<Overlay> mapOverlays = mapV.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.pin);

mySQLiteAdapter = new SQLiteAdapter(getApplicationContext());

if(!mySQLiteAdapter.isEmpty())
{
Cursor initcursor = mySQLiteAdapter.queueAll5();
initcursor.moveToFirst();
for(int i = 0; i < initcursor.getCount();i++)
{
    HelloItemizedOverlay itemizedoverlay = 
             new HelloItemizedOverlay(drawable, allmapactivity.this);
    int lat = (int) (initcursor.getDouble(initcursor.getColumnIndex("Content11")) * 1E6);
    int lon = (int) (initcursor.getDouble(initcursor.getColumnIndex("Content12")) * 1E6);
        latitude.add(lat);
        longitude.add(lon);
    GeoPoint geopoint = new GeoPoint(lat, lon);
    String savedtitle = initcursor.getString(initcursor.getColumnIndex("Content9"));
    String savedtext = initcursor.getString(initcursor.getColumnIndex("Content10"));
     OverlayItem overlayitem = new OverlayItem(geopoint, savedtitle, savedtext);
     itemizedoverlay.addOverlay(overlayitem);
     mapOverlays.add(itemizedoverlay);
     initcursor.moveToNext();
  }
  }

        int latSum = 0;
double latAverage = 0;

 for(Integer latitudeValue: latitude)
 {
  latSum = latSum + latitudeValue;
 }

 latAverage = (double) latSum/latitude.size();


 int lonSum = 0;
 double lonAverage = 0;

for(Integer longitudeValue: longitude)
{
 lonSum = lonSum + longitudeValue;
}

lonAverage = (double) lonSum/longitude.size();

    GeoPoint center = new GeoPoint((int) latAverage, (int) lonAverage);

    mController.animateTo(center); 


}

@Override
protected boolean isRouteDisplayed() {

   // TODO Auto-generated method stub

return false;
}

}

SQLITEADAPTER

public class SQLiteAdapter {



 public static final String MYDATABASE_NAME = "MY_DATABASE";

 public static final String MYDATABASE_TABLE = "MY_TABLE";

 public static final int MYDATABASE_VERSION = 1;

 public static final String KEY_ID = "_id";

 public static final String KEY_CONTENT1 = "Content1";

 public static final String KEY_CONTENT3 = "Content3";

 public static final String KEY_CONTENT4 = "Content4";

 public static final String KEY_CONTENT5 = "Content5";

 public static final String KEY_CONTENT6 = "Content6";

 public static final String KEY_CONTENT7 = "Content7";

 public static final String KEY_CONTENT8 = "Content8";

 public static final String KEY_CONTENT9 = "Content9";

 public static final String KEY_CONTENT10 = "Content10";

 public static final String KEY_CONTENT11 = "Content11";

 public static final String KEY_CONTENT12 = "Content12";




 private static final String SCRIPT_CREATE_DATABASE =

  "create table " + MYDATABASE_TABLE + " ("

  + KEY_ID + " integer primary key autoincrement, "

  + KEY_CONTENT1 + " text not null, "

  + KEY_CONTENT3 + " text not null, "

  + KEY_CONTENT4 + " text not null," 

  + KEY_CONTENT5 + " text not null, "

  + KEY_CONTENT6 + " text not null," 

  + KEY_CONTENT7 + " text not null,"

  + KEY_CONTENT8 + " text not null,"

  + KEY_CONTENT9 + " text not null,"

  + KEY_CONTENT10 + " text not null,"

  + KEY_CONTENT11 + " text not null,"

  + KEY_CONTENT12 + " text not null);";

private static final String FOOTPRINT = null;



private SQLiteHelper sqLiteHelper;

private SQLiteDatabase sqLiteDatabase;



private Context context;



public SQLiteAdapter(Context c){

context = c;

}



 public SQLiteAdapter openToRead() throws android.database.SQLException {

  sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);

  sqLiteDatabase = sqLiteHelper.getReadableDatabase();

  return this; 

 }



 public SQLiteAdapter openToWrite() throws android.database.SQLException {

  sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);

  sqLiteDatabase = sqLiteHelper.getWritableDatabase();

  return this; 

 }



 public void close(){

  sqLiteHelper.close();

 }



 public long insert(String content1, String content3, 
                String content4, String content5, String content6, String content7, 
                String content8, String content9, String content10, String content11, String content12){

  ContentValues contentValues = new ContentValues();

  contentValues.put(KEY_CONTENT1, content1);

  contentValues.put(KEY_CONTENT3, content3);

  contentValues.put(KEY_CONTENT4, content4);

  contentValues.put(KEY_CONTENT5, content5);

  contentValues.put(KEY_CONTENT6, content6);

  contentValues.put(KEY_CONTENT7, content7);

  contentValues.put(KEY_CONTENT8, content8);

  contentValues.put(KEY_CONTENT9, content9);

  contentValues.put(KEY_CONTENT10, content10);

  contentValues.put(KEY_CONTENT11, content11);

  contentValues.put(KEY_CONTENT12, content12);

  return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);

 }

 public int deleterow(){
 SharedPreferences settings = context.getSharedPreferences(FOOTPRINT, 0);
 String itemId = settings.getString("columnvalue5", "");

  return sqLiteDatabase.delete(MYDATABASE_TABLE, KEY_CONTENT1 + "=" + "?", new String[]{itemId});

 }
 public int deleterow2(){
 SharedPreferences settings = context.getSharedPreferences(FOOTPRINT, 0);
 String itemId = settings.getString("columnvalue6", "");
 String itemId2 = settings.getString("columnvalue7", "");

  return sqLiteDatabase.delete(MYDATABASE_TABLE, 
          KEY_CONTENT1 + "=?" + " and " + KEY_CONTENT3 + "=?",  new String[]{itemId,itemId2});

 }
 public int deleterow3(){
 SharedPreferences settings = context.getSharedPreferences(FOOTPRINT, 0);
 String itemId = settings.getString("columnvalue8", "");

  return sqLiteDatabase.delete(MYDATABASE_TABLE, KEY_ID + "=" + "?", new String[]{itemId});

 }


 public Cursor queueAll(){

 String[] columns = new String[]{KEY_ID, KEY_CONTENT1, "sum(" + KEY_CONTENT6 + " )", KEY_CONTENT9};

 Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,

 null, null, KEY_CONTENT1, null, KEY_CONTENT9+ " DESC");


  return cursor;

 }

 public Cursor queueAll2(){

 SharedPreferences settings = context.getSharedPreferences(FOOTPRINT, 0);
 String itemId = settings.getString("columnvalue1", "");



  String[] columns = new String[]{KEY_ID, KEY_CONTENT1, KEY_CONTENT3, "sum(" + KEY_CONTENT6 + " )", KEY_CONTENT9, KEY_CONTENT10};

  Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,

          KEY_CONTENT1 + "=" + "?", new String[]{itemId}, KEY_CONTENT3, null, KEY_CONTENT9+ " DESC");


  return cursor;

 }

 public Cursor queueAll3(){

 SharedPreferences settings = context.getSharedPreferences(FOOTPRINT, 0);
 String itemId = settings.getString("columnvalue1", "");
 String itemId2 = settings.getString("columnvalue2", "");

  String[] columns = new String[]{KEY_ID, KEY_CONTENT1, KEY_CONTENT3, KEY_CONTENT4, KEY_CONTENT5, KEY_CONTENT6, 
                                  KEY_CONTENT7, KEY_CONTENT8, KEY_CONTENT9, KEY_CONTENT11, KEY_CONTENT12};

  Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,

          KEY_CONTENT1 + "=?" + " and " + KEY_CONTENT3 + "=?" , new String[]{itemId,itemId2}, null, null, KEY_CONTENT9+ " DESC");


  return cursor;

 }


 public Cursor queueAll4(){

  String[] columns = new String[]{KEY_ID, "sum(" + KEY_CONTENT6 + " )", KEY_CONTENT9, KEY_CONTENT10 };

  Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,

          null , null, KEY_CONTENT10, null, KEY_CONTENT9+ " DESC");


  return cursor;

 }

 public Cursor queueAll5(){

  String[] columns = new String[]{KEY_CONTENT9, KEY_CONTENT10, KEY_CONTENT11, KEY_CONTENT12};

  Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,

          null , null, null, null, null);


  return cursor;

 }

 public boolean isEmpty()
 {
 try{
 Cursor check = sqLiteDatabase.query("MY_TABLE", new String[] {"Content11"}, null, null, null, null, null);
 }
 catch(NullPointerException e)
 {
     return true;
 }
 return false;
 }


 public class SQLiteHelper extends SQLiteOpenHelper {



  public SQLiteHelper(Context context, String name,

 CursorFactory factory, int version) {

  super(context, name, factory, version);

  }



  @Override

  public void onCreate(SQLiteDatabase db) {

   // TODO Auto-generated method stub

  db.execSQL(SCRIPT_CREATE_DATABASE);

 }



  @Override

  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

   // TODO Auto-generated method stub

  }

 } 

}

Unfortunately, I get a force close error with this code :( heres the logcat:

07-22 19:14:33.918: E/AndroidRuntime(1330): FATAL EXCEPTION: main
07-22 19:14:33.918: E/AndroidRuntime(1330): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.inn.footprint/com.inn.footprint.allmapactivity}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
07-22 19:14:33.918: E/AndroidRuntime(1330):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
07-22 19:14:33.918: E/AndroidRuntime(1330):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
07-22 19:14:33.918: E/AndroidRuntime(1330):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
07-22 19:14:33.918: E/AndroidRuntime(1330):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
07-22 19:14:33.918: E/AndroidRuntime(1330):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-22 19:14:33.918: E/AndroidRuntime(1330):     at android.os.Looper.loop(Looper.java:130)
07-22 19:14:33.918: E/AndroidRuntime(1330):     at android.app.ActivityThread.main(ActivityThread.java:3683)
07-22 19:14:33.918: E/AndroidRuntime(1330):     at java.lang.reflect.Method.invokeNative(Native Method)
07-22 19:14:33.918: E/AndroidRuntime(1330):     at java.lang.reflect.Method.invoke(Method.java:507)
07-22 19:14:33.918: E/AndroidRuntime(1330):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-22 19:14:33.918: E/AndroidRuntime(1330):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-22 19:14:33.918: E/AndroidRuntime(1330):     at dalvik.system.NativeStart.main(Native Method)
07-22 19:14:33.918: E/AndroidRuntime(1330): Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
07-22 19:14:33.918: E/AndroidRuntime(1330):     at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:181)
07-22 19:14:33.918: E/AndroidRuntime(1330):     at android.app.Activity.requestWindowFeature(Activity.java:2729)
07-22 19:14:33.918: E/AndroidRuntime(1330):     at com.inn.footprint.allmapactivity.onCreate(allmapactivity.java:36)
07-22 19:14:33.918: E/AndroidRuntime(1330):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-22 19:14:33.918: E/AndroidRuntime(1330):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
07-22 19:14:33.918: E/AndroidRuntime(1330):     ... 11 more

解决方案

The following NotesDbAdapter has been adapted from the Notepad Tutorial on developer.android.com, think of it as a database wrapper. I've added extra fields such as lat, lon which will be the primary key, i.e how you can access the location of a marker, where your marker will be stored. And then following this code, I've also provided a modification to your class allmapactivity which is get all of the 'notes' i.e markers in your database and then populate your map with them. This code will definitely work as I've tested it! Let me know if you need further advice!

Cheers

/*
* Copyright (C) 2008 Google Inc.
* 
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
* Simple notes database access helper class. Defines the basic CRUD operations
* for the notepad example, and gives the ability to list all notes as well as
* retrieve or modify a specific note.
* 
* This has been improved from the first version of this tutorial through the
* addition of better error handling and also using returning a Cursor instead
* of using a collection of inner classes (which is less scalable and not
* recommended).
*/
public class NotesDbAdapter {

public static final String KEY_TITLE = "title";
public static final String KEY_BODY = "body";
public static final String KEY_LAT = "lat";
public static final String KEY_LON = "lon";

private static final String TAG = "NotesDbAdapter";
public DatabaseHelper mDbHelper;
public SQLiteDatabase mDb;

/**
 * Database creation sql statement
 */
private static final String DATABASE_CREATE =
    "CREATE TABLE notes (lat REAL, lon REAL, title varchar(60), body varchar(300), PRIMARY KEY (lat, lon));";

private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "notes";
private static final int DATABASE_VERSION = 2;

private final Context mCtx;

private static class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS notes");
        onCreate(db);
    }
}

/**
 * Constructor - takes the context to allow the database to be
 * opened/created
 * 
 * @param ctx the Context within which to work
 */
public NotesDbAdapter(Context ctx) {
    this.mCtx = ctx;
    open();
}

/**
 * Open the notes database. If it cannot be opened, try to create a new
 * instance of the database. If it cannot be created, throw an exception to
 * signal the failure
 * 
 * @return this (self reference, allowing this to be chained in an
 *         initialization call)
 * @throws SQLException if the database could be neither opened or created
 */
public NotesDbAdapter open() throws SQLException {
    mDbHelper = new DatabaseHelper(mCtx);
    mDb = mDbHelper.getWritableDatabase();
    return this;
}

public void close() {
    mDbHelper.close();
}


/**
 * Create a new note using the title and body provided. If the note is
 * successfully created return the new rowId for that note, otherwise return
 * a -1 to indicate failure.
 * 
 * @param title the title of the note
 * @param body the body of the note
 * @return rowId or -1 if failed
 */
public long createNote(double lat, double lon, String title, String body) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_LAT, lat);
    initialValues.put(KEY_LON, lon);
    initialValues.put(KEY_TITLE, title);
    initialValues.put(KEY_BODY, body);

    return mDb.insert(DATABASE_TABLE, null, initialValues);
}

/**
 * Delete the note with the given rowId
 * 
 * @param rowId id of note to delete
 * @return true if deleted, false otherwise
 */
public boolean deleteNote(double lat, double lon) {

    return mDb.delete(DATABASE_TABLE, KEY_LAT + "=" + lat + " and " + KEY_LON + "=" + lon, null) > 0;
}

/**
 * Return a Cursor over the list of all notes in the database
 * 
 * @return Cursor over all notes
 */
public Cursor fetchAllNotes() {
    return mDb.query("notes", new String[] {KEY_LAT, KEY_LON,
            KEY_TITLE, KEY_BODY}, null, null, null, null, null);
}

/**
 * Return a Cursor positioned at the note that matches the given rowId
 * 
 * @param rowId id of note to retrieve
 * @return Cursor positioned to matching note, if found
 * @throws SQLException if note could not be found/retrieved
 */
public Cursor fetchNote(double lat, double lon) {

    try{    
    Cursor mCursor =

        mDb.query(true, DATABASE_TABLE, new String[] {KEY_LAT, KEY_LON,
                KEY_TITLE, KEY_BODY}, KEY_LAT + "=" + lat+ " and "+KEY_LON+"="+lon, null,
                null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
    }
    catch(SQLException sqle)
    {
        return null;
    }
}

/**
 * Update the note using the details provided. The note to be updated is
 * specified using the rowId, and it is altered to use the title and body
 * values passed in
 * 
 * @param rowId id of note to update
 * @param title value to set note title to
 * @param body value to set note body to
 * @return true if the note was successfully updated, false otherwise
 */
public boolean updateNote(double lat, double lon, String title, String body) {
    ContentValues args = new ContentValues();
    args.put(KEY_TITLE, title);
    args.put(KEY_BODY, body);

    return mDb.update(DATABASE_TABLE, args, KEY_LAT + "=" + lat + " and " + KEY_LON + "=" + lon, null) > 0;
}

public boolean isEmpty()
{
    try{
    Cursor check = mDb.query("notes", new String[] {"lat"}, null, null, null, null, null);
    }
    catch(NullPointerException e)
    {
        return true;
    }
    return false;
}
}

-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/

Now, the code for your class allmapactivity:

-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/

public class allmapactivity extends MapActivity {
MapController mControl;
GeoPoint GeoP;
MapView mapV;
Cursor cursor;
private NotesDbAdapter mDbHelper;
public ArrayList<Integer> latitude = new ArrayList<Integer>();
public ArrayList<Integer> longitude = new ArrayList<Integer>();

@Override
protected void onCreate(Bundle savedInstanceState) {
 // TODO Auto-generated method stub
 super.onCreate(savedInstanceState);
 setContentView(R.layout.map);
 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


 mapV = (MapView) findViewById(R.id.mapview);
 mapV.displayZoomControls(true);
 mapV.setBuiltInZoomControls(true);
 mapV.setSatellite(false);

final MapController mController = mapV.getController();

List<Overlay> mapOverlays = mapV.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.pin);

mDbHelper = new NotesDbAdapter(getApplicationContext());

    if(!mDbHelper.isEmpty())
    {
    Cursor initcursor = mDbHelper.fetchAllNotes();
    initcursor.moveToFirst();
    for(int i = 0; i < initcursor.getCount();i++)
    {
        HelloItemizedOverlay itemizedoverlay = 
                 new HelloItemizedOverlay(drawable, allmapactivity.this);
        int lat = (int) (initcursor.getDouble(initcursor.getColumnIndex("lat")) * 1E6);
        int lon = (int) (initcursor.getDouble(initcursor.getColumnIndex("lon")) * 1E6);
            latitude.add(lat);
            longitude.add(lon);
        GeoPoint geopoint = new GeoPoint(lat, lon);
        String savedtitle = initcursor.getString(initcursor.getColumnIndex("title");
        String savedtext = initcursor.getString(initcursor.getColumnIndex("body"));
         OverlayItem overlayitem = new OverlayItem(geopoint, savedtitle, savedtext);
         itemizedoverlay.addOverlay(overlayitem);
         mapOverlays.add(itemizedoverlay);
         initcursor.moveToNext();
    }
    }

        String mapCenter = getMapCenter(latitude, longitude);
        int latCenter = (int) (mapCenter.split(",")[0] * 1E6);
        int lonCenter = (int) (mapCenter.split(",")[1] * 1E6);
        GeoPoint center = new GeoPoint(latCenter, lonCenter);

        mController.animateTo(center); // This will move the map focus to the central point of the markers found in the function getMapCenter();



}


 public String getMapCenter(ArrayList<Integer> latitudeList, ArrayList<Integer> longitudeList)
 {
  // This function, as the name suggests will return the latitude, longitude of the central point of the markers found by taking the average of the latitude and longitude values of the markers
  int latSum = 0;
  int lonSum = 0;
  double latAverage = 0;
  double lonAverage = 0;
  String result;

 for(Integer latitudeValue: latitudeList)
 {
  latSum = latSum + latitudeValue;
 }
 for(Integer longitudeValue: longitudeList)
 {
  lonSum = lonSum + longitudeValue;
 }

 latAverage = (double) latSum/latitudeList.size();
 lonAverage = (double) lonSum/longitudeList.size();

 result = latAverage+","+lonAverage;
 return result;
}

@Override
protected boolean isRouteDisplayed() {

   // TODO Auto-generated method stub

return false;
}

}

这篇关于添加标记从SQLite和中心映射/变焦适合他们(Android版)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆