zoukankan      html  css  js  c++  java
  • Android开发 ---SQLite数据库,lock文件,结果集游标,适配器,安全退出,给连接设置下划线,编辑器,投影,ContentValues存储,DbHelper,activity栈

    目录截图:

      

    1、activity_main.xml

     主界面效果:

          

    <?xml version="1.0" encoding="utf-8"?>
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
       <LinearLayout
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:id="@+id/activity_main"
           android:orientation="vertical"
           >
          <TextView
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:id="@+id/title"
              android:textSize="25dp"
              />
          <Button
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:text="Insert()方法案例"
              android:onClick="test_1"
              />
          <LinearLayout
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="horizontal"
              >
             <Button
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:text="添加学生"
                 android:onClick="addStu"
                 android:layout_weight="1"
                 />
             <Button
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:text="测试监听"
                 android:onClick="test"
                 android:layout_weight="1"
                 />
             <Button
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:text="学生信息列表"
                 android:layout_weight="1"
                 android:onClick="loadStuList"
                 />
          </LinearLayout>
          <ListView
              android:layout_width="match_parent"
              android:layout_height="350dp"
              android:id="@+id/stuListView"
              android:divider="@android:color/holo_orange_light"
              android:dividerHeight="2dp"
              />
          <Button
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:text="安全退出"
              android:onClick="safeExit"
              />
       </LinearLayout>
    </ScrollView>

    2、MainActivity.java

    package com.nf.android_sqlite2;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.database.Cursor;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.ListView;
    import android.widget.SimpleCursorAdapter;
    import android.widget.TextView;
    import android.widget.Toast;
    import com.nf.dao.StuDao;
    import com.nf.utils.MyApplication;
    
    public class MainActivity extends Activity {
        private TextView title;
        private ListView stuListView;
       //适配器
    private SimpleCursorAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MyApplication.getInstance().addActivity(this); title = (TextView)findViewById(R.id.title); stuListView = (ListView)findViewById(R.id.stuListView); //获取当前登录人
         //获得一个SharedPreferences对象,第一个参数为对象文件的名字,第二个参数为对此对象的操作权限,MODE_PRIVATE权限是指只能够被本应用所读写 
         //在系统中有一个lock的文件专门保存本应用的用户登录信息    
            SharedPreferences sp = getSharedPreferences("lock",MODE_PRIVATE);
         //将登录人的用户名取出来 String name
    = sp.getString("LoginName","");
         //判断该登录人的用户名是否已经存在,如果不存在,弹框提示请先登录,然后跳转到登录界面
    if (name.length()==0){ Toast.makeText(this,"请先登录",Toast.LENGTH_SHORT).show(); Intent intent = new Intent(this,LoginActivity.class); startActivity(intent); }else{
           //如果登录人的用户名已经存在,则获取用户名并在主界面上显示 xxx欢迎你的光临 title.setText(name
    +",欢迎您的光临"); } }   
      //主界面上显示一个添加学生信息的按钮,点击按钮,页面跳转到添加学生信息的界面
    public void addStu(View view) { Intent intent = new Intent(this,AddStuActivity.class); startActivity(intent); }
      //主界面上显示一个测试监听的按钮,点击按钮,跳转到测试监听的界面
    public void test(View view) { Intent intent = new Intent(this,TestActivity.class); startActivity(intent); }   //当当前Activity界面一显示出来时就去调用loadStuList()方法查询出所有的学生及班级信息 @Override protected void onStart(){ super.onStart(); loadStuList(null); } public void loadStuList(View view){ //查询出所有的学生及其班级信息
         //Cursor是结果集游标,通过实例化一个StuDao,调用其中的findStuInfo()方法查询出所有的学生及班级信息,保存在结果集游标中 Cursor cursor = new StuDao(this).findStuInfo();
         //构建适配器所需的数据资源 String[] from
    = {"sname","cname","ssex","sage","shobby"}; int[] to ={R.id.stuName,R.id.clsName,R.id.stuSex,R.id.stuAge,R.id.stuHobby};
         //通过适配器给指定的布局文件中填充数据
         //第一个参数是指
     stuListView 所在的 Activity,第二个参数是指 显示stuListView项的布局文件    
         //第四个参数指定cursor中哪些列的数据将绑定(显示)到 UI 中。如果 cursor 无效, 则该参数可为 null。
         //指定用于显示 "from" 参数指定的数据列表的 views。 这些 views 必须都是 TextViews。
         //"from" 参数的前 N 个值(valus)和 "to" 参数的前 N 个 views 是一一对应的关系。如果 cursor 无效,则该参数可为 null。
         //FLAG_AUTO_REQUERY会自动查询如果数据库中的数据发生了变化以实时反映到界面上来,3.0之后废弃了,3.0之后使用FLAG_REGISTER_CONTENT_OBSERVER,
         //NO_SELECTION可以改为这个FLAG_REGISTER_CONTENT_OBSERVER
    adapter
    = new SimpleCursorAdapter(this,R.layout.layout_stu_list,cursor,from,to,SimpleCursorAdapter.NO_SELECTION); stuListView.setAdapter(adapter); }
       //点击Insert()方法案例按钮,页面跳转到对某个学生进行增删改查的界面
    public void test_1(View view){ Intent intent = new Intent(this,InsertActivity.class); startActivity(intent); }
      //安全退出
      //登录人的用户信息都保存在lock文件中,如何对文件进行编辑呢,首先需要创建编辑器Editor
      //通过编辑器的clear()方法将里面的用户信息清空,然后提交一下,
    public void safeExit(View view){ //Editor editor = sharedPreferences.edit();//获取编辑器 //SharedPreferences类特别适合用于保存软件配置参数 //使用SharedPreferences保存数据,其背后是用xml文件存放数据,文件存放在/data/data/<package name>/shared_prefs目录下 //getSharedPreferences(name,mode)方法的第一个参数用于指定该文件的名称,名称不用带后缀,后缀会由Android自动加上。
         //方法的第二个参数指定文件的操作模式,共有四种操作模式
    //四种模式: //Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容 //Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件. //Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件. SharedPreferences.Editor editor = getSharedPreferences("lock",MODE_PRIVATE).edit(); //清空编辑器 editor.clear(); editor.commit(); //清空Activity栈 MyApplication.getInstance().exit(); } }

    3、activity_add_stu.xml

      描述:

        这是添加学生界面布局

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/activity_add_stu"
        android:orientation="vertical"
        android:layout_marginTop="5dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="添加学生"
            android:textSize="25dp"
            android:gravity="center"
            />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/sname"
            android:hint="请输入学生姓名"
            />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/sage"
            android:hint="请输入学生年龄"
            />
        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:id="@+id/ssexgroup"
            >
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/sex_1"
                android:text="男"
                android:checked="true"
                />
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/sex_2"
                android:text="女"
                />
        </RadioGroup>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            >
            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/shobby_1"
                android:text="睡觉"
                />
            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/shobby_2"
                android:text="美食"
                />
            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/shobby_3"
                android:text="游戏"
                />
        </LinearLayout>
        <Spinner
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/scno"
            />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            >
            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="添加学生"
                android:onClick="addStu"
                android:layout_weight="1"
                />
            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="取消"
                android:onClick="doBack"
                android:layout_weight="1"
                />
        </LinearLayout>
    </LinearLayout>

    4、AddStuActivity.java

    package com.nf.android_sqlite2;
    
    import android.app.Activity;
    import android.database.Cursor;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.CheckBox;
    import android.widget.EditText;
    import android.widget.LinearLayout;
    import android.widget.RadioButton;
    import android.widget.RadioGroup;
    import android.widget.SimpleCursorAdapter;
    import android.widget.Spinner;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.nf.dao.ClassDao;
    import com.nf.dao.StuDao;
    import com.nf.entity.TbStu;
    import com.nf.utils.MyApplication;
    
    public class AddStuActivity extends Activity {
      //获取布局控件元素
      //下拉列表控件
    private Spinner spin_class;
      //适配器
    private SimpleCursorAdapter adapter;
      //文本输入框
    private EditText sname,sage;
      //单选按钮
    private RadioGroup ssexgroup;
      //多选按钮
    private CheckBox shobby1,shobby2,shobby3;
      //性别默认为男 String sex
    = "男"; private RadioButton sex1,sex2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_stu);
         //将当前Activity放入Activity栈,为了到时候安全退出时,清空当前Activity MyApplication.getInstance().addActivity(
    this);
         //编号 spin_class
    = (Spinner)findViewById(R.id.scno);
         //姓名 sname
    = (EditText)findViewById(R.id.sname);
         //年龄 sage
    = (EditText)findViewById(R.id.sage);
         //爱好 shobby1
    = (CheckBox)findViewById(R.id.shobby_1); shobby2 = (CheckBox)findViewById(R.id.shobby_2); shobby3 = (CheckBox)findViewById(R.id.shobby_3);
         //性别 sex1
    =(RadioButton)findViewById(R.id.sex_1); sex2=(RadioButton)findViewById(R.id.sex_2); ssexgroup = (RadioGroup)findViewById(R.id.ssexgroup);
         //给性别组设置一个选择改变监听器,专门监听RadioGroup组件 ssexgroup.setOnCheckedChangeListener(
    new RadioGroup.OnCheckedChangeListener(){
             @Override
    public void onCheckedChanged(RadioGroup radioGroup,int i){//注意:这个i的值是很大的,不是1,2,3,4
               if (i==sex1.getId()){
                //如果选中的是男,就获取其id RadioButton rb
    = (RadioButton)findViewById(i);
                //通过id获取其内容并转化为字符串 sex
    = rb.getText().toString();
                //弹出提示 Toast.makeText(AddStuActivity.
    this,"男 = "+sex,Toast.LENGTH_SHORT).show(); } if (i==sex2.getId()){ RadioButton rb = (RadioButton)findViewById(i); sex = rb.getText().toString(); Toast.makeText(AddStuActivity.this,"女 = "+sex,Toast.LENGTH_SHORT).show(); } } }); }
      //onResume()是当该activity与用户能进行交互时被执行,用户可以获得activity的焦点,能够与用户交互。 @Override
    protected void onResume(){ super.onResume(); //取出班级并绑定到Spinner中
         //调用班级ClassDao()的getClassCursor()方法查询出所有的班级,并保存在结果集游标中
    Cursor cursor = new ClassDao(this).getClassCursor();
         //设置适配器资源 String[] from
    = {"_id","cname"}; int[] to = {R.id.cno,R.id.cname};
         //给spin_class绑定适配器,将结果集游标里的数据填入到下拉列表中 adapter
    = new SimpleCursorAdapter(this,R.layout.layout_spinner_class,cursor,from,to,SimpleCursorAdapter.NO_SELECTION); spin_class.setAdapter(adapter); } //添加学生 public void addStu(View view){
         //获取id为sname的文本输入框的文本内容并转化为字符串 String name
    = sname.getText().toString();
         //同上
    int age = Integer.parseInt(sage.getText().toString()); String hobby = ""; if (shobby1.isChecked()){ hobby = shobby1.getText()+","; } if (shobby2.isChecked()){ hobby = hobby+shobby2.getText()+","; } if (shobby3.isChecked()){ hobby = hobby+shobby3.getText()+","; }
         //只要选择了某个或多个兴趣,就将所选中的兴趣通过截取字符串的方式截取下来,减一是为了去掉最后一个逗号
    if (hobby.length()>0){ hobby = hobby.substring(0,hobby.length()-1); } //取出下拉列表中选中的项,你选中了哪项TextView就将哪个TextView取出来
         LinearLayout item = (LinearLayout)spin_class.getSelectedView();
         //通过取出的项,进一步取到它的id名  TextView txt_cno
    = (TextView)item.findViewById(R.id.cno);
         //根据id获取它的文本内容并转化为字符串,然后又通过Integer.parseInt()方法将其转化为int类型
    int cno = Integer.parseInt(txt_cno.getText().toString());      //将学生的编号0开始和输入的名字,输入的年龄,选择好的性别和爱好和班级编号一起封装到TbStu TbStu stu = new TbStu(0,name,age,sex,hobby,cno);
         //调用stuDao()的addStu()方法将学生信息添加,如果返回的是true,则弹出添加学生成功
    if (new StuDao(this).addStu(stu)){ Toast.makeText(this,"添加学生成功",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(this,"添加学生失败",Toast.LENGTH_SHORT).show(); } }
      //点击取消按钮则关闭当前Activity
    public void doBack(View view){ this.finish(); } }

    5、activity_test.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/activity_add_stu"
        android:orientation="vertical"
        android:layout_marginTop="5dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:id="@+id/ssexgroup"
            >
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/sex_1"
                android:text="男"
                android:checked="true"
                />
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/sex_2"
                android:text="女"
                />
        </RadioGroup>
    </LinearLayout>

    6、TestActivity.java

    package com.nf.android_sqlite2;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.RadioButton;
    import android.widget.RadioGroup;
    import android.widget.Toast;
    
    public class TestActivity extends Activity {
        private RadioGroup ssexgroup;
        String sex = "男";
        private RadioButton sex1,sex2;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_test);
            sex1=(RadioButton)findViewById(R.id.sex_1);
            sex2=(RadioButton)findViewById(R.id.sex_2);
            ssexgroup = (RadioGroup)findViewById(R.id.ssexgroup);
         //主要是这个事件 ssexgroup.setOnCheckedChangeListener(
    new RadioGroup.OnCheckedChangeListener(){ @Override public void onCheckedChanged(RadioGroup radioGroup,int i){//注意:这个i的值是很大的,不是1,2,3,4 RadioButton rb = (RadioButton)findViewById(i); sex = rb.getText().toString(); if (i==sex1.getId()){ Toast.makeText(TestActivity.this,"男 = "+sex,Toast.LENGTH_SHORT).show(); } if (i==sex2.getId()){ Toast.makeText(TestActivity.this,"女 = "+sex,Toast.LENGTH_SHORT).show(); } } }); } }

    7、activity_login.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/activity_login"
        android:orientation="vertical"
        android:layout_margin="10dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="用户登录"
            android:textSize="25dp"
            android:gravity="center"
            />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/uname"
            android:hint="请输入用户名"
            />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/upwd"
            android:hint="请输入密码"
            android:inputType="textPassword"
            />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            >
            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="登录"
                android:onClick="doLogin"
                android:layout_weight="1"
                />
            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="退出"
                android:onClick="doExit"
                android:layout_weight="1"
                />
        </LinearLayout>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/registerLink"
            android:gravity="right"
            android:text="新用户注册"
            android:onClick="toRegister"
            android:textSize="20dp"
            android:layout_marginTop="10dp"
            android:layout_marginRight="10dp"
            android:textColor="@android:color/holo_blue_light"
            />
    </LinearLayout>

    8、LoginActivity.java

    package com.nf.android_sqlite2;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.graphics.Paint;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.nf.dao.UserDao;
    import com.nf.entity.Users;
    import com.nf.utils.MyApplication;
    
    public class LoginActivity extends Activity {
        private TextView registerLink;
        private EditText uname,upwd;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
            //将当前Activity加入到自定义栈中
            MyApplication.getInstance().addActivity(this);
    
            registerLink = (TextView)findViewById(R.id.registerLink);
         //给用户注册的连接设置下划线 registerLink.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); registerLink.getPaint().setAntiAlias(
    true);//抗锯齿      //获取到用户名和密码 uname = (EditText)findViewById(R.id.uname); upwd = (EditText)findViewById(R.id.upwd); } //点击登录 public void doLogin(View view){
         //当点击登录时获取到用户输入的文本内容并转化为字符串类型 String name
    = uname.getText().toString(); String pwd = upwd.getText().toString();
         //通过调用UserDao()的doLogin()方法将用户名和密码传入进去,然后去那边判断用户名和密码是否已经存在,如果存在则会返回封装在user中的用户编号和用户名,密码就不用返回了 Users user
    = new UserDao(this).doLogin(name,pwd);//调用方法进行登录验证
         //只要user中不为空 if (user!=null){ //保留登录状态
           //先找到那个专门保存用户信息的lock文件 SharedPreferences sp = getSharedPreferences("lock",MODE_PRIVATE);
           //通过创建编辑器 SharedPreferences.Editor editor
    = sp.edit();
           //调用编辑器的putString()方法,将用户编号和用户名添加到lock文件中 editor.putString(
    "LoginNo",user.getUno()+""); editor.putString("LoginName",user.getUname());
           //提交信息 editor.commit();
    //跳转到主页面 Intent intent = new Intent(this,MainActivity.class); startActivity(intent); }else{ Toast.makeText(this,"用户名和密码错误",Toast.LENGTH_SHORT).show(); } } //退出 public void doExit(View view){ this.finish(); MyApplication.getInstance().exit(); } //点击注册按钮时 public void toRegister(View view){
         //在登录界面创建一个对话框 AlertDialog.Builder builder
    = new AlertDialog.Builder(this);
         //设置对话框的标题 builder.setTitle(
    "用户注册");
         //通过投影的方式将layout_register_user的布局投影到当前页面 View dialogView
    = LayoutInflater.from(this).inflate(R.layout.layout_register_user,null);
         //绑定id
    final EditText uname = (EditText)dialogView.findViewById(R.id.uname); final EditText upwd = (EditText)dialogView.findViewById(R.id.upwd);
         //然后又将投影得到的布局绑定到对话框 builder.setView(dialogView);
         //给对话框设置一个注册按钮并设置单击监听事件的方法
           builder.setPositiveButton(
    "注册",new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialogInterface,int i){
              //点击注册按钮后调用UserDao()中的addUser()方法,传入一个封装的User对象,将用户编号,用户名,用户密码传过去,返回true则提示注册成功
    if (new UserDao(LoginActivity.this).addUser(new Users(0,uname.getText().toString(),upwd.getText().toString()))){ Toast.makeText(LoginActivity.this,"注册成功",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(LoginActivity.this,"注册失败",Toast.LENGTH_SHORT).show(); } } });
         //给对话框设置取消按钮 builder.setNeutralButton(
    "取消",null);
         //创建对话框并显示出来 builder.create().show(); } }

    9、activity_insert.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/activity_insert"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Insert()案例"
            android:onClick="test_Insert"
            />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Update()案例"
            android:onClick="test_Update"
            />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Delete()案例"
            android:onClick="test_Delete"
            />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Query()案例"
            android:onClick="test_Query"
            />
    </LinearLayout>

    10、InsertActivity.java

    package com.nf.android_sqlite2;
    
    import android.app.Activity;
    import android.content.ContentValues;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Toast;
    
    import com.nf.dao.DbHelper;
    
    public class InsertActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_insert);
        }
        //Insert()方法实现添加数据
       //点击添加数据 public void test_Insert(View view){
         //实例化SQLiteDatabase对象 SQLiteDatabase sdb
    = DbHelper.getInstance(this).getReadableDatabase();
         //ContentValues是一种存储机制,只能存储基本类型的数据,不能存储对象信息,是通过键值对的方式存储 ContentValues values
    = new ContentValues();
         //通过put()的方法,向ContentValues中存入一个学生信息 values.put(
    "pname","Marry"); values.put("page",24); values.put("psex","女");
         //调用DbHelper中的insert()方法,将学生信息传过去添加到SQLite数据库中
         //第一个参数是表名,表示给SQLite数据库中的哪个表添加数据,第二个参数可能代表字段名称,表示给该表的某个字段插入某值 sdb.insert(
    "Person",null,values); Toast.makeText(this,"添加Person成功!",Toast.LENGTH_SHORT).show(); } //Update()方法修改数据 public void test_Update(View view){
         //同上 SQLiteDatabase sdb
    = DbHelper.getInstance(this).getReadableDatabase(); ContentValues values = new ContentValues();
         //将年龄设置为25 values.put(
    "page","25");
         //调用update()方法,修改person表中名字为Marry的的年龄,将值设置为25 sdb.update(
    "Person",values,"pname='Marry'",null); } //Delete()方法删除数据 public void test_Delete(View view){
         //同上 SQLiteDatabase sdb
    = DbHelper.getInstance(this).getReadableDatabase();
         //调用delete()方法,删除Person表中名字为Marry的人的信息 sdb.delete(
    "Person","pname='Marry'",null); }
    //Query()方法查询数据 public void test_Query(View view){
         //同上 SQLiteDatabase sdb
    = DbHelper.getInstance(this).getReadableDatabase();
         //调用query()查询Person表中年龄为22到25的人的信息,并倒序排序 Cursor cursor
    = sdb.query("Person",null,"page>=? and page<=?",new String[]{"22","25"},null,null,"page desc");
         //循环遍历结果集游标
    while(cursor.moveToNext()){
            //通过游标的getColumnIndex()获取列名为“_id”的编号信息
    int pno = cursor.getInt(cursor.getColumnIndex("_id"));
           //同上 String pname
    = cursor.getString(cursor.getColumnIndex("pname")); int page = cursor.getInt(cursor.getColumnIndex("page")); String psex = cursor.getString(cursor.getColumnIndex("psex"));
           //通过日志的形式输出 Log.i(
    "Query Person",pno+","+pname+","+page+","+psex); }
         //关闭游标 cursor.close(); } }

    11、ClassDao.java

    package com.nf.dao;
    
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    
    /**
     * Created by Admin on 2017/12/13.
     */
    
    public class ClassDao {
        private SQLiteDatabase sdb;
        public ClassDao(Context context){
         //实例化SQLiteDatabase DbHelper dbHelper
    = DbHelper.getInstance(context); sdb = dbHelper.getReadableDatabase(); } public Cursor getClassCursor(){
         //构建查询语句,查询班级表中的所有信息 String sql
    = "select * from tb_class";
         //调用rawQuery()方法进行查询,并将返回的班级信息返回给调用者
    return sdb.rawQuery(sql,null); } }

    12、DbHelper.java

    package com.nf.dao;
    
    import android.content.Context;
    import android.database.DatabaseErrorHandler;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.text.style.TtsSpan;
    import android.util.Log;
    
    public class DbHelper extends SQLiteOpenHelper{
       //数据库名称
        private static final String DATABASE_NAME = "mydb.db";
      //数据库版本
    private static final int VERSION = 1;   //初始化数据库 public DbHelper(Context context) { super(context,DATABASE_NAME,null,VERSION ); } public DbHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) { super(context,DATABASE_NAME,null,VERSION ); }    @Override public void onCreate(SQLiteDatabase db) {
         //创建一个Person表 String sql
    = "create table if not exists Person(" + "_id integer primary key," + "pname text," + "page integer," + "psex text" + ")";
         //执行sql语句 db.execSQL(sql);
         //给Person表中插入一条数据 sql
    = "insert into Person(pname,page,psex)values('Lucy',23,'女')"; db.execSQL(sql); Log.i("DbHelper","创建数据表Person成功"); //创建用户表 sql = "create table if not exists Users(" + "_id integer primary key," + "uname text not null," + "upwd text not null" + ")"; db.execSQL(sql); sql = "insert into Users(uname,upwd) values('admins','admins')"; db.execSQL(sql); Log.i("create DB","创建用户成功"); //创建班级表和学生表 sql = "create table if not exists tb_class(" + "_id integer primary key," + "cname text not null" + ")"; db.execSQL(sql); sql = "insert into tb_class(cname) values('S1T01')"; db.execSQL(sql); sql = "insert into tb_class(cname) values('S1T02')"; db.execSQL(sql); sql = "insert into tb_class(cname) values('S1T03')"; db.execSQL(sql); Log.i("create DB","创建班级成功"); sql = "create table if not exists tb_stu(" + "_id integer primary key," + "sname text not null," + "sage integer," + "ssex text," + "shobby text," + "scno integer," + "foreign key(scno) references tb_class(_id)" + ")"; db.execSQL(sql); sql = "insert into tb_stu(sname,sage,ssex,shobby,scno)values('张三',23,'男','睡觉',1)"; db.execSQL(sql); sql = "insert into tb_stu(sname,sage,ssex,shobby,scno)values('Lucys',21,'女','美食',1)"; db.execSQL(sql); Log.i("create DB","创建用户,班级,学生表成功"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
         //上面的onCreate()方法只会执行一次,一次之后就不会执行那个方法了,但可以通过这个方法做一些修改的操作
         //执行一些修改操作 String sql = "drop table Person"; db.execSQL(sql);
         //重新构建上面的表结构 onCreate(db); }
    //提供一个方法获取DbHelper实例
      //私有化
    private static DbHelper dbHelper;
      //提供公共的访问方法
    public static synchronized DbHelper getInstance(Context context){
         //当外界调用这个方法时,如果发现上面的表结构还未创建,则会实例化这个DbHelper,这样就保证了表结构是存在的
    if (dbHelper == null){ dbHelper = new DbHelper(context); } return dbHelper; } }

    13、StuDao.java

    package com.nf.dao;
    
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    
    import com.nf.entity.TbStu;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    /**
     * Created by Admin on 2017/12/13.
     */
    
    public class StuDao {
        private SQLiteDatabase sdb;
        public StuDao(Context context){
            DbHelper dbHelper = DbHelper.getInstance(context);
            sdb = dbHelper.getReadableDatabase();
        }
        //添加学生
      //添加成功返回true
    public boolean addStu(TbStu stu){
         //构建插入语句 String sql
    = "insert into tb_stu(sname,sage,ssex,shobby,scno) values(?,?,?,?,?)"; try {
           //执行查询 sdb.execSQL(sql,
    new Object[]{stu.getSname(), stu.getSage(), stu.getSsex(), stu.getShobby(), stu.getScno()}); return true; }catch (Exception e){ e.printStackTrace(); } return false; } //查询出所有的学生信息
      //查询成功返回结果集游标,结果集游标里保存着学生信息 public Cursor findStuInfo(){
         //构建联合查询语句 String sql
    = "select s.*,c.cname from tb_stu s left join tb_class c on s.scno=c._id";
         //rawQuery()方法专门是用于查询 Cursor cursor
    = sdb.rawQuery(sql,null); return cursor; }
      
    //查询出所有的学生信息
      //比上面的查询复杂,但灵活度高 public List<Map<String,Object>> findStuInfo2(){
         //构建查询语句 String sql
    = "select s.*,c.cname from tb_stu s left join tb_class c on s.scno = c._id";
         //将查询到的信息放入结果集游标 Cursor cursor
    = sdb.rawQuery(sql,null);
         //构建集合 List
    <Map<String,Object>> list = new ArrayList<Map<String,Object>>();
         //获取游标的列名 String[] columNames
    = cursor.getColumnNames();
         //遍历游标
    while (cursor.moveToNext()){ Map<String,Object> map = new HashMap<String,Object>(); for (int i=0;i<columNames.length;i++){
             //根据游标中的列名得到所有列中的信息,放入map中,在将map添加到list中,返回list map.put(columNames[i],cursor.getString(cursor.getColumnIndex(columNames[i]))); } list.add(map); }
    return list; } }

    14、UserDao.java

    package com.nf.dao;
    
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    
    import com.nf.entity.Users;
    
    import java.nio.file.attribute.UserPrincipalLookupService;
    
    /**
     * Created by Admin on 2017/12/13.
     */
    
    public class UserDao {
        private SQLiteDatabase sdb;
        public UserDao(Context context){
         //实例化SQLiteDatabase对象 DbHelper dbHelper
    = DbHelper.getInstance(context); sdb = dbHelper.getReadableDatabase(); } //验证用户名和密码
      //验证成功则返回用户编号和用户名 public Users doLogin(String name,String pwd){
         //构建查询语句,根据名字查询用户信息 String sql
    = "select * from Users where uname = ?"; Cursor cursor = sdb.rawQuery(sql,new String[]{name}); while(cursor.moveToNext()){ int uno = cursor.getInt(cursor.getColumnIndex("_id")); String uname = cursor.getString(cursor.getColumnIndex("uname")); String upwd = cursor.getString(cursor.getColumnIndex("upwd")); if (uname.equals(name)&&upwd.equals(pwd)){ return new Users(uno,uname,null); } } return null; } //添加用户 public boolean addUser(Users user){ String sql = "insert into Users(uname,upwd)values(?,?)"; try{ sdb.execSQL(sql,new String[]{user.getUname(),user.getUpwd()}); return true; }catch(Exception ex){ ex.printStackTrace(); } return false; } }

    15、TbClass.java

    package com.nf.entity;
    
    /**
     * Created by Admin on 2017/12/13.
     */
    
    public class TbClass {
        private int cno;
        private String cname;
    
        public TbClass() {
        }
    
        public TbClass(int cno, String cname) {
            this.cno = cno;
            this.cname = cname;
        }
    
        public int getCno() {
            return cno;
        }
    
        public void setCno(int cno) {
            this.cno = cno;
        }
    
        public String getCname() {
            return cname;
        }
    
        public void setCname(String cname) {
            this.cname = cname;
        }
    }

    16、TbStu.java

    package com.nf.entity;
    
    public class TbStu {
        private int sno;
        private String sname;
        private int sage;
        private String ssex;
        private String shobby;
        private int scno;
    
        public TbStu() {
        }
    
        public TbStu(int sno, String sname, int sage, String ssex, String shobby, int scno) {
            this.sno = sno;
            this.sname = sname;
            this.sage = sage;
            this.ssex = ssex;
            this.shobby = shobby;
            this.scno = scno;
        }
    
        public int getSno() {
            return sno;
        }
    
        public void setSno(int sno) {
            this.sno = sno;
        }
    
        public String getSname() {
            return sname;
        }
    
        public void setSname(String sname) {
            this.sname = sname;
        }
    
        public int getSage() {
            return sage;
        }
    
        public void setSage(int sage) {
            this.sage = sage;
        }
    
        public String getSsex() {
            return ssex;
        }
    
        public void setSsex(String ssex) {
            this.ssex = ssex;
        }
    
        public String getShobby() {
            return shobby;
        }
    
        public void setShobby(String shobby) {
            this.shobby = shobby;
        }
    
        public int getScno() {
            return scno;
        }
    
        public void setScno(int scno) {
            this.scno = scno;
        }
    }

    17、Users.java

    package com.nf.entity;
    
    /**
     * Created by Admin on 2017/12/13.
     */
    
    public class Users {
        private int uno;
        private String uname;
        private String upwd;
    
        public Users() {
        }
    
        public Users(int uno, String uname, String upwd) {
            this.uno = uno;
            this.uname = uname;
            this.upwd = upwd;
        }
    
        public int getUno() {
            return uno;
        }
    
        public void setUno(int uno) {
            this.uno = uno;
        }
    
        public String getUname() {
            return uname;
        }
    
        public void setUname(String uname) {
            this.uname = uname;
        }
    
        public String getUpwd() {
            return upwd;
        }
    
        public void setUpwd(String upwd) {
            this.upwd = upwd;
        }
    }

    18、MyApplication.java

    package com.nf.utils;
    
    import android.app.Activity;
    import android.app.Application;
    
    import java.util.LinkedList;
    import java.util.List;
    
    //Application配置全局Context
    public class MyApplication extends Application{
        private List<Activity> mList = new LinkedList<Activity>();
        private static MyApplication instance = null;
        private MyApplication(){}
    
        //synchronized同步锁,实现单例效果
        //方法上加static关键词代表这个方法属于类的,这样才可以在MainActivity.java中通过MyApplication.getInstance().addActivity(this);的方式调用
        public synchronized static MyApplication getInstance(){
            if (null == instance){
                //如果实例还没有创建,则创建实例;若实例已经被创建,则直接返回之前创建的实例
                instance = new MyApplication();
            }
            return instance;
        }
        //获取Activity的方法
        //在MainActivity.jaava类中通过MyApplication.getInstance().addActivity(this);传入this,到这个方法获得一个Activity的类
        public void addActivity(Activity activity){
            //将Activity放入到list集合里,再进行循环遍历
            mList.add(activity);
        }
        //安全退出的方法
        public void exit(){
            try{
                //循环遍历list中收集的所有Activity
                for (Activity activity:mList){
                    //将集合中的Activity杀死
                    if (activity != null)
                        activity.finish();
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                //系统退出,在退出之前将所有的Activity杀死,实现安全退出
                System.exit(0);
            }
        }
    
        //当系统内存不足要将后台程序杀死时,且在最后一个后台程序被杀死时会自动调用这个方法,释放UI使用的资源,进行垃圾
        //拓展:onTrimMemory()方法。
        public void onLowMemory(){
            super.onLowMemory();
            //系统垃圾回收
            System.gc();
        }
    
    }

    19、layout_register_user.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp">
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/uname"
            android:hint="请输入用户名"
            />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/upwd"
            android:hint="请输入密码"
            android:inputType="textPassword"
            />
    </LinearLayout>

    20、layout_spinner_class.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:id="@+id/cno"
            android:visibility="invisible"
            />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:id="@+id/cname"
            android:gravity="center_vertical"
            />
    </LinearLayout>

    21、layout_stu_list.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/holo_green_light"
        >
        <ImageView
            android:layout_width="60dp"
            android:layout_height="70dp"
            android:id="@+id/userImage"
            android:src="@mipmap/ic_launcher"
            />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:orientation="vertical"
            >
            <LinearLayout
                android:layout_width="match_parent"
                android:orientation="horizontal"
                android:layout_height="33dp"
                >
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:id="@+id/stuName"
                    android:text="姓名:张三"
                    android:textSize="20dp"
                    android:gravity="center_vertical"
                    android:layout_weight="1"
                    />
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:id="@+id/clsName"
                    android:text="班级:S1T01"
                    android:textSize="20dp"
                    android:gravity="center_vertical"
                    android:layout_weight="1"
                    />
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="2dp"
                android:background="@android:color/darker_gray"
                />
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="35dp"
                    android:orientation="horizontal"
                    >
                    <TextView
                        android:layout_width="0dp"
                        android:layout_height="35dp"
                        android:id="@+id/stuSex"
                        android:gravity="center_vertical"
                        android:layout_weight="1"
                        android:text="性别:男"
                        android:textSize="18dp"
                        />
                    <TextView
                        android:layout_width="0dp"
                        android:layout_height="35dp"
                        android:id="@+id/stuAge"
                        android:layout_weight="1"
                        android:gravity="center_vertical"
                        android:textSize="18dp"
                        android:text="23"
                        />
                    <TextView
                        android:layout_width="0dp"
                        android:layout_height="35dp"
                        android:id="@+id/stuHobby"
                        android:layout_weight="2"
                        android:gravity="center_vertical"
                        android:textSize="18dp"
                        android:text="睡觉"
                        />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
    
    
    如果您发现博客内容有什么错误,请您下方留言
  • 相关阅读:
    vuex 入门
    Vuex 原理
    java web开发问题集合
    JSP Servlet 路径解析 路径设置
    随笔——学习的一些步骤及注意点(不断更新)
    常用正则表达式大全!(例如:匹配中文、匹配html)
    myeclipse+tomcat 工程名改名的问题 ——————完美解决方案
    web开发的步骤
    Servlet中的GET和POST之间的区别
    html、css、javascript、JSP 、xml学习顺序应该是怎样的呢?
  • 原文地址:https://www.cnblogs.com/zn615/p/8250753.html
Copyright © 2011-2022 走看看