캡스톤

Android에서 MySQL로 데이터 저장하기 (로그인)

cocoaaa 2020. 6. 1. 00:31

회원가입에서 저장한 회원 정보를 이용해 로그인 구현을 해보자.

 

https://cocoaaa.tistory.com/7

 

Android에서 MySQL로 데이터 저장하기 (회원가입)

Android에서 MySQL로 회원가입을 위해 데이터 저장을 해보자. 그 전에 이전 포스팅에서 했던 서버 구축을 꼭 해주어야 하고 만약 저장할 데이터에 한글이 있다면 언어 설정도 바꿔줘야한다. https://co

cocoaaa.tistory.com

회원가입 부분은 이 포스팅을 참고하도록 한다.

 

 

앞부분에서 회원가입을 해준 아이디를 사용할것이다.

 

앞에서 쓴 dbcon.php를 작성을 빼먹어서 여기에 추가한다. 이 코드를 include하여 매번 DB연결을 할때마다 작성해줘야하는 번거로움을 덜어준다.

dbcon.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
 
    $host = 'localhost';
    $username = 'root';
    $password = 'moacafe1!';
    $dbname = 'cafeinfo';
 
 
    $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
 
    try {
 
        $con = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8",$username$password);
    } catch(PDOException $e) {
 
        die("Failed to connect to the database: " . $e->getMessage());
    }
 
 
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
 
    if(function_exists('get_magic_quotes_gpc'&& get_magic_quotes_gpc()) {
        function undo_magic_quotes_gpc(&$array) {
            foreach($array as &$value) {   
                if(is_array($value)) {
                    undo_magic_quotes_gpc($value);
                }
                else {
                    $value = stripslashes($value);
                }
            }
        }
 
        undo_magic_quotes_gpc($_POST);
        undo_magic_quotes_gpc($_GET);
        undo_magic_quotes_gpc($_COOKIE);
    }
        undo_magic_quotes_gpc($_POST);
        undo_magic_quotes_gpc($_GET);
        undo_magic_quotes_gpc($_COOKIE);
    }
 
    header('Content-Type: text/html; charset=utf-8');
    #session_start();
?>
 
cs

 

 

 

서버에 MySQL에 데이터 저장을 요청할 php코드를 작성한다.

Login.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
  error_reporting(E_ALL);
  ini_set('display_errors',1);
 
  include('dbcon.php');
 
  $userID=isset($_POST['userID']) ? $_POST['userID'] : '';
  $userPassword=isset($_POST['userPassword']) ? $_POST['userPassword'] : '';
 
  $android = strpos($_SERVER['HTTP_USER_AGENT'], "Android");
 
  if ($userID != "" ){
 
    $sql="select * from user where userID='$userID' AND userPassword=SHA1('$userPassword')";
    $stmt = $con->prepare($sql);
    $stmt->execute();
 
    if ($stmt->rowCount() == 0){
 
      echo "'";
      echo $userID;
      echo "' no id OR wrong password.";
    }
    else{
      $data = array();
 
      while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
 
        extract($row);
 
        array_push($data,
          array('userID'=>$row["userID"],
          'userPassword'=>$row["userPassword"],
          'email'=>$row["email"],
          'phoneNumber'=>$row["phoneNumber"],
          'userSort'=>$row["userSort"]
        ));
 
      if (!$android) {
          echo "<pre>";
          print_r($data);
          echo '</pre>';
      }else
      {
          header('Content-Type: application/json; charset=utf8');
          $json = json_encode(array("user"=>$data), JSON_PRETTY_PRINT+JSON_UNESCAPED_UNICODE);
          echo $json;
      }
    }
  }
  else {
    echo " login. ";
  }
 
 
?>
 
 
 
<?php
$android = strpos($_SERVER['HTTP_USER_AGENT'], "Android");
 
if (!$android){
?>
 
<html>
   <body>
 
      <form action="<?php $_PHP_SELF ?>" method="POST">
         ID: <input type = "text" name = "userID" />
         PASSWORD: <input type = "text" name = "userPassword" />
         <input type = "submit" />
      </form>
 
   </body>
</html>
<?php
}
 
 
?>

