SQLite数据库实例三

这一篇,与大家分享的是学生用户功能实现。四个功能,更改密码,更新个人信息,查询可选修课程,查询成绩

1,更新个人信息

一个Activity的显示需要填写的个人信息,根据业务需求来设计学生个人信息数据库

然后,这里涉及到的数据库操作有两个类型,一个是首次填写,这时候需要插入数据到学生个人信息表中。第二种情况是个人信息发生变更,需要更新数据库

所以定义两个按钮来对应用户需求操作。其次,用户怎么知道自己信息需要更改,这时候,我们就可以利用之前学到的一个类,SharePreference,来从现用户初次填写的信息重现。这就是我的个人想法。关于老师和管理员他们的个人信息更新操作思想也是一样,之下不会再提。

具体代码

首先是学生主界面代码(界面图片请看第一篇):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center" >
     <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <TextView
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:text="@string/change_password"
            android:textColor="#000000"
            android:textSize="18sp" />
        <Button
            android:id="@+id/change_password_student"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="check_message"
            android:text="@string/check_self_message" />
    </LinearLayout>
    <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    <TextView 
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:textSize="18sp"
        android:text="@string/check_self_message_01"
        />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="check_message"
        android:id="@+id/chekSelfMessage"
        android:text="@string/check_self_message"
        />
    </LinearLayout>
       <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    <TextView 
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:textSize="18sp"
        android:text="@string/check_course"
        />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="check_message"
        android:id="@+id/check_course"
        android:text="@string/check_self_message"
        />
    </LinearLayout>
     <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    <TextView 
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:textSize="18sp"
        android:text="@string/check_green_01"
        />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="check_message"
        android:id="@+id/check_green"
        android:text="@string/check_self_message"
        />
    </LinearLayout>
	<ScrollView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    >
    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/show_check_course"
        android:textSize="20sp"
        />
</ScrollView>
</LinearLayout>


代码实现(利用一个新的的Activity来实现)

