User data storage + server upload in Android login interface (2)

                                                    The upload server for registered events

【Interface Change】

According to the previous app registration experience, change the interface to the following figure:


The registration is performed by sending the mobile phone verification code of the app. The mobile phone SMS verification is a certificate that the enterprise gives to the consumer (user), and the identity is verified through the verification code of the mobile phone SMS content. At present, the most commonly used ones are online banking of major banks, online shopping malls, group buying websites, ticketing companies, etc. Mobile phone SMS verification uses SMS verification code to register members, which greatly reduces the data of illegal registration and bad registration.

=================================================================================

At the same time of registration, it is necessary to detect whether the mobile phone number is in the mobile phone number format:

/**
	 *
	 * Determine whether the string format is the phone number format
	 *
	 * Remove leading and trailing spaces when processing strings. Judgment basis
	 *
	 * java-regular expression to determine mobile phone number
	 *
	 * To more accurately match mobile phone numbers, it is not enough to match only 11 digits. For example, there is no number segment starting with 144.
	 *
	 * Therefore, it is necessary to clarify how many number segments have been opened now. The allocation of national number segments is as follows:
	 *
	 * Move: 134, 135, 136, 137, 138, 139, 150, 151, 157(TD), 158, 159, 187, 188
	 *
	 * Unicom: 130, 131, 132, 152, 155, 156, 185, 186
	 *
	 * Telecom: 133, 153, 180, 189, (1349 Satcom)
	 *
	 * @param phone_num
	 * @return true: yes false: no
	 */
	public static boolean isPhoneNum(String phone_num) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(14[0-9])|(17[0-9])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher (phone_num);
		return m.matches();
	}

 ================================================================================

[Registration class is officially used]: Use the afinal framework, although the afinal framework has not been updated for a long time, but I am accustomed to using it, and I have not planned to abandon it for the time being when I am not used to using xutil3

