Get the name of the province city district through the database __ database

Source: Internet
Author: User
Tags sqlite try catch

Reprint please indicate the source, thank http://blog.csdn.net/harryweasley/article/details/46557807

The main purpose of this blog is to explain how to save the database files to the mobile phone system files, and can display the names of various provinces and cities.

There are three tables in the database, they are (I will upload the entire file and the database file later)

Provincial table

CREATE TABLE IF not EXISTS ' fs_province ' (
  ' Provinceid ' bigint is not NULL,
  ' provincename ' varchar () DEFAULT NU LL,
  ' datecreated ' datetime default NULL,
  ' dateupdated ' datetime default NULL,
  PRIMARY KEY (' Provinceid ')
) Engine=myisam DEFAULT Charset=utf8;

City tables

CREATE TABLE IF not EXISTS ' fs_city ' (
  ' Cityid ' bigint not NULL,
  ' cityname ' varchar ' () DEFAULT null,
  ' Zip Code ' varchar default NULL,
  ' Provinceid ' bigint default null,
  ' datecreated ' datetime default null,< c12/> ' dateupdated ' datetime default NULL,
  PRIMARY KEY (' Cityid ')
) engine=myisam default Charset=utf8;

County table

CREATE TABLE IF not EXISTS ' fs_district ' (
  ' Districtid ' bigint is not NULL,
  ' districtname ' varchar () DEFAULT NU LL,
  ' Cityid ' bigint default null,
  ' datecreated ' datetime default NULL,
  ' dateupdated ' datetime default NULL,
  PRIMARY KEY (' Districtid ')
) Engine=myisam DEFAULT Charset=utf8;

Attention:

The province table and the city table, all have Beijing, Shanghai, Chongqing, Tianjin these four cities, therefore must judge for oneself.


First look at the effect of the picture:


We put the binary database file under the Res/raw of the project, as shown in the figure:



The main function of the entire program, I have been encapsulated in the CityInfoDataSupport2 this class.

Package com.example.province;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;

Import java.util.ArrayList;
Import Android.content.Context;
Import Android.database.Cursor;
Import Android.database.sqlite.SQLiteDatabase;
Import Android.database.sqlite.SQLiteDatabase.CursorFactory;
Import android.database.sqlite.SQLiteException;
Import Android.database.sqlite.SQLiteOpenHelper;

