SQLiteOpenHelper&SharedPreferences练习

目录结构:
[img]http://dl.iteye.com/upload/attachment/361683/f6d512c1-f66c-38c4-9b54-76ef1e64c08c.png[/img]

package com.dc.app;

import java.text.DecimalFormat;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class App extends Activity {
private static final String TAG="App";
/** Called when the activity is first created. */
private EditText height,weight;
private Button submit,nextpage,locale,toList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
// this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
// WindowManager.LayoutParams.FLAG_FULLSCREEN);
// this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

setContentView(R.layout.main);

DisplayMetrics dm=new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenWidth=dm.widthPixels;
int screenHeight=dm.heightPixels;

Toast.makeText(this, screenWidth+"*"+screenHeight, Toast.LENGTH_LONG).show();//320*480

height=(EditText)this.findViewById(R.id.height);
weight=(EditText)this.findViewById(R.id.weight);
submit=(Button)this.findViewById(R.id.submit);
submit.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String s_h=height.getText().toString();
String s_w=weight.getText().toString();
if(s_h.equals("")||s_w.equals("")){
Toast.makeText(App.this, R.string.error, Toast.LENGTH_LONG).show();
return;
}
double h=Double.parseDouble(s_h)/100;
double w=Double.parseDouble(s_w);
double bmi=w/(h*h);
Toast.makeText(App.this, getText(R.string.result).toString()+new DecimalFormat("0.00").format(bmi), Toast.LENGTH_LONG).show();
if(bmi>25){
showNotify("减肥通知", "您应该减肥啦!");
}else if(bmi<20){
showNotify("增肥计划", "您应该多吃点!");
}else{
showNotify("好身材", "您应该保持您的身材!");
}
}
});
nextpage=(Button)findViewById(R.id.nextpage);
nextpage.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent();
intent.setClass(App.this, Report.class);
Bundle bundle=new Bundle();
bundle.putString("key_height", height.getText().toString());
bundle.putString("key_weight", weight.getText().toString());
intent.putExtras(bundle);//附加物,为意图追加额外的数据
startActivity(intent);
}
});
locale=(Button)findViewById(R.id.locale);
locale.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Resources res=getResources();
Configuration config=res.getConfiguration();
if(config.locale==Locale.SIMPLIFIED_CHINESE){
config.locale=Locale.ENGLISH;
}else{
config.locale=Locale.SIMPLIFIED_CHINESE;
}
DisplayMetrics dm=res.getDisplayMetrics();
res.updateConfiguration(config, dm);
}

});
toList=(Button)findViewById(R.id.toList);
toList.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(App.this, DummyNote.class);
startActivity(intent);
}

});
}

private void showNotify(String title,String content){
Notification notice=new Notification();
notice.icon=android.R.drawable.stat_sys_warning;
notice.tickerText=getText(R.string.label);
notice.when=10L;
notice.defaults=Notification.DEFAULT_SOUND;
notice.setLatestEventInfo(this, title,content, PendingIntent.getActivity(this, 0, null, 0));

NotificationManager manager=(NotificationManager)getSystemService(this.NOTIFICATION_SERVICE);
manager.notify(0,notice);
}

@Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
return super.onContextItemSelected(item);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
}

private static final int DIALOG_ABOUT = 1;
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
switch (id) {
case DIALOG_ABOUT:
Dialog loginDialog=new AlertDialog.Builder(this)
.setTitle("BMI")
.setMessage(R.string.label2)
.setCancelable(true)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
})
.setNegativeButton(R.string.homepage, new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
Uri uri=Uri.parse(getString(R.string.uri));
Intent intent=new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent);
}
})
.create();
loginDialog.setCanceledOnTouchOutside(true);
return loginDialog;

default:
break;
}
return super.onCreateDialog(id);
}

public static final int menu_id_about=1;
public static final int menu_id_exit=2;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
menu.add(0, menu_id_about, 0, R.string.about).setShortcut('1', 'a');//设置快捷键
menu.add(0, menu_id_exit, 0, R.string.exit).setShortcut('2', 'e');//设置快捷键
return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case menu_id_about:
showDialog(DIALOG_ABOUT);
break;
case menu_id_exit:
save();
this.finish();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
menu.findItem(menu_id_about).setVisible(true).setIcon(android.R.drawable.ic_menu_info_details);
menu.findItem(menu_id_exit).setVisible(true).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
return super.onPrepareOptionsMenu(menu);
}

private void save(){
SharedPreferences setting=this.getPreferences(Activity.MODE_PRIVATE);
setting.edit().putString("HEIGHT", height.getText().toString())
.putString("WEIGHT", weight.getText().toString())
.commit();
}