public class RegisterActivity extends Activity implements OnClickListener{
	private EditText phone;
	private TextView getCode;
	private EditText code;
	private EditText pwd; // password
	private EditText repwd;
	private Button login_ok;
	ProgressBar progressBar;
	Trades trades;


	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView(R.layout.activity_register);
		init();
		//Activity manager, responsible for adding to the queue
		MyActivityManager.addActivity(this);
		findViewById(R.id.iv_back_of_register).setOnClickListener(this);
		findViewById(R.id.tv_login).setOnClickListener(this);
		handler = new Handler () {
			public void handleMessage(Message msg) {
				if (msg.what == 0x1122) {
					ConfigUtil.ProgressBarOff(progressBar);
					startActivity(new Intent(RegisterActivity.this,
							GuideSelect.class));
					finish();
				}
			}
		};
		login_ok.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
			if(ConfigUtil.isPhoneNum(phone.getText().toString()))
				login_Button();
			else
				Toast.makeText(getApplicationContext(), "The phone number is not in the correct format", 1).show();
				
			}
		});
		
		
	}
	/*
	 * Get the component object
	 */
	public void init(){
		progressBar=(ProgressBar)findViewById(R.id.login_progressBar);
		phone=(EditText)findViewById(R.id.register_username);
		getCode=(TextView)findViewById(R.id.getcode);
		code=(EditText)findViewById(R.id.code);
		pwd=(EditText)findViewById(R.id.register_password1);
		repwd=(EditText)findViewById(R.id.register_password2);
		login_ok=(Button)findViewById(R.id.register_ok_button);
	}
	public void login_Button(){
		if (isUserPwdRight() && isUserRight(phone.getText().toString())) {
			register(phone.getText().toString(), pwd.getText().toString(), code
					.getText().toString(), ConfigField.ServerUrl.RegisterUrl);
		}
		
	}
	/**
	 * Submit registration data to the server
	 *
	 * Before submitting to the service, please ensure that 1. The username and password are legal 2. The passwords entered before and after are the same 3. Whether the network connection is normal
	 *
	 * @param phone
	 * :username
	 * @param userPwd
	 * :password
	 * @param code
	 * : verification code
	 * @param url
	 * : Submitted address
	 */
	public void register(String phone,String pwd,String code,String url){
		
		AjaxParams param=new AjaxParams();
		param.put("username", phone);
		String md5pwd=MD5Util.MD5(pwd);
		param.put("pwd", md5pwd);
		param.put("code", code);
		FinalHttp finalhttp=new FinalHttp();
		finalhttp.post(url, param, new AjaxCallBack<String>() {
			public void onSuccess(String t){
				super.onSuccess(t);
			
				try {
					JSONObject json=new JSONObject();
					JSONObject jsondata=json.getJSONObject("data");
					if(jsondata.has("user_id")){
						int user_id=Integer.parseInt(jsondata.getString("user_id"));
						System.out.println(user_id+"");
						ConfigField.Flag.setMyID(user_id);
						goToGuideActivity();
						
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace ();
					System.out.println("Wrong is jumping out,you can't submit you logInfo");
				}
				
			}
			
/*
 * After success, the server will initiate a request, get the user id, call the database, and store the user data in the database
 */
			private void goToGuideActivity() {
				// TODO Auto-generated method stub
				new Thread(){
					
					public void run(){
						FinalHttp finalhttp=new FinalHttp();
						int id=ConfigField.Flag.getMyID();
						finalhttp.get(ConfigField.ServerUrl.RegisterUrl,new AjaxCallBack<String>(){
							
							public void onSuccess(String t) {
								
									
									try {
										JSONObject jsonObject = new JSONObject(t);
								         User user = new User();
										JSONObject jsonUser=jsonObject.getJSONObject("data");
										user.setUser_id(jsonUser.getInt("user_id"));
										Userdb ud = new Userdb(getApplicationContext());
										ud.clear();
										ud.addOne (user);
										ConfigField.Flag.setMy(user);
										To_MainUI();//Jump to the main interface
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										e.printStackTrace ();
									}
									
								
							}
							public void onFailure(Throwable t,
									int errorNo, String strMsg) {
								ConfigUtil.ProgressBarOff(progressBar);
								Toast.makeText(getApplicationContext(), "失败",1).show();
							};
						});
							
						
					}
					
				}.start();
				
			}
			public void onFailure(Throwable t, int errorNo, String strMsg){
				super.onFailure(t, errorNo, strMsg);
				System.out.println("------"+strMsg+"------");
				Toast.makeText(getApplicationContext(), "Networking failed", 1).show();
			}
			
		});
	
		
		
	}
	
	

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.iv_back_of_register:
			finish();
			break;
		case R.id.tv_login:
			startActivity(new Intent(this,LogInActivity.class));
			finish();
			break;
			
		}
		
	}
	/**
	 * Determine whether the user name is legal
	 *
	 * @param name
	 * @return
	 */
	public boolean isUserRight(String phone) {
		if (phone.equals("")) {
			www.zhy.nomalutils.ToastUtil.show_text(getApplicationContext(), "Phone or name cannot be empty");
			return false;
		} else
			return true;
	}

	public void To_MainUI () {
		startActivity(new Intent(RegisterActivity.this, GuideSelect.class));
		RegisterActivity.this.finish();
	}

	/**
	 * Determine whether the user password is legal
	 *
	 * @param pwd
	 * @return
	 */
	public boolean isUserPwdRight() {
		if (repwd.getText().toString().equals(pwd.getText().toString())
				&& !pwd.getText().toString().equals(""))
			return true;
		else {
			if (pwd.getText().toString().equals(""))
				www.zhy.nomalutils.ToastUtil.show_text(getApplicationContext(), "Password cannot be empty.");
			else
				www.zhy.nomalutils.ToastUtil.show_text(getApplicationContext(), "The password is incorrect twice.");
			return false;
		}
	}

}

 ===============================================================================

【database】

The above involves the database code:

The afinal framework is very simple and convenient to create a database. For details, please take a look at the link: https://github.com/yangfuhai/afinal

First create the User class:

