android 将.txt文件转化为.db并使用raw下的数据文件

在做城市搜索,此时,需要数据库,可数据源从何处获得?

1.新建一个.txt文件,以固定格式存储城市数据,如:

1||北京
2||天津
3|新疆|乌鲁木齐
4|新疆|奎屯
5|新疆|伊犁
6|新疆|库尔勒
7|新疆|阿克苏
8|青海省|西宁    
9|河北省|石家庄
10|河北省|邯郸
11|河北省|保定

第一个字段为_id,第二个为provience,第三个字段为city

2.建数据库

 public void onCreate(SQLiteDatabase db) {
                Log.d("DatabaseHelper","oncreat database-----------------------------------------");
                db.execSQL("CREATE TABLE "+ CITY_TABLE + " ("+
                        "_id INTEGER PRIMARY KEY , "+
                        "province TEXT, " +
                        "city TEXT);");                
                        
            }

到系统的/data/data目录下的对应包下查看一下是否数据库已建好。

3.将.txt数据导入到数据库下

将.txt文件放到应用程序对应的databases目录下
adb push ~/桌面/city.txt  /data/data/com.android.weather/databases

# cd /data/data/com.android.weather/databases
# ls
city.txt
city_search.db
# sqlite3 city_search.db
sqlite> .tables
android_metadata  citytable
sqlite> .import city.txt citytable
adb pull /data/data/com.android.weather/databases/city_search.db ~/桌面

现在已经获取了一个city_search.db的文件在桌面上。

4.使用

package com.android.weather.db;

import java.io.File;

import java.io.FileOutputStream;
import java.io.InputStream;


import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.util.Log;
import com.android.weather.R;

public class CityDataProvider extends ContentProvider {
	private static final String TAG = "CityDataProvider";
	
	private static final String AUTHORITY = "com.android.weather.db.city";
	private DatabaseHelper mDatabase;
	public static final Uri CONTENT_URI = Uri.parse("content://"+AUTHORITY+"/city");
	private final static String dataBaseDesDir =  "/data/data/com.android.weather/databases";

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		Log.d(TAG,"query");
		SQLiteDatabase db = mDatabase.getReadableDatabase();		
		return db.query(DatabaseHelper.CITY_TABLE, projection, selection, selectionArgs, null, null, null);
	}
		
	
	public boolean onCreate() {

        mDatabase = DatabaseHelper.getInstance(getContext());
        onCreateDatabaseDir();
        
		return true;
	}
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		return 0;
	}
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		return 0;
	}
	public String getType(Uri uri) {
		return null;
	}
	public Uri insert(Uri uri, ContentValues values) {
		return null;
	}
	
	 private static  class DatabaseHelper extends SQLiteOpenHelper {
	        private static final String DATABASE_NAME = "city_search.db";
	        private static final String CITY_TABLE = "citytable";
	        private static final int DATABASE_VERSION =4;
	    	static synchronized DatabaseHelper getInstance(Context context) {

	    		return new DatabaseHelper(context);
	        }


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

	        public void onCreate(SQLiteDatabase db) {
	        	Log.d("DatabaseHelper","oncreat database-----------------------------------------");
//	        	db.execSQL("CREATE TABLE "+ CITY_TABLE + " ("+
//	    				"_id INTEGER PRIMARY KEY , "+
//	    				"province TEXT, " +
//	    				"city TEXT);");	        	
                        
	        }
	   	 

	        public void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) {
//	        	db.execSQL("DROP TABLE IF EXISTS "+CITY_TABLE);
//	    		onCreate(db);

	        }
	    }
	 
	 private  void onCreateDatabaseDir() {
			
			File dir = new File(dataBaseDesDir);

			if (!dir.exists()) {
				try {
					dir.mkdir();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		
			copyDatabaseFile(dataBaseDesDir);
		}
		
		
		private  void copyDatabaseFile(String destDir) {
			File dest = new File(destDir+"/"+DatabaseHelper.DATABASE_NAME);       
			if(dest.exists())
			{
				return ;
			}
			
			try {
				Log.d(TAG,"the database is not exit,then copy it---------------------");
				
				InputStream in = CityDataProvider.this.getContext().getResources().openRawResource(R.raw.city_search);
				int size = in.available();
				byte buf[] = new byte[size];
				in.read(buf);
				in.close();
				
				FileOutputStream out = new FileOutputStream(dest);
				out.write(buf);
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

}



你可能感兴趣的:(android,exception,String,table,Integer,database)