SELECT * FROM user WHERE userID='$userID' AND userPassword=SHA1('$userPassword')이라는 query를 날려 user 테이블중 입력한 아이디와 비밀번호가 같은 경우를 찾아 있으면 회원정보를을 띄우는 php코드를 작성하였다.

 

 

 

웹브라우저에 http://localhost:포트번호/Login.php 실행하면 이렇게 뜬다.

 

 

로그인을 해보면 이렇게 정보를 가져온다.

 

 

이제 안드로이드로 옮겨보자.

 

 

먼저 레이아웃을 작성해준다.

activity_login.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?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:background="#FFFFFF">
 
    <TextView
        android:id="@+id/loginText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="100dp"
        android:gravity="center"
        android:text="LOG-IN"
 
 
 
        >
 
    </TextView>
 
    <ImageView
        android:id="@+id/loginImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:background="@null"
        android:src="@drawable/ic_person_black_24dp"
        android:layout_marginBottom="16dp"
        ></ImageView>
 
    <EditText
        android:id="@+id/et_id"
        android:layout_width="match_parent"
        android:hint="아이디를 입력하세요."
        android:layout_height="50dp"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="16dp"
 
        >
    </EditText>
    <EditText
        android:id="@+id/et_pass"
        android:layout_width="match_parent"
        android:hint="비밀번호를 입력하세요."
       android:layout_height="50dp"
        android:layout_marginBottom="16dp"
 
        >
    </EditText>
 
    <Button
        android:id="@+id/btn_login"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="Log-in"
        android:layout_marginBottom="16dp"
        >
 
    </Button>
 
    <CheckBox
        android:id="@+id/rememberCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="아이디 저장"
        android:layout_gravity="center"
        android:layout_marginBottom="16dp"
        >
    </CheckBox>
 
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="10"
        >
 
        <TextView
            android:id="@+id/forgotText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_weight="5"
            android:text="Forgot Id/Pw?"
            >
        </TextView>
        <Button
            android:id="@+id/btn_register"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_weight="5"
            android:text="join us"
            >
        </Button>
    </LinearLayout>
    <ListView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="24"
        android:id="@+id/listView_main_list"/>
 
    <TextView
        android:id="@+id/textView_main_result"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0" />
</LinearLayout>

 

 

Login.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package com.example.cafemoa;
 
 
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
 
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
 
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
 
 
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 
import java.io.BufferedReader;
 
import java.io.InputStream;
import java.io.InputStreamReader;
 
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
 
 
public class LoginActivity extends AppCompatActivity {
 
    private static String TAG = "phplogin";
 
    private static final String TAG_JSON = "user";
    private static final String TAG_ID = "userID";
    private static final String TAG_PASS = "userPassword";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_PHONE = "phoneNumber";
    private static final String TAG_SORT = "userSort";
 
    private TextView mTextViewResult;
    ArrayList<HashMap<StringString>> mArrayList;
    ListView mListViewList;
    private EditText mEditTextID, mEditTextPass;
    Button btn_login, btn_register;
    private String mJsonString;
    private   AlertDialog dialog;
 
    String loginSort;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
 
        TextView loginText = (TextView) findViewById(R.id.loginText);
        ImageView loginImage = (ImageView) findViewById(R.id.loginImage);
        CheckBox rememberCheckBox = (CheckBox) findViewById(R.id.rememberCheckBox);
        TextView forgotText = (TextView) findViewById(R.id.forgotText);
 
        mTextViewResult = (TextView)findViewById(R.id.textView_main_result);
        mListViewList = (ListView) findViewById(R.id.listView_main_list);
        mEditTextID = (EditText) findViewById(R.id.et_id);
        mEditTextPass = (EditText) findViewById(R.id.et_pass);
 
       mEditTextPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
 