public class StudentMessageActivity extends Activity
{
	private EditText student_message_activity_age;
	private TextView student_message_activity_Sno;
	private EditText student_message_activity_name;
	private EditText student_message_activity_classIn;
	private RadioGroup rg;
	private String sexUnkNow = "男";
	private EditText student_message_activity_step;
	private EditText student_message_activity_QQ;
	private EditText student_message_activity_phone;
	private EditText student_message_activity_address;
	private EditText student_message_activity_stepIN;
	private TextView show_student_messge;
	private StringBuilder builder;
	private StudentMessageService studentMessageService;
	private StudentMessageTable studentMessageTable;
	private String Sno;
	private SharedPreferences sharePreference;
	private Editor editor;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.student_message_activity);
		init();
	}

	@SuppressLint("WorldReadableFiles")
	@SuppressWarnings("deprecation")
	private void init()
	{
		student_message_activity_age = (EditText)findViewById(R.id.student_message_activity_age);
		student_message_activity_Sno = (TextView)findViewById(R.id.student_message_activity_Sno);
		student_message_activity_name = (EditText)findViewById(R.id.student_message_activity_name);
		student_message_activity_classIn = (EditText)findViewById(R.id.student_message_activity_classIn);
		rg = (RadioGroup)findViewById(R.id.rg);
		rg.setonCheckedchangelistener(new OnCheckedchangelistener()
		{
			public void onCheckedChanged(RadioGroup group,int checkedId)
			{
				sexUnkNow = checkedId==R.id.male?"男":"女";
			}
		});
		student_message_activity_step = (EditText)findViewById(R.id.student_message_activity_step);
		student_message_activity_QQ = (EditText)findViewById(R.id.student_message_activity_QQ);
		student_message_activity_phone = (EditText)findViewById(R.id.student_message_activity_phone);
		student_message_activity_address = (EditText)findViewById(R.id.student_message_activity_address);
		student_message_activity_stepIN = (EditText)findViewById(R.id.student_message_activity_stepIN);
	
		show_student_messge = (TextView)findViewById(R.id.show_student_messge);
		studentMessageService = new StudentMessageService(this);
		Intent intentFromMainFrame = getIntent();
		Sno = intentFromMainFrame.getStringExtra("name");
		student_message_activity_Sno.setText(Sno);
		sharePreference = getSharedPreferences("studentMessage",Context.MODE_WORLD_READABLE);//使用一个sharePreference来给用户提示他的个人信息,没有的时候则是提示没有记录,有的时候方便用户查看是否需要更新
		show_student_messge.setText(sharePreference.getString(Sno,"没有记录请添加"));
	}
	
	@SuppressLint("ShowToast")
	public void student_meaasge_activity_button(View v)
	{
		String age = student_message_activity_age.getText().toString();
		String name = student_message_activity_name.getText().toString();
		String classIn = student_message_activity_classIn.getText().toString();
		String sex = sexUnkNow;
		String step = student_message_activity_step.getText().toString();
		String qq = student_message_activity_QQ.getText().toString();
		String phone = student_message_activity_phone.getText().toString();
		String address = student_message_activity_address.getText().toString();
		String stepIn = student_message_activity_stepIN.getText().toString();
		builder = new StringBuilder();
		builder.append("年龄:").append(age+"\n");
		builder.append("学号:").append(Sno+"\n");
		builder.append("姓名:").append(name+"\n");
		builder.append("班级:").append(classIn+"\n");
		builder.append("性别:").append(sex+"\n");
		builder.append("专业:").append(step+"\n");
		builder.append("QQ:").append(qq+"\n");
		builder.append("电话:").append(phone+"\n");
		builder.append("地址:").append(address+"\n");
		builder.append("学院:").append(stepIn+"\n");
		show_student_messge.setText(builder.toString());
		Log.i("StudentMessageActivity",stepIn);
		editor = sharePreference.edit();
		editor.putString(Sno,builder.toString());
		editor.commit();//必须有这个,是把内存中的数据提交到磁盘空间中
		studentMessageTable = new StudentMessageTable(age,Sno,name,classIn,sex,step,qq,phone,address,stepIn);//一个类似于学生老师管理员密码表所使用到一个临时存放学生信息的domain类,方便数据添加和查找特定信息,这里就不给出了
		switch (v.getId())
		{
		case R.id.student_meaasge_activity_sure://对应的是第一次填写,这次对数据库的操作是插入
			studentMessageService.save(studentMessageTable);
			Toast.makeText(getApplicationContext(),"首次填写成功",0).show();
			break;

		case R.id.student_meaasge_activity_change://对应的数据库操作是更新
			studentMessageService.update(studentMessageTable);
			Toast.makeText(getApplicationContext(),"更新成功",0).show();
			break;
		}
	}
}
更改密码操作(也是重开一个新的Activity):
public class StudentChangePassword extends Activity
{
	private EditText student_password_before;
	private EditText student_password_Now;
	private EditText student_password_Now_01;
	private StudentService studentService;
	private Intent intentStartStudentMainFrame;

	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.student_change_password);
		student_password_before = (EditText) findViewById(R.id.student_password_before);
		student_password_Now = (EditText) findViewById(R.id.student_password_Now);
		student_password_Now_01 = (EditText) findViewById(R.id.student_password_Now_01);
		studentService = new StudentService(this);
	}

	@SuppressLint("ShowToast")
	public void change_student_password(View v)
	{
		Intent intent = getIntent();
		String name = intent.getStringExtra("name");
		String passWord = student_password_before.getText().toString();

		String Now = student_password_Now.getText().toString();
		String sure = student_password_Now_01.getText().toString();
		Log.i("StudentChangePassword",name + "	" + passWord + "	" + Now);
		if (passWord.equals(studentService.quary(name,StudentService.TABLE_UESAMESSAGE).getpassWord()))//判断输入的密码与数据库中的是否相等
			if (Now.equals(sure) && Now.trim().length() >= 5)//判断两次输入的密码是否相等,且其中的新密码长度去空格是否大于5,都正确才会执行数据库的更新操作
			{
				UserMessage user = new UserMessage(name,Now);
				studentService.update(user,StudentService.TABLE_UESAMESSAGE);
				Toast.makeText(getApplicationContext(),"修改成功",0).show();
				intentStartStudentMainFrame = new Intent(
						StudentChangePassword.this,StudentMainFrame.class);
				intentStartStudentMainFrame.putExtra("Now",Now);
				setResult(2,intentStartStudentMainFrame);
				student_password_before.setText("");
				student_password_Now.setText("");
				student_password_Now_01.setText("");
				finish();
			} else
			{
				StartSelf();
				Toast.makeText(getApplicationContext(),"两次输入的新密码不正确或者是少于等于5",0).show();
			}
		else
		{
			StartSelf();
			Toast.makeText(getApplicationContext(),"原密码错误",0).show();
		}
	}

	private void StartSelf()
	{
		student_password_before.setText("");
		student_password_Now.setText("");
		student_password_Now_01.setText("");
		intentStartStudentMainFrame = new Intent(StudentChangePassword.this,StudentChangePassword.class);
		startActivity(intentStartStudentMainFrame);
		finish();
	}
}
查询可选修课程与查询成绩(这学生这个mainActivity中实现,点击之后弹出一个多选的对话框,之后把所选的课程显示在屏幕的下方),所以源码就是学生的主界面
public class StudentMainFrame extends Activity
{
	private Intent intent;
	private TextView show_check_course;
	private DataBaSEOpenHelper  dataBaSEOpenHelper;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.student_main_frame);
		dataBaSEOpenHelper = new DataBaSEOpenHelper(this);
		show_check_course = (TextView) findViewById(R.id.show_check_course);
	}

	public void check_message(View v)
	{
		switch (v.getId())
		{
		case R.id.change_password_student://跳转到更改密码的界面
			Intent intentFromStudnet = getIntent();
			String name = intentFromStudnet.getStringExtra("name");
			intent = new Intent(StudentMainFrame.this,StudentChangePassword.class);
			intent.putExtra("name",name);//学号是外码,不可以更改,所以需要传递给更改密码的Activity,用Text人View显示出来,下同
			startActivityForResult(intent,1);
			break;
		case R.id.chekSelfMessage://跳转更新信息的界面
			Intent intentFromStudnet2 = getIntent();
			String name2 = intentFromStudnet2.getStringExtra("name");
			intent = new Intent(StudentMainFrame.this,StudentMessageActivity.class);
			intent.putExtra("name",name2);
			startActivity(intent);
			break;
		case R.id.check_course:
			check_course_message();/查询可选修的课程/
			break;
		case R.id.check_green:
			showscore();//显示选修课程的成绩,在没有老师给自己的课程打分的时候是null
			break;

		}
	}

	private void showscore()
	{
		show_check_course.setText("");//把这个空间置为空,因为还有其他组件使用过,每一次使用之前置空
		Intent intentFromStudnet = getIntent();
		String name = intentFromStudnet.getStringExtra("name");
		sqliteDatabase db = dataBaSEOpenHelper.getReadableDatabase();
		StringBuffer sb = new StringBuffer("所选课程的所有成绩是:\n");
		Cursor cursor = db
				.rawQuery("select dbS_C.c_name,dbS_C.score from dbS_C,allstudentmessage where dbS_C.s_name=allstudentmessage.Sno AND allstudentmessage.Sno=?",new String[]{ name });//从数据库文件中找到课程--课程表,然后从表中根据学号找到自己选的课程有哪些
		while(cursor.movetoNext())
		{
			String course_name = cursor.getString(cursor.getColumnIndex("c_name"));
			String score = cursor.getString(cursor.getColumnIndex("score"));
			sb.append("课程名称:").append(course_name+",");
			sb.append("课程成绩:").append(score+"\n");
		}
		cursor.close();
		show_check_course.setTextSize(12);
		show_check_course.setText(sb.toString());//显示每一门课程的成绩和课程名称

	}

	private String[] courseName;//存放课程的名称
	private boolean[] flag;//在多选对话框中显示哪些已经选了

	public void check_course_message()
	{
		show_check_course.setText("");
		sqliteDatabase dbCourse = dataBaSEOpenHelper.getReadableDatabase();
		Cursor cursor = dbCourse.rawQuery("select * from course",null);//从数据库文件中找到课程数据库表,查询所有的课程信息,放到数组中
		courseName = new String[7];

		int i = 0;
		while (cursor.movetoNext())
		{
			courseName[i++] = cursor.getString(cursor.getColumnIndex("name"));//存入数组
		}
		dbCourse.close();
		final StringBuffer sb = new StringBuffer("您选修的课程有:\n");
		flag = new boolean[courseName.length];

		new AlertDialog.Builder(this)
				.setTitle("选择需要选修的课程,可以选择多门")
				.setMultiChoiceItems(courseName,flag,new OnMultiChoiceClickListener()//为多选添加事件监听
						{
							public void onClick(DialogInterface dialog,int which,boolean isChecked)
							{
								flag[which] = isChecked;//显示已选
							}
						})
				.setPositiveButton("确定",new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog,int which)
					{
						for (int i = 0; i < flag.length; i++)
						{
							if (flag[i])
							{
								sb.append(courseName[i] + "\n");//点击确定的时候把所有的标记已选的课程记录下来,之后再屏幕下方显示,方便用户查看和是否需要重新选课
							}
						}
						show_check_course.setText(sb.toString());
						insertIntoDB();
					}
				})
				.setNegativeButton("取消",new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog,int which)
					{

					}
				}).show();
		
	}

	protected void insertIntoDB()
	{
		Intent intentFromStudnet = getIntent();
		String name = intentFromStudnet.getStringExtra("name");
		sqliteDatabase dbS_C = dataBaSEOpenHelper.getWritableDatabase();
		dbS_C.execsql("delete from dbS_C where s_name=?",new Object[]{ name });//把之前的选课记录清除掉,然后更新数据库,把新的选修的课程放到学生--课程数据库表中
		for (int j = 0; j < courseName.length; j++)
		{
			if (flag[j])
			{
				dbS_C.execsql("insert into dbS_C(s_name,c_name) values(?,?)",new Object[]
						{ name,courseName[j] });
			}
		}
	}
	private AlertDialog builder = null;
	  public boolean onKeyUp(int keyCode,KeyEvent event) {  
		     
          if(keyCode == KeyEvent.KEYCODE_BACK){  
			builder = new AlertDialog.Builder(StudentMainFrame.this)
					.setTitle("温馨提示:")
					.setMessage("退出本程序?")
					.setPositiveButton("确定",new DialogInterface.OnClickListener()
							{
      public void onClick(DialogInterface dialog,int whichButton) {  
    	  StudentMainFrame.this.finish();  
      }  
     })  
   .setNegativeButton("取消",new DialogInterface.OnClickListener() {  
      public void onClick(DialogInterface dialog,int whichButton) {  
       builder.dismiss();  
      }  
     }).show();  
          }  
          return true;  
} 
}
下次和大家分享的是老师用户功能实现。

相关文章

SQLite架构简单,又有Json计算能力,有时会承担Json文件/RES...
使用Python操作内置数据库SQLite以及MySQL数据库。
破解微信数据库密码,用python导出微信聊天记录
(Unity)SQLite 是一个软件库,实现了自给自足的、无服务器...
安卓开发,利用SQLite实现登陆注册功能