首页 > 数据库 >SQLiteOpenHelper&SharedPreferences练习

SQLiteOpenHelper&SharedPreferences练习

时间:2023-04-07 10:04:32浏览次数:55  
标签:db 练习 SQLiteOpenHelper SharedPreferences DatabaseHelper import android null publ


目录结构:


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;
	}
}







  • SQLiteOpenHelper&SharedPreferences练习_SQL

  • 大小: 15.8 KB
  • SQLiteOpenHelper&SharedPreferences练习_SQL_02

  • 大小: 22.8 KB
  • SQLiteOpenHelper&SharedPreferences练习_SQL_03

  • 大小: 12.8 KB
  • BMI.zip (75.6 KB)
  • 下载次数: 12
  • 查看图片附件

标签:db,练习,SQLiteOpenHelper,SharedPreferences,DatabaseHelper,import,android,null,publ
From: https://blog.51cto.com/u_5454003/6174594

相关文章

  • 循环语句练习(2)
    1.数组项目求和点击查看代码intsum=0;int[]s=newint[6]{2,3,4,7,9,6};foreach(intiins){sum+=i;}Console.WriteLine(sum);2.数组项求最大值和最小值......
  • 结对编程——四则运算练习题
    结对编程题目如下:小学老师要每周给同学出300道四则运算练习题。这个程序有很多种实现方式:C/C++C#/VB.net/JavaExcelUnixShellEmacs/Powershell/VbscriptPerlPython一个或两个运算符(a+b或a+b+c),100以内的数字,不需要写答案。需要检查答案是否正确,并且保证答案在0......
  • AIArena Frontend 初步练习
    尝试对starter项目的页面进行改变修改侧边栏,只留下最上面的「仪表盘」和「列表页」两个大模块inSideNav.vuethecodeforthesidebarmenuis:<menu-content:navData="menu"/>fromtherewecangettoMenuContent.vueIthinkitisreferencingtheitemsinalis......
  • Python小练习:权重初始化(Weight Initialization)
    Python小练习:权重初始化(WeightInitialization)作者:凯鲁嘎吉-博客园 http://www.cnblogs.com/kailugaji/调用Pytorch中的torch.nn.init.xxx实现对模型权重与偏置初始化。1.weight_init_test.py1#-*-coding:utf-8-*-2#Author:凯鲁嘎吉CoralGajic3#https://w......
  • 链表练习4
    已知整型链表,设计算法,删除所有结点值为x的结点,删除的结点个数通过形参返回。#include<stdio.h>#include<stdlib.h>typedefstructnode{intdata;structnode*next;}Node,*LinkList;LinkListcreate(){LinkListh,r,s;h=(LinkList)malloc(sizeof(Node));r=h;inta;sc......
  • Python小练习:处理字符串
    Python小练习:处理字符串作者:凯鲁嘎吉-博客园 http://www.cnblogs.com/kailugaji/介绍两种处理字符串的方式:1.将英语名词单数转化为复数形式(仅适用于一般形式),2.将字符串(带有下换线_)转化为驼峰化形式。1.word_test.py1#-*-coding:utf-8-*-2#Author:凯鲁嘎吉......
  • 2023_4_5 蓝桥杯练习
    《P8671[蓝桥杯2018国AC]约瑟夫环 循环(%)问题》   我尝试用STL中的list与vector进行模拟可以发现复杂度都是>=O(N*K)的,会超时只有通过数学推式来得到全部正确的答案这里简单说一下STLlist与vector中对插入,删除元素的用法:list:......
  • NFS练习题
    NFS练习题1.开放/nfs/share目录,提供给任意用户只读(/etc/exportsro)查询1.任意客户端2.任意的用户​​​​ 服务端showmoutexportfssystemctlstartnfs 修改了nfs配置文件,需要重启什么吗?修改了nfs配置文件,只需要让nfs重新读取该配置文件即可,你都不需要重新,因为你......
  • 练习——集合排序
    packagecom.collection_.list_;publicclassBook{privateStringname;privateStringauther;privatedoubleprice;publicBook(Stringname,Stringauther,doubleprice){this.name=name;this.auther=auther;......
  • 链表练习3
    已知整型链表,设计算法,在所有结点值为x的结点前插入结点值为y的结点,插入的结点个数通过函数值返回。#include<stdio.h>#include<stdlib.h>typedefstructnode{//用Node代替structnodeinta;structnode*next;}Node,*LinkList;LinkListcreate();Link......