        btn_register = findViewById(R.id.btn_register);
        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
                startActivity(intent);
            }
        });
 
 
        btn_login = findViewById(R.id.btn_login);
        btn_login.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
 
                mArrayList.clear();
 
 
                GetData task = new GetData();
                task.execute( mEditTextID.getText().toString(), mEditTextPass.getText().toString());
 
            }
        });
 
 
        mArrayList = new ArrayList<>();
 
    }
 
    private class GetData extends AsyncTask<String, Void, String>{
 
        ProgressDialog progressDialog;
        String errorString = null;
 
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
 
            progressDialog = ProgressDialog.show(LoginActivity.this,
                    "Please Wait"nulltruetrue);
        }
 
 
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
 
            progressDialog.dismiss();
            mTextViewResult.setText(result);
            Log.d(TAG, "response - " + result);
 
            if (result == null){
 
                mTextViewResult.setText(errorString);
            }
            else {
 
                mJsonString = result;
                showResult();
            }
        }
 
 
        @Override
        protected String doInBackground(String... params) {
 
            String userID = (String)params[0];
            String userPassword = (String)params[1];
 
            String serverURL = "http://203.237.179.120:7003/query.php";
            String postParameters = "userID=" + userID + "&userPassword=" + userPassword ;
 
 
            try {
 
                URL url = new URL(serverURL);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
 
 
                httpURLConnection.setReadTimeout(5000);
                httpURLConnection.setConnectTimeout(5000);
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.connect();
 
 
                OutputStream outputStream = httpURLConnection.getOutputStream();
                outputStream.write(postParameters.getBytes("UTF-8"));
                outputStream.flush();
                outputStream.close();
 
 
                int responseStatusCode = httpURLConnection.getResponseCode();
                Log.d(TAG, "POST response code - " + responseStatusCode);
 
                InputStream inputStream;
                if(responseStatusCode == HttpURLConnection.HTTP_OK) {
                    inputStream = httpURLConnection.getInputStream();
                }
                else{
                    inputStream = httpURLConnection.getErrorStream();
                }
 
 
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
 
                StringBuilder sb = new StringBuilder();
                String line;
 
                while((line = bufferedReader.readLine()) != null){
                    sb.append(line);
                }
 
 
                bufferedReader.close();
 
 
                return sb.toString();
 
 
            } catch (Exception e) {
 
                Log.d(TAG, "InsertData: Error ", e);
 
                return new String("Error: " + e.getMessage());
            }
 
        }
    }
 
    private void showResult(){
 
        try {
            JSONObject jsonObject = new JSONObject(mJsonString);
            JSONArray jsonArray = jsonObject.getJSONArray(TAG_JSON);
 
            for (int i = 0; i < jsonArray.length(); i++) {
 
                JSONObject item = jsonArray.getJSONObject(i);
 
                String userID = item.getString(TAG_ID);
                String userPassword = item.getString(TAG_PASS);
                String email = item.getString(TAG_EMAIL);
                String phoneNumber = item.getString(TAG_PHONE);
                final String userSort = item.getString(TAG_SORT);
 
                HashMap<String,String> hashMap = new HashMap<>();
 
                hashMap.put(TAG_ID, userID);
                hashMap.put(TAG_PASS, userPassword);
                hashMap.put(TAG_EMAIL, email);
                hashMap.put(TAG_PHONE, phoneNumber);
                hashMap.put(TAG_SORT, userSort);
 
                mArrayList.add(hashMap);
 
                Intent intent = new Intent(LoginActivity.this, Home2Activity.class);
                AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
                dialog = builder.setMessage("Login.")
                        .setNegativeButton("Success"new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if(userSort.equals("2")) {
                                    Intent intent = new Intent(LoginActivity.this, Home2Activity.class);
                                intent.putExtra("loginID", mEditTextID.getText().toString());
                                intent.putExtra("loginSort", userSort);
                                startActivity(intent);
                            }
                                else if(userSort.equals("1")) {
                                    Intent intent = new Intent(LoginActivity.this, Home3Activity.class);
                                    intent.putExtra("loginID", mEditTextID.getText().toString());
                                    intent.putExtra("loginSort", userSort);
                                    startActivity(intent);
                                }
                            }
                        })
 
                        .create();
                dialog.show();
 
 
                return;
            }
 
 
            ListAdapter adapter = new SimpleAdapter(
                    LoginActivity.this, mArrayList, R.layout.user_list,
                    new String[]{TAG_ID,TAG_PASS,TAG_EMAIL,TAG_PHONE,TAG_SORT},
                    new int[]{R.id.textView_list_id, R.id.textView_list_pass, R.id.textView_list_email,R.id.textView_list_phone,R.id.textView_list_sort}
            );
mListviewList.setAdapter(adapter);
} catch (JSONException e) {
Log.d(TAG, "showResult: ", e);
}
 
}
 
 
 

 

 

 

결과