[1.안드로이드 - AndroidManifest.xml]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.helloworld">
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".subActivity"
            android:label="@string/login_page"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>
 
 

[2.안드로이드 - MainActivity.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
package com.example.helloworld;
 
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        Button button = (Button) findViewById(R.id.login_btn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), subActivity.class);
                startActivity(intent);
            }
        });
    }
}
 
 

[3.안드로이드 - subActivity]

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
package com.example.helloworld;
 
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
 
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.concurrent.ExecutionException;
 
 
public class subActivity extends AppCompatActivity {
    private EditText idEditText;
    private EditText pwdEditText;
    private String idText,pwdText;
    private String mJsonString;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub);
 
        idEditText = (EditText) findViewById(R.id.input_id);
        pwdEditText = (EditText) findViewById(R.id.input_pwd);
 
        idEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int id, KeyEvent event) {
                if(id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL){
                    return true;
                }
                return false;
            }
        });
 
        pwdEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int pwd, KeyEvent event) {
                if(pwd == EditorInfo.IME_ACTION_DONE || pwd == EditorInfo.IME_NULL){
                    // 함수 실행
                    return true;
                }
                return false;
            }
        });
 
        Button login_btn = (Button) findViewById(R.id.btn_login);
        Button sign_up_btn = (Button) findViewById(R.id.btn_sign_up);
 
        login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                idText = idEditText.getText().toString();
                pwdText = pwdEditText.getText().toString();
                if(idText != "" && pwdText != ""){
                    // AsyncTask 를 통해 HttpURLConnection 수행.
                    try{
                        loginTask task = new loginTask();
                        task.execute("http://아이피/android_server/connectDB.php","m_id",idText,"m_pwd",pwdText);
                        String callBackValue = task.get();
 
                        AlertDialog.Builder builder = new AlertDialog.Builder(subActivity.this);
 
                        // fail
                        if(callBackValue.isEmpty() || callBackValue.equals(""|| callBackValue == null || callBackValue.contains("Error")) {
                            builder.setTitle("로그인 실패").setMessage("입력한 회원 정보가 없습니다.");
                            AlertDialog alertDialog = builder.create();
                            alertDialog.show();
                        }
                        // success
                        else {
                            System.out.println(callBackValue);
                            try{
                                JSONObject jsonObject = new JSONObject(callBackValue);
                                JSONArray jsonArray = jsonObject.getJSONArray("member");
 
                                for(int i = 0 ; i<jsonArray.length(); i++){
                                    JSONObject item = jsonArray.getJSONObject(i);
 
                                    String id = item.getString("m_id");
                                    String password = item.getString("m_pwd");
                                    String phone = item.getString("m_phone");
                                    String address = item.getString("m_address");
                                    System.out.println("id : "+ id);
                                    System.out.println("password : "+ password);
                                    System.out.println("phone : "+ phone);
                                    System.out.println("address : "+ address);
                                }
                            }catch (JSONException e) {
                                System.out.println("json_error : "+ e);
                            }
                            /*
                            if(callBackValue == "1"){
                                builder.setTitle("로그인 성공").setMessage("메인 페이지로 이동합니다.");
                                AlertDialog alertDialog = builder.create();
                                alertDialog.show();
                            }else{
                                builder.setTitle("로그인 실패").setMessage("입력한 회원 정보가 없습니다.");
                                AlertDialog alertDialog = builder.create();
                                alertDialog.show();
                            }
                            */
                            // TODO : callBackValue 를 이용해서 코드기술
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
 
                }
                /*
                // 알림창
                AlertDialog.Builder builder = new AlertDialog.Builder(subActivity.this);
                builder.setTitle("알림창").setMessage("로그인 버튼 클릭");
 
                builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Toast.makeText(getApplicationContext(),"Ok click", Toast.LENGTH_SHORT).show();
                    }
                });
 
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Toast.makeText(getApplicationContext(),"Cancel click", Toast.LENGTH_SHORT).show();
                    }
                });
 
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
                */
            }
        });
 
        sign_up_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 알림창
                AlertDialog.Builder builder = new AlertDialog.Builder(subActivity.this);
                builder.setTitle("알림창").setMessage("로그인 버튼 클릭");
 
                builder.setPositiveButton("Ok"new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(),"OK click", Toast.LENGTH_SHORT).show();
                    }
                });
 
                builder.setNegativeButton("Cancel"new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(),"Cancel click", Toast.LENGTH_SHORT).show();
                    }
                });
 
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
            }
        });
    }
    private class loginTask extends AsyncTask<String,String,String>{
        @Override
        protected String doInBackground(String... params) {
            String serverURL = (String) params[0];
 
            String key = (String) params[1];
            String value = (String) params[2];
 
            String key2 = (String) params[3];
            String value2 = (String) params[4];
            String postParameters = key + "=" + value + "&" + key2 + "=" + value2;
            try{
                URL url = new URL(serverURL); // 주소가 저장된 변수를 이곳에 입력합니다.
 
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setReadTimeout(5000); //5초안에 응답이 오지 않으면 예외가 발생합니다.
                httpURLConnection.setConnectTimeout(5000); //5초안에 연결이 안되면 예외가 발생합니다.
                httpURLConnection.setRequestMethod("POST"); //요청 방식을 POST로 합니다.
                httpURLConnection.connect();
 
                OutputStream outputStream = httpURLConnection.getOutputStream();
                outputStream.write(postParameters.getBytes("UTF-8")); //전송할 데이터가 저장된 변수를 이곳에 입력합니다.
                outputStream.flush();
                outputStream.close();
 
                // 응답을 읽습니다.
 
                int responseStatusCode = httpURLConnection.getResponseCode();
                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 = null;
 
                while ((line = bufferedReader.readLine()) != null) {
                    sb.append(line);
                }
 
                bufferedReader.close();
 
                return sb.toString();
 
            } catch (Exception e) {
                return new String("Error: " + e.getMessage());
            }
        }
 
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
 
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //System.out.println("결과값 : "+ s);
            /*
            mJsonString = s;
            showResult();
            */
        }
 
    }
 
}
 
 
 

