`

数据库与MapView总结

阅读更多

1.学习MENU功能:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class EX10_06 extends Activity
{
  /* 独一无二的menu选项identifier,用以识别事件 */
  static final private int MENU_ADD = Menu.FIRST;
  static final private int MENU_EDIT = Menu.FIRST+1;
  static final private int MENU_DRAW = Menu.FIRST+2;
  
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu)
  {
    // TODO Auto-generated method stub
    /* menu群组ID */
    int idGroup1 = 0;
    
    /* The order position of the item */
    int orderItem1 = Menu.NONE;
    int orderItem2 = Menu.NONE+1;
    int orderItem3 = Menu.NONE+2;
    
    /* 创建3个Menu菜单 */
    menu.add(idGroup1, MENU_ADD, orderItem1, R.string.str_manu1).
    setIcon(android.R.drawable.ic_menu_add);
    
    menu.add(idGroup1, MENU_EDIT, orderItem2, R.string.str_manu2).
    setIcon(android.R.drawable.ic_dialog_info);
    
    menu.add(idGroup1, MENU_DRAW, orderItem3, R.string.str_manu3).
    setIcon(R.drawable.hipposmall);
    
    return super.onCreateOptionsMenu(menu);
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item)
  {
    // TODO Auto-generated method stub
    Intent intent = new Intent();
    switch(item.getItemId())
    {
      case (MENU_ADD):
        /* 新建餐厅资料 */
        intent.setClass(EX10_06.this, EX10_06_02.class);
        startActivity(intent);
        finish();
        break;
      case (MENU_EDIT):
        /* 编辑数据 */
        intent.setClass(EX10_06.this, EX10_06_03.class);
        startActivity(intent);
        finish();
        break;
      case (MENU_DRAW):
        /* 前往系统随机数选择餐厅功能 */
        intent.setClass(EX10_06.this, EX10_06_04.class);
        startActivity(intent);
        finish();
        break;
    }
    return super.onOptionsItemSelected(item);
  }  
}

 2。添加餐馆以及操作数据库

package irdc.ex10_06;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class EX10_06_02 extends Activity {

	private EditText mEditText01, mEditText02, mEditText03;
	private Button mButton01;
	static final private int MENU_EDIT = Menu.FIRST + 1;
	static final private int MENU_DRAW = Menu.FIRST + 2;
	private MySQLiteOpenHelper dbHelper = null;

	int version = 1;
	String tables[] = { "t_restaurant" };
	String fieldNames[][] = { { "f_id", "f_name", "f_address", "f_cal" } };

	String fieldTypes[][] = { { "INTEGER PRIMARY KEY AUTOINCREMENT", "text",
			"text", "text" } };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_add);

		mEditText01 = (EditText) findViewById(R.id.myEditText1);
		mEditText02 = (EditText) findViewById(R.id.myEditText2);
		mEditText03 = (EditText) findViewById(R.id.myEditText3);

		dbHelper = new MySQLiteOpenHelper(this, "mydb", null, version, tables,
				fieldNames, fieldTypes);
		mButton01 = (Button) findViewById(R.id.myButton1);
		mButton01.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				if (mEditText01.getText().toString().trim().length() != 0
						&& mEditText02.getText().toString().trim().length() != 0
						&& mEditText03.getText().toString().trim().length() != 0) {
					String f[] = { "f_id", "f_name" };
					String[] selectionArgs = { mEditText01.getText().toString() };
					Cursor c = dbHelper.select(tables[0], f, "f_name=?",
							selectionArgs, null, null, null);
					String strRes = "";
					while (c.moveToNext()) {
						strRes += c.getString(0) + "\n";
					}
					if (strRes == "") {
						String f2[] = { "f_name", "f_address", "f_cal" };
						String v[] = { mEditText01.getText().toString().trim(),
								mEditText02.getText().toString().trim(),
								mEditText03.getText().toString().trim()

						};
						long rowid = dbHelper.insert(tables[0], f2, v);
						strRes += rowid + "\n";
					} else {

					}
					if (dbHelper != null
							&& dbHelper.getReadableDatabase().isOpen()) {
						dbHelper.close();
					}
					Intent intent = new Intent();
					intent.setClass(EX10_06_02.this, EX10_06_03.class);
					startActivity(intent);
					finish();
				}

			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		int idGroup1 = 0;

		int orderItem2 = Menu.NONE + 1;
		int orderItem3 = Menu.NONE + 2;

		menu.add(idGroup1, MENU_EDIT, orderItem2, R.string.str_manu2).setIcon(
				android.R.drawable.ic_dialog_info);
		
		menu.add(idGroup1, MENU_DRAW, orderItem3, R.string.str_manu3).setIcon(
				R.drawable.hipposmall);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    Intent intent=new Intent();
	    switch (item.getItemId()) {
		case (MENU_EDIT):
			if(dbHelper!=null&&dbHelper.getReadableDatabase().isOpen()){
				dbHelper.close();
			}
		intent.setClass(EX10_06_02.this, EX10_06_03.class);
		startActivity(intent);
		finish();
		
			break;
			
		case (MENU_DRAW):
			if(dbHelper!=null&&dbHelper.getReadableDatabase().isOpen()){
				dbHelper.close();
			}
		intent.setClass(EX10_06_02.this, EX10_06_04.class);
		startActivity(intent);
		finish();
		
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
		if(dbHelper!=null&&dbHelper.getReadableDatabase().isOpen()){
			dbHelper.close();
		}
		super.onDestroy();
	}
}

 

3。编辑餐馆

package irdc.ex10_06;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

/* 编辑餐厅数据Activity */
public class EX10_06_03 extends Activity
{
  private ListView mListView01;
  static final private int MENU_ADD = Menu.FIRST;
  static final private int MENU_DRAW = Menu.FIRST+2;
  private MySQLiteOpenHelper dbHelper=null;
  /* version必须大于等于1 */
  private int version = 1;
  private List<String> allRestaurantID;
  private List<String> allRestaurantName;
  private List<String> allRestaurantAddress;
  private List<String> allRestaurantCal;
  private List<String> lstRestaurant;
  private int intItemSelected=-1;
  
  /* 数据库数据表  */
  private String tables[] = { "t_restaurant" };
  
  /* 数据库字段名称  */
  private String fieldNames[][] =
  {
    { "f_id", "f_name", "f_address", "f_cal" }
  };
  
  /* 数据库字段数据类型  */
  private String fieldTypes[][] =
  {
    { "INTEGER PRIMARY KEY AUTOINCREMENT", "text" , "text", "text"}
  };
  
  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_list);
    
    mListView01 = (ListView)findViewById(R.id.myListView1);
    dbHelper = new MySQLiteOpenHelper
    (this, "mydb", null, version, tables, fieldNames, fieldTypes);
    
    updateListView();
    
    mListView01.setOnItemClickListener
    (new ListView.OnItemClickListener()
    {
   
      public void onItemClick
      (AdapterView<?> parent, View v, int id,  long arg3)
      {
        // TODO Auto-generated method stub
        /* f_id字段 */
        intItemSelected = id;
        
        /* 弹出的菜单提供两种功能(编辑、删除) */
        String[] dlgMenu=
        {
          getResources().getText(R.string.str_edit_it).toString(),
          getResources().getText(R.string.str_del_it).toString()
        };
        new AlertDialog.Builder(EX10_06_03.this)
        .setTitle(R.string.str_whattodo)
        .setItems(dlgMenu, mListener1)
        .setPositiveButton(R.string.str_cancel,
        new DialogInterface.OnClickListener()
        {
          public void onClick(DialogInterface dialog, int which)
          {
          }
        }).show();
      }
    });
  }
  
  private OnClickListener mListener1=
  new DialogInterface.OnClickListener()
  {

    public void onClick(DialogInterface dialog, int which)
    {
      // TODO Auto-generated method stub
      switch(which)
      {
        case 0:
          /* 数据修改 */
          if(intItemSelected>=0)
          {
            /* 创建背景模糊效果的前景窗口 */
            final Dialog d = new Dialog(EX10_06_03.this);
            Window window = d.getWindow();
            window.setFlags
            (
              WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
              WindowManager.LayoutParams.FLAG_BLUR_BEHIND
            );
            d.setTitle(R.string.str_edit_it);
            d.setContentView(R.layout.layout_edit);
            
            /* 将User点击的餐厅数据放入窗口Widget当中 */
            final EditText mEditText01 = 
            (EditText)d.findViewById(R.id.myEditText1);
            final EditText mEditText02 = 
            (EditText)d.findViewById(R.id.myEditText2);
            final EditText mEditText03 = 
            (EditText)d.findViewById(R.id.myEditText3);
            mEditText01.setText
            (allRestaurantName.get(intItemSelected));
            mEditText02.setText
            (allRestaurantAddress.get(intItemSelected));
            mEditText03.setText
            (allRestaurantCal.get(intItemSelected));
            
            /* 更新数据按钮事件处理 */
            Button mButton01 = (Button)d.findViewById(R.id.myButton2);
            mButton01.setOnClickListener(new Button.OnClickListener()
            {
         
              public void onClick(View arg0)
              {
                // TODO Auto-generated method stub
                String[] updateFields =
                {
                  "f_name", "f_address", "f_cal"
                };
                String[] updateValues =
                {
                  mEditText01.getText().toString(),
                  mEditText02.getText().toString(),
                  mEditText03.getText().toString()
                };
                String where = "f_id=?";
                String[] whereValue =
                {
                  allRestaurantID.get(intItemSelected)
                };
                /* 调用update()更新数据表里的记录 */
                int intCol = dbHelper.update
                (
                  tables[0], updateFields, updateValues,
                  where, whereValue
                );
                /* 返回更新成功笔数 >0时 */
                if(intCol>0)
                {
                  updateListView();
                }
                d.dismiss();
              }
            });
            d.show();
          }
          break;
        case 1:
          /* 删除数据 */
          if(intItemSelected>=0)
          {
            String where = "f_id=?";
            String[] whereValue =
            {
              allRestaurantID.get(intItemSelected)
            };
            int intCol = dbHelper.delete
            (
              tables[0], where, whereValue
            );
            
            /* 返回删除成功笔数 >0时 */
            if(intCol>0)
            {
              /* 删除成功 */
              updateListView();
            }
          }
          break;
      }
    }
  };
  
  /**
   * 更新ListView数据
   */
  private void updateListView()
  {
    String f[] = { "f_id", "f_name", "f_address", "f_cal"};
    /* SELECT f[] FROM tables[0] */
    Cursor c = dbHelper.select
    (
      tables[0], f, "", null, null, null, null
    );
    lstRestaurant = new ArrayList<String>();
    allRestaurantID = new ArrayList<String>();
    allRestaurantName = new ArrayList<String>();
    allRestaurantAddress = new ArrayList<String>();
    allRestaurantCal = new ArrayList<String>();
    
    while (c.moveToNext())
    {
      lstRestaurant.add
      (
        c.getString(1)+"("+c.getString(3)+
        getResources().getText(R.string.str_cal)+")"
      );
      allRestaurantID.add(c.getString(0));
      allRestaurantName.add(c.getString(1));
      allRestaurantAddress.add(c.getString(2));
      allRestaurantCal.add(c.getString(3));
    }
    if(lstRestaurant.size()>0)
    {
      ArrayAdapter<String> adapter = new ArrayAdapter<String>
      (
        EX10_06_03.this,
        R.layout.simple_list_item_single_choice, lstRestaurant
      );
      mListView01.setItemsCanFocus(true);
      mListView01.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
      mListView01.setAdapter(adapter);
    }
    else
    {
      /* 数据库无记录,将flag设置为-1 */
      intItemSelected = -1;
      
      ArrayAdapter<String> adapter = new ArrayAdapter<String>
      (
        EX10_06_03.this, R.layout.simple_list_item_single_choice,
        lstRestaurant
      );
      mListView01.setItemsCanFocus(true);
      mListView01.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
      mListView01.setAdapter(adapter);
    }
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu)
  {
    // TODO Auto-generated method stub
    /* menu群组ID */
    int idGroup1 = 0;
    
    /* The order position of the item */
    int orderItem1 = Menu.NONE;
    int orderItem3 = Menu.NONE+2;
     
    menu.add(idGroup1, MENU_ADD, orderItem1, R.string.str_manu1).
    setIcon(android.R.drawable.ic_menu_add);
    menu.add(idGroup1, MENU_DRAW, orderItem3, R.string.str_manu3).
    setIcon(R.drawable.hipposmall);
    return super.onCreateOptionsMenu(menu);
  }
  
  @Override
  public boolean onMenuItemSelected(int featureId, MenuItem item)
  {
    // TODO Auto-generated method stub
    Intent intent = new Intent();
    switch(item.getItemId())
    {
      case (MENU_ADD):
        /* 前往新建餐厅功能 */
        if(dbHelper!=null && 
           dbHelper.getReadableDatabase().isOpen())
        {
          dbHelper.close();
        }
        intent.setClass(EX10_06_03.this, EX10_06_02.class);
        startActivity(intent);
        finish();
        break;
      case (MENU_DRAW):
        /* 前往系统随机数选择餐厅功能 */
        if(dbHelper!=null && 
           dbHelper.getReadableDatabase().isOpen())
        {
          dbHelper.close();
        }
        intent.setClass(EX10_06_03.this, EX10_06_04.class);
        startActivity(intent);
        finish();
        break;
    }
    return super.onMenuItemSelected(featureId, item);
  }
  
  @Override
  protected void onResume()
  {
    // TODO Auto-generated method stub
    super.onResume();
  }
  
  @Override
  protected void onPause()
  {
    // TODO Auto-generated method stub
    super.onPause();
  }
  
  @Override
  protected void onDestroy()
  {
    // TODO Auto-generated method stub
    if(dbHelper!=null && 
       dbHelper.getReadableDatabase().isOpen())
    {
      dbHelper.close();
    }
    super.onDestroy();
  }  
}

 

4。在Map上画图

package irdc.ex10_06;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import android.database.Cursor;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

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;

public class EX10_06_04 extends MapActivity{
   
	private TextView mTextView01;
	  /* 独一无二的menu选项identifier,用以识别事件 */
	  static final private int MENU_ADD = Menu.FIRST;
	  static final private int MENU_EDIT = Menu.FIRST+1;
	  static final private int MENU_DRAW = Menu.FIRST+2;
	  
	  /* Google地图所需成员变量 */
	  private MapView mMapView01;
	  private int intZoomLevel=20;
	  
	  /* 数据库所需成员变量 */
	  private MySQLiteOpenHelper dbHelper=null;
	  private int version = 1;
	  private List<String> allRestaurantID;
	  private List<String> allRestaurantName;
	  private List<String> allRestaurantAddress;
	  private List<String> allRestaurantCal;
	  
	  /* 数据库数据表 */
	  private String tables[] = { "t_restaurant" };
	  
	  /* 数据库字段名称 */
	  private String fieldNames[][] =
	  {
	    { "f_id", "f_name", "f_address", "f_cal" }
	  };
	  
	  /* 数据库字段数据类型 */
	  private String fieldTypes[][] =
	  {
	    { "INTEGER PRIMARY KEY AUTOINCREMENT", "text" , "text", "text"}
	  };
	  

	  protected void onCreate(Bundle savedInstanceState)
	  {
	    // TODO Auto-generated method stub
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.layout_draw);
	    
	    mTextView01 = (TextView)findViewById(R.id.myTextView7);
	    /* 创建MapView对象 */
	    mMapView01 = (MapView)findViewById(R.id.myMapView1);
	    
	    /* 数据库连接 */
	    dbHelper = new MySQLiteOpenHelper
	    (this, "mydb", null, version, tables, fieldNames, fieldTypes);
	    
	    /* 系统选择餐馆 */
	    drawRestaurant();
	  }
	private void drawRestaurant() {
		String f[] = { "f_id", "f_name", "f_address", "f_cal"};
	    /* SELECT f[] FROM tables[0] */
	    Cursor c = dbHelper.select
	    (
	      tables[0], f, "", null, null, null, null
	    );
	    allRestaurantID = new ArrayList<String>();
	    allRestaurantName = new ArrayList<String>();
	    allRestaurantAddress = new ArrayList<String>();
	    allRestaurantCal = new ArrayList<String>();
	    
	    /* 将所有餐厅数据放入List<String>对象 */
	    while (c.moveToNext())
	    {
	      allRestaurantID.add(c.getString(0));
	      allRestaurantName.add(c.getString(1));
	      allRestaurantAddress.add(c.getString(2));
	      allRestaurantCal.add(c.getString(3));
	    }
	    
	    if(allRestaurantID.size()>0)
	    {
	      Random generator = new Random();
	      int intThrowIndex = generator.nextInt(allRestaurantID.size());
	      mTextView01.setText
	      (
	        allRestaurantName.get(intThrowIndex)+"\n"+
	        allRestaurantAddress.get(intThrowIndex)+"\n"+
	        allRestaurantCal.get(intThrowIndex)+
	        getResources().getText(R.string.str_cal)
	      );
	      /* 以地址查询地理坐标 */
	      GeoPoint gp = 
	      getGeoByAddress(allRestaurantAddress.get(intThrowIndex));
	      if(gp==null)
	      {
	        /* 地址无法反查为GeoPoint时 */
	        mMapView01.setVisibility(MapView.GONE);
	      }
	      else
	      {
	        /* 更新MapView地图 */
	        mMapView01.setVisibility(MapView.VISIBLE);
	        showImageOverlay(gp);
	        refreshMapViewByGeoPoint
	        (
	          getGeoByAddress(allRestaurantAddress.get(intThrowIndex)),
	          mMapView01, intZoomLevel, true
	        );
	      }
	    }
	    else
	    {
	      /* 数据库无记录 */
	      
	    }

		
	}
	
	  private GeoPoint getGeoByAddress(String strSearchAddress)
	  {
	    GeoPoint gp = null;
	    try
	    {
	      if(strSearchAddress!="")
	      {
	        Geocoder mGeocoder01 = 
	        new Geocoder(EX10_06_04.this, Locale.getDefault());
	        List<Address> lstAddress = 
	        mGeocoder01.getFromLocationName(strSearchAddress, 1);
	        if (!lstAddress.isEmpty())
	        {
	          Address adsLocation = lstAddress.get(0);
	          /* 1E6 = 1000000*/
	          double geoLatitude = adsLocation.getLatitude()*1E6;
	          double geoLongitude = adsLocation.getLongitude()*1E6;
	          gp = new GeoPoint((int) geoLatitude, (int) geoLongitude);
	        }
	      }
	    }
	    catch (Exception e)
	    { 
	      e.printStackTrace(); 
	    }
	    return gp;
	  }
	  
	  /**
	   * 更新MapView地图
	   * @param gp GeoPoint地理坐标对象
	   * @param mv 查询的数据的字段名称
	   * @param zoomLevel 放大层级
	   * @param setSatellite 是否显示卫星地图
	   */
	  public static void refreshMapViewByGeoPoint
	  (GeoPoint gp, MapView mv, int zoomLevel, boolean setSatellite)
	  {
	    try
	    {
	      mv.displayZoomControls(true);
	      MapController mc = mv.getController();
	      mc.animateTo(gp);
	      mc.setZoom(zoomLevel);
	      mv.setSatellite(setSatellite);
	    }
	    catch(Exception e)
	    {
	      e.printStackTrace();
	    }
	  }
	  
	  /**
	   * 在地图上显示Overlay图片
	   * @param gp GeoPoint地理坐标对象
	   */
	  private void showImageOverlay(GeoPoint gp)
	  {
	    /* 设置Overlay */
	    GeoPointImageOverlay mLocationOverlay01;
	    mLocationOverlay01 = new GeoPointImageOverlay
	    (
	      gp,
	      R.drawable.hipposmall
	    );
	    List<Overlay> overlays = mMapView01.getOverlays();
	    overlays.add(mLocationOverlay01);
	  }
	  
	  
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

}

 

5。工具方法:

package irdc.ex10_06;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Location;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

public class GeoPointImageOverlay extends Overlay
{
  private Location mLocation;
  private int drawableID;
  private double geoLatitude,geoLongitude;
  
  /* 建构方法一,传入Location对象 */
  public GeoPointImageOverlay(Location location, int drawableID)
  {
    this.mLocation = location;
    this.drawableID = drawableID;
    /* 取得Location的经纬度 */
    this.geoLatitude = this.mLocation.getLatitude()*1E6;
    this.geoLongitude = this.mLocation.getLongitude()*1E6;
  }
  
  public GeoPointImageOverlay
  (Double geoLatitude, Double geoLongitude, int drawableID)
  {
    this.geoLatitude = geoLatitude*1E6;
    this.geoLongitude = geoLongitude*1E6;
    this.drawableID = drawableID;
  }
  
  public GeoPointImageOverlay(GeoPoint gp, int drawableID)
  {
    this.geoLatitude = gp.getLatitudeE6();
    this.geoLongitude = gp.getLongitudeE6();
    this.drawableID = drawableID;
  }
  
  public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when){
	 Projection projection=mapView.getProjection();
	 if(shadow==false){
		 GeoPoint gp=new GeoPoint((int)this.geoLatitude, (int)this.geoLongitude);
		 Point point=new Point();
		 projection.toPixels(gp, point);
		 
		 Paint paint=new Paint();
		 paint.setAntiAlias(true);
		 
		 Bitmap bm=BitmapFactory.decodeResource(mapView.getResources(), this.drawableID);
		 canvas.drawBitmap(bm, point.x, point.y, paint);
	 }
	  
	  return super.draw(canvas, mapView, shadow, when);
	  
  }
  
  
  public void updateLocation(Location location)
  {
    this.mLocation = location;
  }
  
  public Location getLocation()
  {
    return mLocation;
  }
  
}

 

6。数据库

package irdc.ex10_06;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class MySQLiteOpenHelper extends SQLiteOpenHelper {

	public String TableNames[];
	public String FieldNames[][];
	public String FieldTypes[][];
	public static String NO_CREATE_TABLES = "no talbes";
	private String message = "";

	public MySQLiteOpenHelper(Context context, String name,
			CursorFactory factory, int version, String tableNames[],
			String fielsNames[][], String fieldTypes[][]) {
		super(context, name, factory, version);
		TableNames = tableNames;
		FieldNames = fielsNames;
		FieldTypes = fieldTypes;
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		if (TableNames == null) {
			message = NO_CREATE_TABLES;
			return;
		}
		for (int i = 0; i < TableNames.length; i++) {
			String sql = "create table " + TableNames[i] + " (";
			for (int j = 0; j < FieldNames[i].length; j++) {
				sql += FieldNames[i][j] + " " + FieldTypes[i][j] + ",";
			}
			sql = sql.substring(0, sql.length() - 1);
			sql += ")";
			db.execSQL(sql);
		}

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
		for (int i = 0; i < TableNames[i].length(); i++) {
			String sql = "DROP TABLE IF EXISTS " + TableNames[i];
			db.execSQL(sql);
		}
		onCreate(db);
	}
public void execute(String sql) throws java.sql.SQLException{
	SQLiteDatabase db =this.getWritableDatabase();
	db.execSQL(sql);
}

 public Cursor select(String table,String[] columns,String selection,String[] selectionArgs,
		 String groupBy,String having,String orderBy
		 ){SQLiteDatabase db=this.getReadableDatabase();
		 Cursor cursor =db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
		 return cursor;
 
 }
 
 public long insert(String table,String fields[],String values[]){
	 SQLiteDatabase db=this.getReadableDatabase();
	 ContentValues cv =new ContentValues();
	 for(int i=0;i<fields.length;i++){
		 cv.put(fields[i], values[i]);
	 }
	return db.insert(table,null, cv);
		
 }
 	public int delete(String table,String where,String[] whereValue){
 		SQLiteDatabase db=this.getReadableDatabase();
 	return	db.delete(table, where, whereValue);
 	}
 	
 	public int update(String table,String updateFields[],String updateValues[],String where,
 			String[] whereValue){
 		SQLiteDatabase db =this.getWritableDatabase();
 		ContentValues cv=new ContentValues();
 		for(int i=0;i<updateFields.length;i++){
 			cv.put(updateFields[i], updateValues[i]);
 		}
 		return db.update(table, cv, where, whereValue);
 	}
 	public String getMessage(){
 		return message;
 	}
 	public synchronized void close(){
 		super.close();
 	}
}

 

分享到:
评论

相关推荐

    arcgis for android 读取加载sqlite数据库.rar

    使用JDBC连接数据库,执行SQL语句,将查询结果转化为ArcGIS要素,并加载到MapView中。 7. **最佳实践**: - 使用ContentProvider封装数据库操作,提高代码的可复用性和安全性。 - 考虑使用ORM(Object-Relational ...

    基于android的地图源码 连接远程数据库 实现定位 查询

    在Android开发中,地图应用是常见且重要...总结来说,这个项目涵盖了Android地图应用开发的核心技术,包括地图集成、定位、网络通信、多线程、数据库操作和路径规划。掌握这些技能对于构建功能丰富的地图应用至关重要。

    arcgis for android 加载sqlite

    总结来说,通过ArcGIS for Android结合JDBC接口,开发者能够轻松地将SQLite数据库中的空间数据加载到Android应用中。这个过程涉及到Android的数据库管理、JDBC连接、SQL查询以及ArcGIS的数据解析和显示。了解这些...

    显示地图_C#_VS_组件gis_

    总结起来,C#与VS结合ArcGIS组件进行GIS开发,主要涉及以下知识点: 1. ArcGIS API for .NET的使用和安装。 2. MapView和Map对象的创建及初始化。 3. ArcGIS Online地图服务的调用。 4. 私有地图服务的加载和身份...

    关系数据库管理空间数据的方式下数据查询方法的研究 (2005年)

    这是基于空间数据类型与空间关系的逻辑概括,涵盖如点、线、面等基本空间数据类型之间的关系。在实践中,关系数据库通过使用特定的查询语言,如结构化查询语言(SQL),来实现对空间数据的查询。这包括利用空间索引、...

    android 百度地图路径规划

    这个Key是你应用与百度地图服务交互的身份凭证,将其添加到你的项目中,通常是放在AndroidManifest.xml文件中的meta-data标签内。 ```xml ... android:name="com.baidu.lbsapi.API_KEY" android:value="你的...

    《GIS开发者》第五期

    - **结论**:总结了MapView控件的优点和潜在应用场景。 #### 五、热点技术:在组件式GIS开发中集成Python - **关键技术点**: - **Python简介**:简述Python语言的特点及其在GIS开发中的优势。 - **Python与组件...

    基于Android平台的路径日记系统开发与设计.pdf

    3. **MapActivity和MapView**:MapActivity和MapView是Android SDK中用于展示和操作地图的组件,它们允许用户在地图上查看、添加和管理路径信息。 4. **数据存储**:系统选择SQLite数据库存储用户的位置信息、跟踪...

    android程序的自动更新 和 基于GPS定位的轨迹存储.rar

    在实现轨迹回放功能时,可以将存储的轨迹点按照时间顺序加载,利用MapView或MapView库在地图上绘制轨迹线。通过动画效果,用户可以直观地看到历史行走路径。为了优化用户体验,还可以添加速度控制、缩放、平移等交互...

    ArcGIS for android实例

    总结来说,ArcGIS for Android提供了一个强大且灵活的平台,使得开发者能够轻松地在Android设备上构建具有专业地图功能的应用。通过理解其配置流程、核心组件及其实战应用,我们可以创建出满足各种需求的地理信息...

    Arcgis地图sample

    samples-android-master`中的样例展示了如何加载不同类型的在线地图或本地地图数据,如TiledMapServiceLayer(瓦片地图服务)、DynamicMapServiceLayer(动态地图服务)和GeodatabaseFeatureTable(地理数据库特征表...

    BaiduMapApi-master.rar

    在地图上显示轨迹可能需要用到`MapView`类,通过它我们可以加载和交互地图,同时使用`Overlay`类或者`Polyline`类来绘制轨迹线。 此外,为了保证用户体验,还需要处理权限问题,例如请求用户授予访问位置的权限。在...

    16.(arcgis api for js篇)arcgis api for js椭圆采集.zip

    4. **处理椭圆几何对象**:拿到椭圆后,可以对其进行进一步的处理,比如计算面积、与其它几何对象的相交检查,或者将其保存到数据库中。 5. **显示结果**:最后,我们可以将绘制的椭圆叠加到地图上,或者以其他方式...

    Android-RunMap一个简单的运动跑步App

    接着在AndroidManifest.xml中添加必要的权限,并在布局文件中嵌入MapView组件。 3. **定位服务** 跑步应用需要实时获取用户的位置信息。Android提供了Location API来实现这一功能。可以使用...

    利用ArcGis API解析FileGDB

    FileGDB是Esri的桌面地理数据库,以单个文件形式存储地理信息,相比传统的个人Geodatabase(MDB)和企业级Geodatabase(SDE),它具有更好的性能和更小的磁盘占用。FileGDB支持矢量数据和栅格数据,并且可以包含多个...

    android旅游记录软件源码

    总结来说,这款"android旅游记录软件源码"涵盖了Android开发的多个核心知识点,包括定位服务的使用、地图显示与轨迹记录、邮件发送功能的实现,以及开源项目的优势。对于想要深入学习Android开发或者有兴趣开发旅游...

    MapDemo-master.zip

    开发者需要在`AndroidManifest.xml`中添加地图相关的权限,然后在布局文件中嵌入`MapView`控件,并通过Java或Kotlin代码初始化并交互。 三、运动数据记录 对于健身应用,记录用户的运动数据至关重要。这可能包括...

    android 通讯录

    一、添加与删除联系人 在Android中,接触通讯录API首先需要获取`ContactsContract`权限,并使用ContentResolver进行操作。添加联系人通常涉及到以下几个步骤: 1. 创建一个ContentValues对象,设置联系人的姓名、...

    Arcgis for android 测距测面积

    地图服务可以是在线的ArcGIS Online服务,也可以是本地的地理数据库。 2. 添加测量工具:ArcGIS SDK提供了一个`MeasurementTool`类,用于测量两点间的直线距离。你可以通过实例化这个类并设置监听器来实现测距功能...

Global site tag (gtag.js) - Google Analytics