最近刚刚做了一个模块,在本地建立一个数据库,存储注册的账号,登录的时候取出,正确则登录,登录之后跳到一个webView网页。
直接上代码吧。
LoginActivity.java
package com.example.login; import com.example.service.UserService; import android.app.Activity; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class LoginActivity extends Activity implements OnClickListener{ SQLiteDatabase mysql; private EditText et_name; private EditText et_password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); initView(); } private void initView() { et_name = (EditText) findViewById(R.id.et_Name); et_password = (EditText) findViewById(R.id.et_Password); Button newUer = (Button) findViewById(R.id.newUer); Button login = (Button) findViewById(R.id.login); login.setOnClickListener(this); newUer.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.login: String name=et_name.getText().toString(); String pass=et_password.getText().toString(); Log.i("TAG",name+"_"+pass); UserService uService=new UserService(LoginActivity.this); boolean flag=uService.login(name, pass); if(flag){ Log.i("TAG","登录成功"); Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show(); Toast.makeText(LoginActivity.this, "正在加载,请耐心等待", Toast.LENGTH_LONG).show(); Intent intent = new Intent(); intent.setClass(LoginActivity.this,UserDetailActivity.class); //intent.putExtra("url", newsList.get(arg1).url); startActivity(intent); LoginActivity.this.finish(); }else{ if (et_name.getText().toString().trim().length() == 0) { Toast.makeText(this, "请填写账号", Toast.LENGTH_SHORT).show(); } else if (et_password.getText().toString().trim().length() == 0) { Toast.makeText(this, "请填写密码", Toast.LENGTH_SHORT).show(); }else { Log.i("TAG","登录失败,请检查账号密码是否正确!"); Toast.makeText(LoginActivity.this, "登录失败,请检查账号密码是否正确!", Toast.LENGTH_LONG).show(); } } break; case R.id.newUer: Intent intent=new Intent(LoginActivity.this,RegisteredActivity.class); startActivity(intent); break; default: break; } } }
RegisteredActivity.java
package com.example.login; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import com.example.service.UserService; import com.example.userbean.User; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.text.Editable; import android.text.SpannableString; import android.text.Spanned; import android.text.TextWatcher; import android.text.style.AbsoluteSizeSpan; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class RegisteredActivity extends Activity implements OnClickListener { private ImageView img_back; private Button btn_registered; private EditText et_Account; private EditText et_Password; private EditText et_Password_true; private EditText et_Name; private EditText et_Company; private EditText et_Phone; SQLiteDatabase mysql; // phoneNum格式 private int Is; private String string; private int After; private boolean isIncrease = false; boolean isTrue = false; private Button bt1; private Button bt2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.registered); setContentView(R.layout.registered); // 找到控件 initView(); // 判断两次密码是否一致 initEditTextSet(); } /** * 判断两次密码是否一致方法 */ private void initEditTextSet() { et_Password_true .setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) {// 获得焦点 } else {// 失去焦点 if (!(et_Password_true .getText().toString().trim()).equals(et_Password .getText().toString().trim())) { et_Password_true .setError(getString(R.string.Inconsistent_password)); } else { isTrue = true; return; } } } }); } private void initView() { img_back = (ImageView) findViewById(R.id.registered_back);// 返回 btn_registered = (Button) findViewById(R.id.btn_registered);// 注册 et_Account = (EditText) findViewById(R.id.editText_Account_number);// 账号 et_Password = (EditText) findViewById(R.id.editText_Password);// 密码 et_Password_true = (EditText) findViewById(R.id.editText_Password_true);// 确认密码 et_Name = (EditText) findViewById(R.id.editText_Name);// 姓名 et_Company = (EditText) findViewById(R.id.editText_Company);// 单位 et_Phone = (EditText) findViewById(R.id.editText_Phone);// 手机 img_back.setOnClickListener(this); btn_registered.setOnClickListener(this); // 设置电话号文本自动生成344 格式例如:138 8888 8888 et_Phone.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { Is = arg0.length(); if (Is - After == 1) { isIncrease = true; } else { isIncrease = false; } if (isIncrease) { if (arg0.length() == 3) { string = arg0 + " "; et_Phone.setText(string); et_Phone.setSelection(4); } if (arg0.length() == 8) { string = arg0 + " "; et_Phone.setText(string); et_Phone.setSelection(9); } } } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { After = arg0.length(); } @Override public void afterTextChanged(Editable arg0) { } }); // ======================= 判断特殊字符于密码长度 =====================// final int mMaxLenth = 16;// 设置允许输入的字符长度 et_Password.addTextChangedListener(new TextWatcher() { private int cou = 0; int selectionEnd = 0; @Override public void onTextChanged(CharSequence s, int start, int before, int count) { cou = before + count; String editable = et_Password.getText().toString(); String str = stringFilter(editable); // 过滤特殊字符 if (!editable.equals(str)) { et_Password.setText(str); } et_Password.setSelection(et_Password.length()); cou = et_Password.length(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { if (cou > mMaxLenth) { Toast.makeText(RegisteredActivity.this, "密码长度已经为最长", Toast.LENGTH_SHORT).show(); selectionEnd = et_Password.getSelectionEnd(); s.delete(mMaxLenth, selectionEnd); } } }); // ------------------------ 判断特殊字符于密码长度 -----------------------// btn_registered.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { btn_registered.setBackgroundColor(getResources().getColor( R.color.blue_other_one)); } else if (event.getAction() == MotionEvent.ACTION_UP) { btn_registered.setBackgroundColor(getResources().getColor( R.color.blue_other)); } return false; } }); // 设置Edittext里面文本字体的大小 SpannableString ss = new SpannableString("请输入‘11位’本人手机号码"); AbsoluteSizeSpan ass = new AbsoluteSizeSpan(10, true); ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); et_Phone.setHint(new SpannableString(ss)); // 设置Edittext里面文本字体的大小 SpannableString pa = new SpannableString("请输入‘8-16位’不含有特殊字符的密码"); AbsoluteSizeSpan paw = new AbsoluteSizeSpan(10, true); pa.setSpan(paw, 0, pa.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); et_Password.setHint(new SpannableString(pa)); } /** * 设置密码特殊字的字符方法 * * @param str * @return * @throws PatternSyntaxException */ public static String stringFilter(String str) throws PatternSyntaxException { String regEx = "[/\\:*?<>|\"\n\t]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(str); return m.replaceAll(""); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.registered_back: finish(); break; // 完成注册 case R.id.btn_registered: if (et_Account.getText().toString().trim().length() == 0) { Toast.makeText(this, "请填写账号", Toast.LENGTH_SHORT).show(); } else if (et_Password.getText().toString().trim().length() == 0) { Toast.makeText(this, "请填写密码", Toast.LENGTH_SHORT).show(); } else if (et_Name.getText().toString().trim().length() == 0) { Toast.makeText(this, "请填写姓名", Toast.LENGTH_SHORT).show(); } else if (et_Company.getText().toString().trim().length() == 0) { Toast.makeText(this, "请填写单位名", Toast.LENGTH_SHORT).show(); } else if (et_Phone.getText().toString().trim().length() <= 0) { Toast.makeText(this, "请填写本人联系电话", Toast.LENGTH_SHORT).show(); } else { try { String account = et_Account.getText().toString().trim(); String password = et_Password.getText().toString().trim(); String password_true = et_Password_true.getText() .toString().trim(); String name = et_Name.getText().toString().trim(); String company = et_Company.getText().toString().trim(); String phone = et_Phone.getText().toString().trim(); UserService uService = new UserService( RegisteredActivity.this); User user = new User(); user.setAccount(account); user.setPassword(password); user.setPassword_true(password_true); user.setName(name); user.setPassword_true(password_true); user.setPhone(phone); user.setCompany(company); uService.register(user); // Toast.makeText(RegisteredActivityNew.this, "注册成功", // Toast.LENGTH_LONG).show(); LayoutInflater fac2 = LayoutInflater .from(RegisteredActivity.this); View dialogview2 = fac2.inflate(R.layout.tishi, null); TextView view_1 = (TextView) dialogview2 .findViewById(R.id.textView1); view_1.setText("注册成功!"); AlertDialog dialog2 = new AlertDialog.Builder( RegisteredActivity.this) .setTitle("提示框") .setView(dialogview2) .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick( DialogInterface arg0, int arg1) { Intent intent = new Intent(); intent.setClass( RegisteredActivity.this, LoginActivity.class); startActivity(intent); RegisteredActivity.this.finish(); } }).create(); dialog2.show(); } catch (Exception e) { Dialog dialog3 = new AlertDialog.Builder( RegisteredActivity.this) .setTitle("信息框") .setMessage("注册失败") .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick( DialogInterface arg0, int arg1) { } }).create(); dialog3.show(); } } break; default: break; } } }
UserDetailActivity.java
package com.example.login; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; public class UserDetailActivity extends Activity { private FrameLayout loading_view; private WebView webview; @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.webview); webview = (WebView) findViewById(R.id.webview); //加载过程中转圈的进度条 //loading_view = (FrameLayout) findViewById(R.id.loading_view); webview = (WebView) findViewById(R.id.webview); WebSettings webSettings = webview.getSettings(); //设置WebView属性,能够执行Javascript脚本 webSettings.setJavaScriptEnabled(true); //设置可以访问文件 webSettings.setAllowFileAccess(true); //设置支持缩放 webSettings.setBuiltInZoomControls(true); //加载需要显示的网页 webview.loadUrl("http://www.baidu.com"); // webview.loadUrl("file:///E:/java_demo_workspace/day01/day01/WebRoot/html/表单标签.html"); //设置Web视图 webview.setWebViewClient(new webViewClient ()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override //设置回退 //覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法 public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) { webview.goBack(); //goBack()表示返回WebView的上一页面 return true; } finish();//结束退出程序 return false; } //Web视图 private class webViewClient extends WebViewClient { public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } }
Service包
DatabaseHelper.java
package com.example.service; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DatabaseHelper extends SQLiteOpenHelper{ static String name="user.db"; static int dbVersion=1; public DatabaseHelper(Context context) { super(context, name, null, dbVersion); } //只有第一次创建的时候会用到。 @Override public void onCreate(SQLiteDatabase db) { String sql="create table user(id integer primary key autoincrement,Account varchar(20),Password varchar(20),Password_true varchar(20),Name varchar(20),Company varchar(20),Phone varchar(20))"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
UserService.java
package com.example.service; import com.example.userbean.User; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class UserService { private DatabaseHelper dbHelper; public UserService(Context context) { dbHelper = new DatabaseHelper(context); } //登录用 public boolean login(String Account,String Password){ SQLiteDatabase sdb=dbHelper.getReadableDatabase(); String sql="select * from user where Account=? and Password=?"; Cursor cursor=sdb.rawQuery(sql, new String[]{Account,Password}); if(cursor.moveToFirst()==true){ cursor.close(); return true; } return false; } //注册用 public boolean register(User user){ SQLiteDatabase sdb=dbHelper.getReadableDatabase(); String sql="insert into user(Account,Password,Password_true,Name,Company,Phone) values(?,?,?,?,?,?)"; Object obj[]={user.getAccount(),user.getPassword(),user.getPassword_true(),user.getName(),user.getCompany(),user.getPhone()}; sdb.execSQL(sql, obj); return true; } }
UserBean包
User.java
package com.example.userbean; import java.io.Serializable; public class User implements Serializable{ private int id; private String Account; private String Password; private String Password_true; private String Name; private String Company; private String Phone; public User() { super(); // TODO Auto-generated constructor stub } public User(int id, String account, String password, String password_true, String name, String company, String phone) { super(); this.id = id; Account = account; Password = password; Password_true = password_true; Name = name; Company = company; Phone = phone; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAccount() { return Account; } public void setAccount(String account) { Account = account; } public String getPassword() { return Password; } public void setPassword(String password) { Password = password; } public String getPassword_true() { return Password_true; } public void setPassword_true(String password_true) { Password_true = password_true; } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getCompany() { return Company; } public void setCompany(String company) { Company = company; } public String getPhone() { return Phone; } public void setPhone(String phone) { Phone = phone; } @Override public String toString() { return "User [id=" + id + ", Account=" + Account + ", Password=" + Password + ", Password_true=" + Password_true + ", Name=" + Name + ", Company=" + Company + ", Phone=" + Phone + "]"; } }