[4.안드로이드 - activity_main.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
<?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:weightSum="9">
    <Button
        android:id="@+id/login_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="로그인"
        android:textColor="#ffffff"
        android:textSize="40sp"
        android:background="#0066ff"
        android:gravity="center"
        android:layout_weight="3"/>
    <Button
        android:id="@+id/prevent_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="상품 예약"
        android:textColor="#ffffff"
        android:textSize="40sp"
        android:background="#ffcc33"
        android:gravity="center"
        android:layout_weight="3"/>
    <Button
        android:id="@+id/question_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="상담 문의"
        android:textColor="#ffffff"
        android:textSize="40sp"
        android:background="#66cc00"
        android:gravity="center"
        android:layout_weight="3"/>
</LinearLayout>
 
 
 

[5.안드로이드 - activity_sub.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
<LinearLayout 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"
    android:gravity="center_horizontal">
 
    <LinearLayout
        android:id="@+id/email_login_form"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginRight="20sp"
        android:layout_marginLeft="20sp"
        android:gravity="center"
        android:orientation="vertical">
 
        <EditText
            android:id="@+id/input_id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/user_id"
            android:inputType="textEmailAddress"
            android:maxLines="1"
            android:singleLine="true" />
 
        <EditText
            android:id="@+id/input_pwd"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/user_pwd"
            android:inputType="textPassword"
            android:maxLines="1"
            android:singleLine="true" />
 
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
 
            <Button
                android:id="@+id/btn_login"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:layout_weight="1"
                android:text="@string/action_login"
                android:textStyle="bold" />
 
            <Button
                android:id="@+id/btn_sign_up"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:layout_weight="1"
                android:text="@string/action_sign_up"
                android:textStyle="bold" />
        </LinearLayout>
 
    </LinearLayout>
</LinearLayout>
 
 

[6.conectDB.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
<?php
 
    header('content-type: text/html; charset=utf-8'); 
    //MYSQL 접속 정보
    $db = mysqli_connect("서버주소","디비사용자","디비 비번","디비 이름");
    if(!$db){
        die("Error ".mysqli_connect_error());
    }
    //한글
    mysqli_set_charset($db'UTF8');
 
    $id = $_POST['m_id'];
    $pwd = $_POST['m_pwd'];
    $result_arr = array();
    $result = $db->query("SELECT * FROM member WHERE m_id='$id' AND m_pwd = '$pwd'");
    $num = $result->num_rows;
    if($num > 0){
        $low = $result->fetch_assoc();
        array_push($result_arr,$low);
        header('Content-Type: application/json; charset=utf8');
        echo json_encode(array("member"=>$result_arr));
    }else{
        echo false;
    }
 
    mysqli_close($db);
?>
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

[7.결과 화면]

'안드로이드' 카테고리의 다른 글

안드로이드 웹뷰 사용하기  (0) 2019.06.04
안드로이드 REST API 사용법  (0) 2019.06.03

+ Recent posts