Import android.os.Environment;
	public class CityInfoDataSupport2 {private static CityInfoDataSupport2 cityinfodatasupport;
	public static final String package_name = "Com.example.province"; /** * Database in the mobile phone system memory Path * * private static String Database_path = "/data" + environment.getdatadirectory () + "/" +packa
	Ge_name + "/databases/";
	/** * The name of the database/public static final String dbname = "mzk_db";

	Private Sqlitedatabase MSDB;
		public static CityInfoDataSupport2 getinstance (context) {initdatabase); if (Cityinfodatasupport = =NULL) {Cityinfodatasupport = new CityInfoDataSupport2 ();

	return cityinfodatasupport;
		/** * Initial database/private static void Initdatabase (context context) {Boolean dbexist = Checkdatabase ();
		if (dbexist) {} else {//if not present, the data in raw is stored in the cell phone SD card copydatabase (context); /** * Copy Database to mobile phone specified folder * * @throws ioexception/private static void Copydatabase (context context) {STR
		ing databasefilenames = database_path + dbname;
		File dir = new file (Database_path);
		FileOutputStream OS = null;
		InputStream is = null;
		To determine if a folder exists, do not exist to create an if (!dir.exists ()) {dir.mkdirs ();
			try {//get the output stream OS = new FileOutputStream (databasefilenames) of the database;
			The input stream to get the data file is = Context.getresources (). Openrawresource (r.raw.mzk_db);
			byte[] buffer = new byte[8192];
			int count = 0;
				while ((count = is.read (buffer))!=-1) {os.write (buffer, 0, count);
			Os.flush (); }//The reason is not initialized here, because this is a static method, and MSDB is not set to static, nor is it recommended to set static//msdb = SQLitedatabase.openorcreatedatabase (Database_path +//dbname, NULL);
		catch (Exception e) {e.printstacktrace ();
				Finally {try {os.close ();
			Is.close ();
			catch (IOException e) {e.printstacktrace (); }}/** * To determine whether the database exists * * @return/private static Boolean checkdatabase () {Sqlitedatabase CheckDB =
		Null
		String databasefilename = Database_path + dbname; To add a try catch method with try {///Return the latest database CheckDB = sqlitedatabase.opendatabase (DatabaseFileName, NULL, Sqlitedat Abase.
		OPEN_READONLY);
		The catch (Sqliteexception e) {//Todo:handle exception} if (CheckDB!= null) {checkdb.close (); //If CheckDB is null, there is no database, returns false return CheckDB = = null?
	False:true; /** * Query all provinces for information * * @return Province Info/public arraylist<city> queryprovince () {//CREATE DATABASE MSDB = Sqlit
		Edatabase. Openorcreatedatabase (Database_path + dbname, NULL);
arraylist<city> list = new arraylist<city> ();		String sql = "SELECT * from Fs_province";
		Cursor Cursor = msdb.rawquery (sql, NULL);
			while (Cursor.movetonext ()) {City city = new City ();
			String id = cursor.getstring (cursor.getcolumnindex ("Provinceid"));
			String name = cursor.getstring (cursor. Getcolumnindex ("Provincename"));
			City.setname (name);
			City.setid (ID);
		List.add (city);
		} if (cursor!= null) {cursor.close ();
	} return list; /** * Through the provinces to find the city * * @param the ID of the Provinceid * province * @return All cities in the governorate * * Public ARRAYLIST&LT;CITY&G T Querycitybyprovince (String Provinceid) {//CREATE DATABASE MSDB = sqlitedatabase. Openorcreatedatabase (Database_path + DbN
		AME, NULL);
		arraylist<city> list = new arraylist<city> ();
		String sql = "SELECT * from fs_city where provinceid=" + Provinceid;
		Cursor Cursor = msdb.rawquery (sql, NULL);
			while (Cursor.movetonext ()) {City city = new City ();
			String id = cursor.getstring (cursor.getcolumnindex ("Cityid")); String name = Cursor.getstring (Cursor.getcolumnindex ("CityName"));
			City.setname (name);
			City.setid (ID);
		List.add (city);
		} if (cursor!= null) {cursor.close ();

	} return list; /** * Through the city to find the county area * * * @param provinceid * Province ID * @return All cities in the governorate/public ARRAYLIST&LT;CITY&G T  Querydistrictbycity (String Cityid) {//CREATE DATABASE MSDB = sqlitedatabase. Openorcreatedatabase (Database_path + dbname,
		NULL);
		arraylist<city> list = new arraylist<city> ();
		String sql = "SELECT * from Fs_district where cityid=" + Cityid;
		Cursor Cursor = msdb.rawquery (sql, NULL);
			while (Cursor.movetonext ()) {City city = new City ();
			String id = cursor.getstring (cursor.getcolumnindex ("Districtid"));
			String name = cursor.getstring (cursor. Getcolumnindex ("Districtname"));
			City.setname (name);
			City.setid (ID);
		List.add (city);
		} if (cursor!= null) {cursor.close ();

	} return list; public void CloseDataBase () {if (MSDB!= null) {Msdb.close ();
 }
	}
}

In this class, the database binaries in the program are copied to the phone system memory. There are very detailed comments in the code, and I don't say much here.


Next is the content of each activity, is very simple, I will put a bar, and then I will upload the entire program.

Package com.example.province;

Import java.util.ArrayList;
Import android.app.Activity;
Import android.content.Intent;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.AdapterView;
Import Android.widget.AdapterView.OnItemClickListener;

Import Android.widget.ListView; /** * Name of the province, including Beijing, Shanghai, Tianjin, Chongqing, Hong Kong, Macau These six are special examples * @author LGX * * */public class Mainactivity extends activity {ARRAYLIST&L T
	City> Province;

	ListView province_list;
		@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

		Setcontentview (R.layout.activity_main);
		Province_list = (ListView) Findviewbyid (r.id.province_list);
		Province = Cityinfodatasupport2.getinstance (this). Queryprovince ();
		Testadapter adapter = new Testadapter (this, province);
		Province_list.setadapter (adapter); Province_list.setonitemclicklistener (New Onitemclicklistener () {@Override public void Onitemclick (Adapterview<?> Parent, view view, int position, long id) {String Proviceid = province.get (position). GetId (
				);
				String provicename = province.get (position). GetName ();
					if (provicename.equals ("Beijing") | | provicename.equals ("tianjin") | | provicename.equals ("shanghai") | | provicename.equals ("chongqing")) {
					Intent Intent = new Intent (mainactivity.this, Districtactivity.class);
					Intent.putextra ("Pcode", Proviceid);
				StartActivity (Intent);
					else {Intent Intent = new Intent (mainactivity.this, Cityactivity.class);
					Intent.putextra ("Pcode", Proviceid);
				StartActivity (Intent);
	}

			}
		});
		} @Override protected void OnDestroy () {Super.ondestroy ();
	Cityinfodatasupport.getinstance (This). Close ();
 }

}


Project Download Address: http://download.csdn.net/detail/harryweasley/8807143

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.