private void read(){
SharedPreferences setting=this.getPreferences(Activity.MODE_PRIVATE);
height.setText(setting.getString("HEIGHT", ""));
weight.setText(setting.getString("WEIGHT", ""));
}

@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
save();
}

@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
read();
}


}


package com.dc.helper;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

public static final String databaseName="bmi.db";
public static final String tableName="notes";
public static final int databaseVersion=1;

public static final String field0="_id";
public static final String field1="note";
public static final String field2="created";
//创建或打开数据库
public DatabaseHelper(Context context) {
super(context, databaseName, null, databaseVersion);
// TODO Auto-generated constructor stub
}

//当数据库被创建时触发创建表
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sql="create table "+tableName+"("+field0+" INTEGER PRIMARY KEY,"+field1+" TEXT,"+field2+" INTEGER);";
db.execSQL(sql);
}

//升级数据库时触发
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub

String sql="DROP TABLE IF EXISTS "+tableName;
db.execSQL(sql);
onCreate(db);
}


}


package com.dc.adaper;

import java.text.SimpleDateFormat;
import java.util.Date;

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

import com.dc.helper.DatabaseHelper;

public class DatabaseAdaper {
Context content;
DatabaseHelper helper;
SQLiteDatabase db;
public DatabaseAdaper(Context content){
this.content=content;
open();
}
public void open(){
helper=new DatabaseHelper(content);//创建或打开数据库
db=helper.getWritableDatabase();//真正创建
}
public void close(){
db.close();
}
public Cursor list(){
// return db.rawQuery("SELECT * FROM "+DatabaseHelper.tableName, null);
return db.query(DatabaseHelper.tableName, new String[]{DatabaseHelper.field0,DatabaseHelper.field1,DatabaseHelper.field2}, null, null, null, null, null);
}
public long insert(String note){
Date now=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
ContentValues values=new ContentValues();
values.put(DatabaseHelper.field1, note);
values.put(DatabaseHelper.field2, sdf.format(now));
return db.insert(DatabaseHelper.tableName, null, values);
}
public boolean delete(long id){
return db.delete(DatabaseHelper.tableName, DatabaseHelper.field0+"="+id, null)>0;
}

public Cursor get(long id){
Cursor cursor=db.query(DatabaseHelper.tableName, new String[]{DatabaseHelper.field0,DatabaseHelper.field1,DatabaseHelper.field2}, DatabaseHelper.field0+"="+id, null, null, null, null);
if(cursor!=null){
cursor.moveToFirst();
}
return cursor;
}

public boolean update(long id,String note){
ContentValues values=new ContentValues();
values.put(DatabaseHelper.field1, note);
return db.update(DatabaseHelper.tableName, values, DatabaseHelper.field0+"="+id, null)>0;
}
}


[img]http://dl.iteye.com/upload/attachment/361686/2269a2c6-b965-38d2-8eb6-43f9b8eed2ca.png[/img]

[img]http://dl.iteye.com/upload/attachment/361688/fa9fa485-019d-3ed3-b29c-1daea7e72bed.png[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SQLiteOpenHelperAndroid系统提供的一个用于管理SQLite数据库的帮助类,它封装了数据库的创建、升级和降级等操作。使用SQLiteOpenHelper可以方便地创建和管理SQLite数据库,避免了手动编写SQL语句的繁琐过程。 SQLiteOpenHelper类的使用步骤如下: 1. 自定义一个继承自SQLiteOpenHelper的帮助类,并实现onCreate()、onUpgrade()和onDowngrade()等方法。 2. 在自定义的帮助类中重写onCreate()方法,创建数据库和表格。 3. 在自定义的帮助类中重写onUpgrade()方法,升级数据库版本。 4. 在自定义的帮助类中重写onDowngrade()方法,降级数据库版本。 5. 在应用程序中创建自定义的帮助类对象,并调用getWritableDatabase()或getReadableDatabase()方法获取可读写的数据库对象。 示例代码: ```java public class MyDatabaseHelper extends SQLiteOpenHelper { public static final String CREATE_BOOK = "create table Book (" + "id integer primary key autoincrement, " + "author text, " + "price real, " + "pages integer, " + "name text)"; public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_BOOK); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // 升级数据库 } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { // 降级数据库 } } ``` ```java MyDatabaseHelper dbHelper = new MyDatabaseHelper(context, "BookStore.db", null, 1); SQLiteDatabase db = dbHelper.getWritableDatabase(); // 获取可写数据库对象 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值