public class User implements DataModel {
	/*
	 * User information encapsulation class
	 */

	@Id(column = "id")
	private int id;
	private String name;
	private String tel;
	
	public String getStatusInfo() {
		return statusInfo;
	}

	private int user_id;
	private int status;

	public User() {
		name = "User";
		
		
		
	}
	public int getUser_id() {
		return user_id;
	}

	public void setUser_id(int user_id) {
		this.user_id = user_id;
	}

	
	
	
}

 A point to note:

//It should be noted here that the User object must have an id attribute, or an attribute annotated with @ID

It was ignored when I first started learning, so the creation was unsuccessful, and the addition of permission issues also needed attention.

================================================================================

【URL】:

Create a static class specifically to call the URL for example:

public static class ServerUrl {
		// Log in
		public static final String LoginUrl = "http://kaka.ileban.com/index.php/Api/User/login";
		// register
		public static final String RegisterUrl = "http://kaka.ileban.com/index.php/Api/User/register/";
		// upload image
		
	}

 The reason for using static classes, static methods, and static properties is that you can directly call their methods and properties without creating a class object.

=================================================================================

【Database data operation】:

/**
 * User data table operation class
 *
 */

public class Userdb {

	private FinalDb finalDb;

	public Userdb(Context context) {
		finalDb = FinalDb.create(context, ConfigField.Db.DBNAME);
	}

	
	public boolean isLogin()
	{
		try {
			List<User>list=finalDb.findAll(User.class);
			ConfigField.Flag.setMy(list.get(0));
			if(list.size()>0)
				return true;
		} catch (Exception e) {
			// TODO: handle exception
		}
		 return false;
	}
	

	//User login, write user information to the database
	public void put_in_db(int id)
	{
		try {
			List<User>list=finalDb.findAllByWhere(User.class, "user_id="+id);
			if(list.size()==0)
			{
				User user=new User();
				user.setUser_id(id);
				addOne(user);
				list.add(user);
			}
			ConfigField.Flag.setMy(list.get(0));
		} catch (Exception e) {
			Log.i("Main", e.toString());
		}
		
	}
	
	public void clear() {
		finalDb.deleteAll(User.class);
	}

	public List<User> getAll() {
		return finalDb.findAll(User.class);
	}

	/**
	 * Bulk add user information
	 *
	 * @param list
	 */
	public void add(List<User> list) {
		for (int i = 0; i < list.size(); i++) {
			User user = list.get(i);
			finalDb.save(user);
		}
	}

	/**
	 * Batch update user information
	 *
	 * @param list
	 */
	public void update(List<User> list) {
		clear();
		for (int i = 0; i < list.size(); i++) {
			User user = list.get(i);
			finalDb.save(user);
		}
	}

	public void addOne(User user) {
		finalDb.save(user);

	}

	public void update(User user) {
		clear();
		finalDb.save(user);
	}
}

 =================================================================================

【Summarize】:

The more important thing in this connection is not the demo but the concept of establishing a login registration system, how to set the class, interface, and the standard format of the upload server, and the classification should be clear. Several packages are created under the project.



 What kind of data is placed, not only can you see it at a glance, but also for the secondary development of the project and code reuse, the handover of small partners brings a good effect. In the past, Xiaobian also wrote it all in one package for convenience. The speed is fast, It seems very uncomfortable. The time it takes to hand over to my friends is far more than my own classification time, so these classes are also forcing myself to learn more professional construction projects, and do basic login registration, simple login registration is absolutely It is not simple, many lines of code and classes are required to pay attention to many small details, and it is necessary to carefully analyze how to allocate and call more conveniently. The knowledge points that need to be paid attention to in this lesson: 1. The use of afinal framework 2. Understanding of Ajaxcallback callback function 3. The server uploads knowledge Json parsing, and the database is used.

 

The next class will describe the login interface. Compared with registration, it is much simpler. I believe that with the foundation of this class, it will be much easier to understand in the next class. Come on with me! ! !

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326562920&siteId=291194637