android 本地数据库添加数据

1.

private final static String DATABASE_PATH = android.os.Environment
			.getExternalStorageDirectory().getAbsolutePath() + "/citypro";
	private final static String PATH_USE = "MyData";

 2.

// 复制数据库
		boolean blcunzai = checkgpsdb();		
		if (!blcunzai) {
			// 复制数据库到程序目录s
			SQLiteDatabase mydb = copygpsdbtofile();
			mydb.close();
		}

 3.

// 获取当前时间
					Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
					String strnow = formatter.format(curDate);
					System.out.println("now date-->" + strnow);
					// test_s
					boolean blsuccess = InsertGPStoDB(Commons.LNG, Commons.LAT,
							strnow);
 

4.

private static boolean InsertGPStoDB(String longitude, String latitude,
			String updatetime) {

		String databaseFilename = DATABASE_PATH + "/" + PATH_USE + "/"
				+ "gps.db";
		if (databaseFilename == null) {
			return false;
		}

		SQLiteDatabase mydatabase = SQLiteDatabase.openOrCreateDatabase(
				databaseFilename, null);

		if (mydatabase.isOpen()) {
			try {

				String strsqlupdateinfo = "insert into gpsmain(longitude,latitude,updatetime) values("
						+ "'"
						+ longitude
						+ "',"
						+ "'"
						+ latitude
						+ "',"
						+ "'"
						+ updatetime + "')";
				mydatabase.execSQL(strsqlupdateinfo);
				mydatabase.close();
				return true;
			} catch (Exception ex) {

				Log.e("tag:", ex.getMessage());
				return false;
			}
		}

		return true;
	}

	private boolean checkgpsdb() {
		String strfile = DATABASE_PATH + "/" + PATH_USE + "/" + "gps.db";
		File dir = new File(strfile);
		if (dir.exists()) {
			return true;
		} else {
			return false;
		}

	}

	private SQLiteDatabase copygpsdbtofile() {

		try {
			String databaseFilename = DATABASE_PATH + "/" + PATH_USE + "/"
					+ "gps.db";

			File dir = new File(DATABASE_PATH);
			// 如果/sdcard/dictionary目录中存在,创建这个目录
			if (!dir.exists()) {
				Log.i("databaseFilename", "dir.exists()");
				dir.mkdir();

			}
			dir = new File(DATABASE_PATH + "/" + PATH_USE);
			if (!dir.exists()) {
				Log.i("databaseFilename", "dir.exists()");
				dir.mkdir();

			}
			if (!(new File(databaseFilename)).exists()) {
				InputStream is = getResources().openRawResource(R.raw.gps);
				FileOutputStream fos;
				fos = new FileOutputStream(databaseFilename);

				byte[] buffer = new byte[8192];
				int count = 0;
				// 开始复制dictionary.db文件
				while ((count = is.read(buffer)) > 0) {
					fos.write(buffer, 0, count);
				}
				fos.close();
				is.close();
			}

			SQLiteDatabase mydatabase = SQLiteDatabase.openOrCreateDatabase(
					databaseFilename, null);

			return mydatabase;
		} catch (Exception e) {
			e.getMessage();
		}

		return null;

	}
 

相关推荐