一張圖看懂Android註冊登入+服務端
阿新 • • 發佈:2019-02-07
整個環境是執行在Android虛擬機器+tomcat伺服器+MySQL上面的。。。需要對服務端以及Android都要比較熟悉。才能夠比較完整的配置下來。。。
Android端相關程式碼:
1.註冊登入成功後的頁面的類
package com.test.login;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class UserInfoActivity extends Activity {
private TextView tvUsername;
private TextView tvGender;
private TextView tvAge;
private TextView tvPhone;
private TextView tvEmail;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_info_activity);
initViews();
Intent intent = getIntent();
displayUserInfo(intent);
}
private void initViews() {
tvUsername = (TextView) findViewById(R.id.usr_info_username);
tvGender = (TextView) findViewById(R.id.usr_info_gender);
tvAge = (TextView) findViewById(R.id.usr_info_age);
tvPhone = (TextView) findViewById(R.id.usr_info_phone);
tvEmail = (TextView) findViewById(R.id.usr_info_email);
}
private void displayUserInfo(Intent intent) {
String username = intent.getStringExtra("username");
String gender = intent.getStringExtra("gender");
int age = intent.getIntExtra("age", -1);
String phone = intent.getStringExtra("phone");
String email = intent.getStringExtra("email");
tvUsername.setText(username);
tvGender.setText(gender);
tvAge.setText(String.valueOf(age));
tvPhone.setText(phone);
tvEmail.setText(email);
}
}
2.註冊使用者的類
package com.test.login;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.MailTo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class CreateUserActivity extends Activity implements OnClickListener {
public static final String CREATE_ACCOUNT_URL = "http://10.0.2.2:8080/test/servlet/NewAccount";
public static final int MSG_CREATE_RESULT = 1;
private EditText eUsername;
private EditText ePwd1;
private EditText ePwd2;
private RadioGroup rGender;
private EditText eAge;
private EditText ePhone;
private EditText eEmail;
private Button btnSubmit;
private Button btnReset;
ProgressDialog progress;
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch(msg.what) {
case MSG_CREATE_RESULT:
progress.dismiss();
JSONObject json = (JSONObject) msg.obj;
hanleCreateAccountResult(json);
break;
}
}
};
private void hanleCreateAccountResult(JSONObject json) {
/*
* result_code:
* 0 註冊成功
* 1 使用者名稱已存在
* 2 資料庫操作異常
* */
int result;
try {
result = json.getInt("result_code");
} catch (JSONException e) {
Toast.makeText(this, "沒有獲取到網路的響應!", Toast.LENGTH_LONG).show();
e.printStackTrace();
return;
}
if(result == 1) {
Toast.makeText(this, "使用者名稱已存在!", Toast.LENGTH_LONG).show();
return;
}
if(result == 2) {
Toast.makeText(this, "註冊失敗!服務端出現異常!", Toast.LENGTH_LONG).show();
return;
}
if(result == 0) {
Toast.makeText(this, "註冊成功!前往登陸介面!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
return;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_user_activity);
initViews();
}
private void initViews() {
eUsername = (EditText)findViewById(R.id.new_username);
ePwd1 = (EditText)findViewById(R.id.new_password_1);
ePwd2 = (EditText)findViewById(R.id.new_password_2);
rGender = (RadioGroup)findViewById(R.id.new_radio_group_gender);
eAge = (EditText)findViewById(R.id.new_age);
ePhone = (EditText)findViewById(R.id.new_phone);
eEmail = (EditText)findViewById(R.id.new_email);
btnSubmit = (Button)findViewById(R.id.new_btn_submit);
btnReset = (Button)findViewById(R.id.new_btn_reset);
btnSubmit.setOnClickListener(this);
btnReset.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.new_btn_submit:
handleCreateAccount();
break;
case R.id.new_btn_reset:
handleReset();
break;
}
}
private void handleCreateAccount() {
boolean isUsernameValid = checkUsername();
if(!isUsernameValid) {
Toast.makeText(this, "使用者名稱不正確,請重新輸入", Toast.LENGTH_LONG).show();
return;
}
int pwdResult = checkPassword();
if(pwdResult == 1) {
Toast.makeText(this, "兩次輸入的密碼不一致,請確認!", Toast.LENGTH_LONG).show();
return;
}
if (pwdResult == 2) {
Toast.makeText(this, "密碼不能為空!", Toast.LENGTH_LONG).show();
return;
}
int isAgeValid = checkAge();
if(isAgeValid == -1) {
Toast.makeText(this, "年齡不能為空!", Toast.LENGTH_LONG).show();
return;
}
if(isAgeValid == -2) {
Toast.makeText(this, "年齡超出範圍(1~100)!", Toast.LENGTH_LONG).show();
return;
}
if(isAgeValid == -3) {
Toast.makeText(this, "年齡格式輸入錯誤,請不要輸入字母、符號等其他字串!", Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(ePhone.getText().toString())) {
Toast.makeText(this, "請輸入電話號碼!", Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(eEmail.getText().toString())) {
Toast.makeText(this, "請輸入郵箱!", Toast.LENGTH_LONG).show();
return;
}
createAccount();
}
private void createAccount() {
progress = new ProgressDialog(this);
progress.setCancelable(false);
progress.setCanceledOnTouchOutside(false);
progress.show(this, null, "註冊中...");
new Thread(new Runnable() {
@Override
public void run() {
Log.d("yanghongbing", "Start Network!");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(CREATE_ACCOUNT_URL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", eUsername.getText().toString()));
params.add(new BasicNameValuePair("password", ePwd1.getText().toString()));
RadioButton selectedGender = (RadioButton)CreateUserActivity.this.findViewById(rGender.getCheckedRadioButtonId());
params.add(new BasicNameValuePair("gender",
selectedGender.getText().toString()));
params.add(new BasicNameValuePair("age", eAge.getText().toString()));
params.add(new BasicNameValuePair("phone", ePhone.getText().toString()));
params.add(new BasicNameValuePair("email", eEmail.getText().toString()));
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
if(httpResponse.getStatusLine().getStatusCode() == 200) {
Log.d("yanghongbing", "Network OK!");
HttpEntity entity = httpResponse.getEntity();
String entityStr = EntityUtils.toString(entity);
String jsonStr = entityStr.substring(entityStr.indexOf("{"));
JSONObject json = new JSONObject(jsonStr);
sendMessage(MSG_CREATE_RESULT, json);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
private boolean checkUsername() {
String username = eUsername.getText().toString();
if(TextUtils.isEmpty(username)) {
return false;
}
return true;
}
private int checkPassword() {
/*
* return value:
* 0 password valid
* 1 password not equal 2 inputs
* 2 password empty
* */
String pwd1 = ePwd1.getText().toString();
String pwd2 = ePwd2.getText().toString();
if(!pwd1.equals(pwd2)) {
return 1;
} else if(TextUtils.isEmpty(pwd1)) {
return 2;
} else {
return 0;
}
}
private int checkAge() {
/*
* return value
* 0 輸入合法
* -1 輸入為空
* -2輸入為負數
* -3輸入為非數值字串或包括小數
* */
int ageNum;
String age = eAge.getText().toString();
if(TextUtils.isEmpty(age)) {
return -1;
}
try {
ageNum = Integer.parseInt(age);
} catch (NumberFormatException e) {
e.printStackTrace();
return -3;
}
if(ageNum <= 0 || ageNum > 100) {
return -2;
}
return 0;
}
private void handleReset() {
eUsername.setText("");
ePwd1.setText("");
ePwd2.setText("");
((RadioButton)(rGender.getChildAt(0))).setChecked(true);
eAge.setText("");
ePhone.setText("");
eEmail.setText("");
}
private void sendMessage(int what, Object obj) {
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
mHandler.sendMessage(msg);
}
}
3.登入頁面的類
package com.test.login;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
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 {
private EditText loginUsername;
private EditText loginPassword;
private Button loginButton;
private Button createButton;
private ProgressDialog loginProgress;
public static final int MSG_LOGIN_RESULT = 0;
public String serverUrl = "http://10.0.2.2:8080/test/servlet/loadMessage";
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch(msg.what) {
case MSG_LOGIN_RESULT:
loginProgress.dismiss();
JSONObject json = (JSONObject) msg.obj;
handleLoginResult(json);
break;
}
};
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
initViews();
}
private void initViews() {
loginUsername = (EditText)findViewById(R.id.login_username);
loginPassword = (EditText)findViewById(R.id.login_password);
loginButton = (Button)findViewById(R.id.login);
createButton = (Button)findViewById(R.id.create_count);
loginButton.setOnClickListener(this);
createButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.login:
handleLogin();
break;
case R.id.create_count:
handleCreateCount();
break;
default:
break;
}
}
private void handleLogin() {
String username = loginUsername.getText().toString();
String password = loginPassword.getText().toString();
login(username, password);
}
private void login(final String username, final String password) {
loginProgress = new ProgressDialog(this);
loginProgress.setCancelable(false);
loginProgress.setCanceledOnTouchOutside(false);
loginProgress.show(this, null, "登陸中...");
new Thread(new Runnable() {
@Override
public void run() {
Log.d("yanghongbing", "start network!");
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(serverUrl);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
HttpResponse httpResponse = null;
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
httpResponse = client.execute(httpPost);
if(httpResponse.getStatusLine().getStatusCode() == 200) {
Log.d("yanghongbing", "network OK!");
HttpEntity entity = httpResponse.getEntity();
String entityString = EntityUtils.toString(entity);
String jsonString = entityString.substring(entityString.indexOf("{"));
Log.d("yanghongbing", "entity = " + jsonString);
JSONObject json = new JSONObject(jsonString);
sendMessage(MSG_LOGIN_RESULT, json);
Log.d("yanghongbing", "json = " + json);
}
} catch (UnsupportedEncodingException e) {
Log.d("yanghongbing", "UnsupportedEncodingException");
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.d("yanghongbing", "ClientProtocolException");
e.printStackTrace();
} catch (IOException e) {
Log.d("yanghongbing", "IOException");
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
Log.d("yanghongbing", "IOException");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
private void handleCreateCount() {
Intent intent = new Intent(this, CreateUserActivity.class);
startActivity(intent);
finish();
}
private void handleLoginResult(JSONObject json){
/*
* login_result:
* -1:登陸失敗,未知錯誤!
* 0: 登陸成功!
* 1:登陸失敗,使用者名稱或密碼錯誤!
* 2:登陸失敗,使用者名稱不存在!
* */
int resultCode = -1;
try {
resultCode = json.getInt("result_code");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
switch(resultCode) {
case 0:
onLoginSuccess(json);
break;
case 1:
Toast.makeText(this, "使用者名稱或密碼錯誤!", Toast.LENGTH_LONG).show();
break;
case 2:
Toast.makeText(this, "使用者名稱不存在!", Toast.LENGTH_LONG).show();
break;
case -1:
default:
Toast.makeText(this, "登陸失敗!未知錯誤!", Toast.LENGTH_LONG).show();
break;
}
}
private void onLoginSuccess(JSONObject json) {
Intent intent = new Intent(this, UserInfoActivity.class);
try {
intent.putExtra("username", json.getString("username"));
intent.putExtra("gender", json.getString("gender"));
intent.putExtra("age", json.getInt("age"));
intent.putExtra("phone", json.getString("phone"));
intent.putExtra("email", json.getString("email"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(intent);
finish();
}
private void sendMessage(int what, Object obj) {
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
mHandler.sendMessage(msg);
}
}
Android的xml:
1.登陸註冊頁面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:layout_marginTop="80dip">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="使用者名稱"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/login_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_weight="1" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="密 碼"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/login_password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="10dip"
android:inputType="textPassword" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:gravity="center">
<Button
android:id="@+id/login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登陸" />
<Button
android:id="@+id/create_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="註冊" />
</LinearLayout>
</LinearLayout>
2.註冊資訊的xml
<?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" >
<LinearLayout
android:id="@+id/UserInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dip"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:layout_weight="0.85"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="使用者名稱"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/new_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="5dip" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout7"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="密 碼"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/new_password_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="5dip"
android:inputType="textPassword" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout8"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="密 碼"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/new_password_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="5dip"
android:inputType="textPassword" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dip">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="性 別"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RadioGroup
android:id="@+id/new_radio_group_gender"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:orientation="horizontal"
>
<RadioButton
android:id="@+id/new_gender_boy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:layout_marginLeft="10dip"
android:text="男" />
<RadioButton
android:id="@+id/new_gender_girl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:text="女" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dip">
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="年 齡"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/new_age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:layout_weight="1"
android:inputType="number" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dip" >
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="電 話"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/new_phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="5dip"
android:inputType="phone" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dip" >
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email "
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/new_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="5dip"
android:inputType="textEmailAddress" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dip"
android:gravity="center">
<Button
android:id="@+id/new_btn_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="提交" />
<Button
android:id="@+id/new_btn_reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="重置" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
3.登入後顯示資訊的xml:
<?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:layout_marginLeft="20dip"
android:layout_marginRight="20dip">
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dip">
<TextView
android:id="@+id/textView1"
android:layout_width=