DBAdapter 类#
这是我的示例代码,它工作正常。在 AddActivity 中,我将从编辑文本中获取一些值,并使用 DBAdapter 我将保存在 sqlite 中。
package gps.profile.changer;
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;
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_LAT = "latcol";
public static final String KEY_LON = "loncol";
public static final String KEY_LOCNAME = "locnamecol";
public static final String KEY_PROTYPE="protypecol";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "gps";
private static final String DATABASE_TABLE = "locationtb";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table locationtb (_id integer autoincrement primary key,latcol real not null,"
+ "loncol real not null,locnamecol varchar not null, "
+ "protypecol varchar not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
// TODO Auto-generated constructor stub
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
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 locationtb");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a title into the database---
public long insertTitle(double latcol, double loncol, String locnamecol,String protypecol)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_LAT, latcol);
initialValues.put(KEY_LON, loncol);
initialValues.put(KEY_LOCNAME, locnamecol);
initialValues.put(KEY_PROTYPE, protypecol);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular title---
public boolean deleteTitle(String rowId)
{
return db.delete(DATABASE_TABLE, KEY_LOCNAME +
"=" + rowId, null) > 0;
}
//---retrieves all the titles---
public Cursor getAllTitles()
{
return db.query(DATABASE_TABLE, new String[] {
KEY_LAT,
KEY_LON,
KEY_LOCNAME,
KEY_PROTYPE},
null,null,null,null,null);//put extra null if not work
}
//---retrieves a particular title---
public Cursor getTitle(String gen) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {
KEY_LAT,
KEY_LON,
KEY_LOCNAME,
KEY_PROTYPE
},
KEY_PROTYPE + "=" + gen,
null,null,null,null,null);
if (mCursor != null)
{
mCursor.moveToFirst();
Log.e("","");
}
return mCursor;
}
//checking profile saved for that latitude and longitude in db
public Cursor getprofilelist(String gen) throws SQLException
{
Cursor mcursor = db.rawQuery("select * from locationtb where protypecol=? " ,new String [] {gen});
if (mcursor != null)
{
mcursor.moveToFirst();
Log.e("","");
}
return mcursor;
}
public Cursor getLocationProfile(Double a,Double b ) throws SQLException
{
Cursor mcursor = db.rawQuery("select * from locationtb where latcol=? and loncol=?" ,new String [] {String.valueOf(a),String.valueOf(b)});
if (mcursor != null)
{
mcursor.moveToFirst();
Log.e("","");
}
return mcursor;
}
//---updates a title---
public boolean updateTitle(long rowId, String latcol,
String loncol, String locnamecol,String protypecol)
{
ContentValues args = new ContentValues();
args.put(KEY_LAT, latcol);
args.put(KEY_LON, loncol);
args.put(KEY_LOCNAME,locnamecol);
args.put(KEY_PROTYPE, protypecol);
return db.update(DATABASE_TABLE, args,
KEY_LOCNAME + "=" + rowId, null) > 0;
}
}
添加活动
package gps.profile.changer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.location.LocationManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
public class AddActivity extends Activity
{
public EditText locationname;
public EditText latit,longit;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.addlayout);
latit = (EditText) findViewById(R.id.lat1);
longit = (EditText) findViewById(R.id.long1);
locationname = (EditText) findViewById(R.id.locname);
adddata=(ImageView)findViewById(R.id.imageadd);
spinn= (Spinner) findViewById(R.id.spinner1);
locatname=locationname.getText().toString();
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.profiles, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinn.setAdapter(adapter);
spinn.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
spinsave=spinn.getSelectedItem().toString();
//Toast.makeText(AddActivity.this, spinsave, Toast.LENGTH_SHORT ).show();
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
}
}
public void connect(View v)
{
latitude=latit.getText().toString();
longitude=longit.getText().toString();
latdou=Double.parseDouble(latitude);
longdou=Double.parseDouble(longitude);
locatname=locationname.getText().toString();
int latlen=latitude.length();
int lonlen=longitude.length();
int namlen=locatname.length();
if(latlen!=0&&lonlen!=0&&namlen!=0)
{
Toast.makeText(AddActivity.this, "added", Toast.LENGTH_SHORT ).show();
db = new DBAdapter(this);
insert();
startService(new Intent(this, LocationAddActivity.class));
Log.e("added","added");
// update();
// dis("'Vibrate'");
// del("1");
// disAll();
// getlocationpro(latlaa1,lnglaa1);
}
else
{
Toast.makeText(AddActivity.this, "fill all fields", Toast.LENGTH_SHORT ).show();
startService(new Intent(this, LocationAddActivity.class));
}
}
/* private void update(){
db.open();
if (db.updateTitle(1,
"1",
"java ",
"ravi"))
Toast.makeText(this, "Update successful.",
Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "Update failed.",
Toast.LENGTH_LONG).show();
//-------------------
//---retrieve the same title to verify---
Cursor c = db.getTitle(1);
if (c.moveToFirst())
DisplayTitle(c);
else
Toast.makeText(this, "No title found",
Toast.LENGTH_LONG).show();
//-------------------
db.close();
}*/
public void insert(){
db.open();
long id = db.insertTitle(
latlaa1,
lnglaa1,
locatname,
spinsave
);
db.close();
}
/* private void disAll(){
Toast.makeText(AddActivity.this, "disall", Toast.LENGTH_SHORT ).show();
//db = new DBAdapter(this);
db.open();
Cursor c = db.getAllTitles();
if (c.moveToFirst())
{
do {
System.out.println("bool2");
if(latdou==c.getDouble(0)&&longdou==c.getDouble(1))
{
Toast.makeText(AddActivity.this, "Location Already Exist in the Name of:"+c.getString(2), Toast.LENGTH_LONG).show();
// startService(new Intent(this, LocationAddActivity.class));
if(locatname==c.getString(2))
{
Toast.makeText(AddActivity.this, "Location Name Already Exist:"+c.getString(2), Toast.LENGTH_LONG ).show();
// startService(new Intent(this, LocationAddActivity.class));
}
}
} while (c.moveToNext());
}
insert();
db.close();
}*/
private void dis(String j){
db.open();
try{
Cursor c = db.getTitle(j);
if (c.moveToFirst())
{
do {
System.out.println("bool2");
DisplayTitle(c);
} while (c.moveToNext());
}
}catch(Exception e){
System.out.println(e);
}
db.close();
}
/* private void getlocationpro(Double a,Double b){
db.open();
try{
Cursor c = db.getLocationProfile(a,b);
if (c.moveToFirst())
{
do {
System.out.println("bool2");
DisplayTitle(c);
} while (c.moveToNext());
}
}catch(Exception e){
System.out.println(e);
}
db.close();
} */
/*
private void del(String j){
db.open();
if (db.deleteTitle(j))
Toast.makeText(this, "Delete successful.",
Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "Delete failed.",
Toast.LENGTH_LONG).show();
db.close();
}*/
public void DisplayTitle(Cursor c)
{
Toast.makeText(this,
"LAITUDE: " + c.getDouble(0) + "\n" +
"LONGITUDE: " + c.getDouble(1) + "\n" +
"LOCATION NAME: " + c.getString(2)+"\n"+
"PROFILE TYPE: " + c.getString(3),
Toast.LENGTH_LONG).show();
}
private class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
latit = (EditText) findViewById(R.id.lat1);
longit = (EditText) findViewById(R.id.long1);
latlaa1 =arg1.getDoubleExtra("latlaa", 0);
lnglaa1=arg1.getDoubleExtra("lnglaa", 1);
latit.setText(String.valueOf(latlaa1));
longit.setText(String.valueOf(lnglaa1));
get1();
//startService(new Intent(AddActivity.this, LocationAddActivity.class));
//LocationAddActivity laa=new LocationAddActivity();
// laa.get(null);
Toast.makeText(AddActivity.this, "receiver ", Toast.LENGTH_SHORT ).show();
// Intent intent=new Intent(AddActivity.this, LocationAddActivity.class);
// startService(intent);
}
public void get1()
{
db = new DBAdapter(AddActivity.this);
db.open();
Cursor c = db.getLocationProfile(latlaa1,lnglaa1);
if (c.moveToFirst())
{
do {
if(c!=null)
{
// Initialize the location fields
if(c.getString(3).equals("Vibrate"))
{
Toast.makeText(getBaseContext(),"VIBRATE profile activated ",Toast.LENGTH_SHORT).show();
}
else if (c.getString(3).equals("Silent"))
{
Toast.makeText(getBaseContext(),"silent profile activated !",Toast.LENGTH_SHORT).show();
}
else if (c.getString(3).equals("General"))
{
Toast.makeText(getBaseContext(),"Loud profile activated !",Toast.LENGTH_SHORT).show();
}
}
} while (c.moveToNext());
}
else
{
Toast.makeText(getBaseContext(),"else vibrate activated !",Toast.LENGTH_SHORT).show();
mobilemode.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
}
db.close();
}
}
}