티스토리 뷰
마이닷홈
닷홈 - 호스팅은 닷홈
닷홈은 무제한 웹호스팅, 무료호스팅, 도메인, 홈페이지빌더, 무제한메일, SSL보안인증서, 서버호스팅, 코로케이션 서비스를 제공하고 있습니다.
www.dothome.co.kr
사용된 api
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.volley">
<uses-permission android:name="android.permission.INTERNET"/>
<application
{"result":"NK","msg":"비번오류","error_code":"1000"}
>> 중괄호로 뜨니까 jsonObject다. jsonArr는 대괄호로 시작
팝업 Toast 메세지하는데, 자주 쓰이니까 메소드로 빼놓기
TEXT WATCHER / 아이디 중복체크 안한 상태에서 가입해버리지 않도록
length<1 -=> 아이디가 1보다 작다 = 아이디가 비었다.
암호도 똑같이 처리해줌
자동로그인 ->savepref 메소드
requestCode사용법
더보기
전체코드
MainActivity
package com.real.boardexam;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText idEt;
EditText pwEt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
idEt = findViewById(R.id.id_et);
pwEt = findViewById(R.id.pw_et);
findViewById(R.id.join_btn).setOnClickListener(this);
findViewById(R.id.login_btn).setOnClickListener(this);
}
private String getData(String key){
String value = "";
SharedPreferences sharedPreferences = getSharedPreferences("login",MODE_PRIVATE);
value = sharedPreferences.getString(key,"no");
return value;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1000 ){ //회원 가입 창에서 복귀했다
if(resultCode == RESULT_OK){ //회원 가입 성공
String name = getData("name");
String pass = getData("pass");
//자동 로그인 시도
}else{ //회원 가입 실패
}
}
}
@Override
public void onClick(View view) {
if(view.getId() == R.id.join_btn){
startActivityForResult(new Intent(this, com.real.boardexam.JoinActivity.class), 1000);
}
}
}
JoinActivity
package com.real.boardexam;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class JoinActivity extends AppCompatActivity implements View.OnClickListener {
boolean isJoinChk;
EditText idEt;
EditText pwEt1;
EditText pwEt2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_join);
idEt = findViewById(R.id.id_et);
pwEt1 = findViewById(R.id.pw_et1);
pwEt2 = findViewById(R.id.pw_et2);
isJoinChk = false; // 중복체크 안한 상태
setResult(RESULT_CANCELED); // 기본적인 값은 회원가입 실패
findViewById(R.id.dup_btn).setOnClickListener(this);
findViewById(R.id.join_btn).setOnClickListener(this);
idEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//idEt 안에 텍스트가 바뀌면 무조건 중복 체크 플래그 원상복귀
isJoinChk = false;
}
@Override
public void afterTextChanged(Editable editable) {
}
});
}
//name이 중복되었는 지 확인하는 요청
private void chkID() {
RequestQueue stringRequest = Volley.newRequestQueue(this);
String url = "http://heutwo.dothome.co.kr/temp/test_chk.php";
StringRequest myReq = new StringRequest(Request.Method.POST, url,
successListener, errorListener) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("name", idEt.getText().toString().trim());
return params;
}
};
myReq.setRetryPolicy(new DefaultRetryPolicy(3000, 0, 1f)
);
stringRequest.add(myReq);
}
private void savePref(String key, String value){
SharedPreferences sharedPreferences = getSharedPreferences("login", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
Response.Listener<String> successListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String str = jsonObject.getString("result");
if (str.equalsIgnoreCase("OK")) { // 사용가능한 아이디
isJoinChk = true;
showToast("사용 가능한 아이디");
} else { //사용 불가능한 아이디
isJoinChk = false;
showToast("사용 불가능한 아이디");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// error.getLocalizedMessage();
// error.getMessage();
// error.getStackTrace();
}
};
private void requestForJoin() {
RequestQueue stringRequest = Volley.newRequestQueue(this);
String url = "http://heutwo.dothome.co.kr/temp/test_join.php";
StringRequest myReq = new StringRequest(Request.Method.POST, url,
successJoinListener, errorListener) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("name", idEt.getText().toString().trim());
params.put("pass", pwEt1.getText().toString().trim());
return params;
}
};
myReq.setRetryPolicy(new DefaultRetryPolicy(3000, 0, 1f)
);
stringRequest.add(myReq);
}
Response.Listener<String> successJoinListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String str = jsonObject.getString("result");
if (str.equalsIgnoreCase("OK")) { //회원 가입 성공!
showToast("회원 가입 성공!");
savePref("name", idEt.getText().toString().trim()); //자동 로그인을 위해 아이디 저장
savePref("pass", pwEt1.getText().toString().trim()); //자동 로그인을 위해 암호 저장
setResult(RESULT_OK); // 회원 가입 성공 표시
finish(); // 액티비티 종료
} else {
showToast("회원 실패!");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
@Override
public void onClick(View view) {
if (view.getId() == R.id.join_btn) {
if (isJoinChk) { // 아이디 중복체크 했니?
String pw1 = pwEt1.getText().toString().trim();
String pw2 = pwEt2.getText().toString().trim();
if (idEt.getText().toString().trim().length() < 1) { //아이디 입력칸이 비었니?
showToast("아이디를 입력하세요");
} else if (pwEt1.getText().toString().trim().length() < 1) { //암호 입력칸이 비었니?
showToast("암호를 입력하세요");
} else if(!pw1.equals(pw2)){ // 암호 입력칸 2개가 일치하니?
showToast("암호가 일치하지 않습니다");
}else{
requestForJoin(); // 회원가입 시도
}
} else {
showToast("중복체크 하셈");
}
} else if (view.getId() == R.id.dup_btn) {
chkID();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/id_et"
android:layout_width="200dp"
android:layout_height="70dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="200dp"
android:hint="이름"
android:padding="8dp"
android:textSize="20sp" />
<EditText
android:id="@+id/pw_et"
android:layout_width="200dp"
android:layout_height="70dp"
android:layout_below="@+id/id_et"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:hint="암호"
android:inputType="textPassword"
android:padding="8dp"
android:textSize="20sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/pw_et"
android:layout_alignLeft="@+id/pw_et"
android:layout_alignRight="@+id/pw_et"
android:orientation="horizontal">
<Button
android:id="@+id/join_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="가입"
android:textSize="20sp" />
<Button
android:id="@+id/login_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="로그인"
android:textSize="20sp" />
</LinearLayout>
</RelativeLayout>
activity_join.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".JoinActivity">
<EditText
android:id="@+id/id_et"
android:layout_width="200dp"
android:layout_height="70dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="200dp"
android:hint="이름"
android:inputType="text"
android:maxLines="1"
android:maxLength="12"
android:padding="8dp"
android:textSize="20sp" />
<EditText
android:id="@+id/pw_et1"
android:layout_width="200dp"
android:layout_height="70dp"
android:layout_below="@+id/id_et"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:hint="암호"
android:inputType="textPassword"
android:maxLines="1"
android:maxLength="12"
android:padding="8dp"
android:textSize="20sp" />
<EditText
android:id="@+id/pw_et2"
android:layout_width="200dp"
android:layout_height="70dp"
android:layout_below="@+id/pw_et1"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:hint="암호"
android:inputType="textPassword"
android:maxLines="1"
android:maxLength="12"
android:padding="8dp"
android:textSize="20sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/pw_et2"
android:layout_alignLeft="@+id/pw_et2"
android:layout_alignRight="@+id/pw_et2"
android:orientation="horizontal">
<Button
android:id="@+id/dup_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="중복확인"
android:textSize="20sp" />
<Button
android:id="@+id/join_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="가입"
android:textSize="20sp" />
</LinearLayout>
</RelativeLayout>
댓글