Notice
Recent Posts
Recent Comments
Today
Total
04-19 00:01
Archives
관리 메뉴

Jeongchul Kim

웹서버 PHP MySQL 연동 안드로이드 통신 [4] 안드로이드 앱 본문

Android

웹서버 PHP MySQL 연동 안드로이드 통신 [4] 안드로이드 앱

김 정출 2016. 2. 15. 23:36



웹서버 PHP MySQL 연동 안드로이드 통신

[4] 안드로이드 앱


본 프로젝트는 웹 호스팅으로 부터 호스팅 서비스를 구매하고 PHP 파일을 생성하며, 호스팅 서비스에 MySQL를 이용하여

APP과 데이터 통신 및 파일 저장하는 것을 목표으로 한다.



이전 포스팅 메뉴

웹서버 PHP MySQL 연동 안드로이드 통신 [1] 웹 호스팅 신청

웹서버 PHP MySQL 연동 안드로이드 통신 [2] MySQL

웹서버 PHP MySQL 연동 안드로이드 통신 [3] PHP



4. 안드로이드 앱 Android App


안드로이드와 PHP 통신을 통해 MySQL에 저장하는 법을 포스트하겠습니다.


안드로이드 앱에서는 Java 파일 2개과 XML 파일 1개가 필요합니다.


DB_Manager.java , SignUpUserInformationFragment.java ,

fragment_signup_user_information.xml


우선 DB_Manager 부터 보겠습니다.

DB_Manager.java

첫 번째 포스트 3번에서 생성한 signup_user_information.php을 가리키는 주소를 담은 문자열이 있어야 합니다.

웹서버 PHP MySQL 연동 안드로이드 통신 [3] PHP

public class DB_Manager {

private String urlPath;

// 회원 가입의 정보를 MySQL에 저장할 php를 포함한 도메인 주소를 입력한다.

private final String signup_user_information_UrlPath =

"http://smartwheel.kr/user_signup/signup_user_information.php";


/*-- DB user에 접속하여 회원 가입에 관한 db 저장할 데이터 */

private String user_id;

private String user_name;

private String user_password;

private String user_phone;

private String user_email;


함수 인자로 입력받은 유저의 아이디와 이름과 비밀번호, 핸드폰 번호, 이메일을 넘겨 받습니다.

이후에 SignupUserInformation() 클래스를 실행합니다.


/* 회원가입 부분 */

/* -- 유저에게 id,password,핸드폰,이메일을 입력받는다. */

public ArrayList<String> signup_user_information(String user_id, String user_name, String user_password, String user_phone, String user_email) {

  urlPath = signup_user_information_UrlPath;

  this.user_id = user_id;

  this.user_name = user_name;

  this.user_password = user_password;

  this.user_phone = user_phone;

  this.user_email = user_email;

  try {

      results = new SignupUserInformation().execute().get();

  } catch ( InterruptedException e ) {

      e.printStackTrace();

  } catch ( ExecutionException e ) {

      e.printStackTrace();

  }

  return results;

}


문자열로 이루어진 데이터를 서버에 POST 방식으로 전송합니다.

HttpURLConnection 방식을 이용해 연결을 하고 OutputStream, BufferedReader를 통해 보낸다.

/* 회원가입 부분 */

/* -- 문자열로 이루어진 데이터를 서버에 POST 방식으로 전송한다 */

class SignupUserInformation extends AsyncTask<Void, Void, ArrayList<String>> {

  @Override

  protected ArrayList<String> doInBackground(Void... voids) {

      // TODO Auto-generated method

      try {

          URL url = new URL(urlPath); // Set url

          HttpURLConnection con = (HttpURLConnection) url.openConnection();

          con.setDoInput(true); // Available Write

          con.setDoOutput(true); // Available Read

          con.setUseCaches(false); // No cash

          con.setRequestMethod("POST");


          String param = "user_id="+user_id+"&user_name="+user_name+"&user_password="+user_password+"&user_phone="+user_phone+

                  "&user_email="+user_email;


          OutputStream outputStream = con.getOutputStream();

          outputStream.write(param.getBytes());

          outputStream.flush();

          outputStream.close();


          BufferedReader rd = null;

          rd = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));

          String line = null;

          while((line = rd.readLine()) != null) {

              Log.d("BufferedReader:", line);

          }

      } catch (UnsupportedEncodingException e) {

          e.printStackTrace();

      } catch (IOException e) {

          e.printStackTrace();

      }

      return null;

  }

  protected void onPostExecute(ArrayList<String> qResults) {

      super.onPostExecute(qResults);

  }

}


SignUpUserInformationFragment.java

public class SignUpUserInformationFragment extends Fragment implements View.OnClickListener{


  public int view_id = 0;

  public String symbolvalue;


  private DB_Manager db_manager;

  private DB_Define db_define;

  private ArrayList<String> results;


  private EditText et_id;

  private EditText et_name;

  private EditText et_passWord;

  private EditText et_passWordAgain;

  private EditText et_phone;

  private EditText et_email;


  public SignUpUserInformationFragment() {


  }


  public View onCreateView(LayoutInflater inflater, ViewGroup container,

                           Bundle savedInstanceState) {


      View rootView = inflater.inflate(R.layout.fragment_signup_user_information, container, false);

      et_id = (EditText)rootView.findViewById(R.id.user_id);

      et_name = (EditText)rootView.findViewById(R.id.user_name);

      et_passWord = (EditText)rootView.findViewById(R.id.user_passWord);

      et_passWordAgain = (EditText) rootView.findViewById(R.id.user_passWordAgain);

      et_phone = (EditText) rootView.findViewById(R.id.user_Phone);

      et_email = (EditText) rootView.findViewById(R.id.user_Email);

      Button btn_agreeJoin = (Button) rootView.findViewById(R.id.btn_agreeJoin);


      et_id.setOnClickListener(this);

      et_name.setOnClickListener(this);

      et_passWord.setOnClickListener(this);

      et_passWordAgain.setOnClickListener(this);

      et_phone.setOnClickListener(this);

      et_email.setOnClickListener(this);

      btn_agreeJoin.setOnClickListener(this);


      db_manager = new DB_Manager();


      results = new ArrayList<String>();


      return rootView;

  }


  @Override

  public void onClick(View view) {


      //*밑 4줄은 비밀번호와 비밀번호 확인을 해서 서로 일치한지 비교해주기 위해 둘 모두 String으로 변환하여 비교해준다.

      String a = et_passWord.getText().toString();

      String b = et_passWordAgain.getText().toString();


      //signup_id에 아이디들을 스위치문으로 받아와준다.

      switch (view.getId()) {

          case R.id.user_id:

              popup(R.id.user_id, "아이디입력");

              break;

          case R.id.user_name:

              popup(R.id.user_name, "이름 입력");

              break;

          case R.id.user_Email:

              popup(R.id.user_Email, "이메일을 입력 해주세요");

              break;

          case R.id.user_Phone:

              // 핸드폰 번호 따오는 알고리즘

              TelephonyManager systemService = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);

              String PhoneNumber = systemService.getLine1Number();

              PhoneNumber = PhoneNumber.substring(PhoneNumber.length() - 10, PhoneNumber.length());

              PhoneNumber = "0" + PhoneNumber;

              // 얻어온 전화번호에 자동으로 하이픈(-) 추가

              //PhoneNumber = PhoneNumberUtils.formatNumber(PhoneNumber);

              et_phone.setText(PhoneNumber);

              // 해당 에디트텍스트를 사용자입력 금지시킴

              et_phone.setEnabled(false);

              break;

          case R.id.btn_agreeJoin:

              FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();

              /*

              if (et_id.length() < 1) {

                  Toast.makeText(getActivity(), "아이디가 공백입니다!", Toast.LENGTH_SHORT).show();

                  break;

              }

              if (et_name.length() < 1) {

                  Toast.makeText(getActivity(), "이름이 공백입니다!", Toast.LENGTH_SHORT).show();

                  break;

              }

              if (et_phone.length() < 1) {

                  Toast.makeText(getActivity(), "전화번호가 공백입니다!", Toast.LENGTH_SHORT).show();

                  break;

              }

              if (et_email.length() < 1) {

                  Toast.makeText(getActivity(), "메일이 공백입니다!", Toast.LENGTH_SHORT).show();

                  break;

              }

              */

              if(a.length()<1)

                  Toast.makeText(getActivity(), "비밀번호가 공백입니다!", Toast.LENGTH_SHORT).show();

              else if (!a.equals(b))

                  Toast.makeText(getActivity(), "비밀번호가 일치하지 않습니다", Toast.LENGTH_SHORT).show();

              else {

                  String user_id = et_id.getText().toString();

                  String user_name = et_name.getText().toString();

                  String user_password = et_passWord.getText().toString();

                  String user_phone = et_phone.getText().toString();

                  String user_email = et_email.getText().toString();

       dbmanger.signup_user_information(user_id, user_name, user_password, user_phone, user_email);

                  Intent mainIntent = new Intent(getActivity(), SignUpPhotoActivity.class);

                  startActivity(mainIntent);

              }

              break;

      }


  }

  //밑에는 popup을 만들어주는 함수이다.

  public void popup(final int id, String title) {

      view_id = id;

      Context mContext = getActivity().getApplicationContext();

      LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);


      //R.layout.dialog는 xml 파일명이고  R.id.popup은 보여줄 레이아웃 아이디

      final View layout = inflater.inflate(R.layout.popup_signup, (ViewGroup) getActivity().findViewById(R.id.popupId));

      final AlertDialog.Builder aDialog = new AlertDialog.Builder(getActivity());


      aDialog.setTitle(title); //타이틀바 제목

      aDialog.setView(layout); //dialog.xml 파일을 뷰로 셋팅

      aDialog.setNegativeButton("닫기", new DialogInterface.OnClickListener() {

          public void onClick(DialogInterface dialog, int which) {

          }

      });


      //밑에는 팝업창에서 정보들을 입력한 후 확인을 누르면 EditText자리에 그대로 String으로 나타내주기 위한 함수이다.

      aDialog.setPositiveButton("확인", new DialogInterface.OnClickListener() {

                  public void onClick(DialogInterface dialog, int which) {

                      if (view_id == R.id.user_id) {

                          EditText edit = (EditText) ((AlertDialog) dialog).findViewById(R.id.enterId); //팝업창에 EditText부분에 아이디

                          symbolvalue = edit.getText().toString();

                          /**

                              읿력받은 id와 서버의 저장되어 있는 id를 조회하여 중복되는 지 여부를 검사한다.

                          */

                          results = db_manager.inquiryUser(symbolvalue, "");

                          String[] result_query = results.get(0).split(":"); // Split input string

                          String isExistId = result_query[4];

                          String isExistPw = result_query[6];

                          Log.d("isExistID:", isExistId);

                          Log.d("isExistPassword:", isExistPw);

                          if (isExistId.equals(db_define.IS_EXIST_ID)) { // If id existed in db and correspond

                              symbolvalue = "";

                              Toast.makeText(getActivity(), "아이디가 중복입니다", Toast.LENGTH_SHORT).show();

                          }

                          TextView text = (TextView) getActivity().findViewById(id);//각 항목에 대한 id를 받아온다.

                          edit.requestFocus();

                          text.setText(symbolvalue);

                      } else {

                          EditText edit = (EditText) ((AlertDialog) dialog).findViewById(R.id.enterId); //팝업창에 EditText부분에 아이디

                          symbolvalue = edit.getText().toString();

                          edit.requestFocus();

                          TextView text = (TextView) getActivity().findViewById(id);//각 항목에 대한 id를 받아온다.

                          text.setText(symbolvalue);

                      


                  }

              }


      );

          //그냥 닫기버튼을 위한 부분

          //팝업창 생성

          AlertDialog ad = aDialog.create();

          ad.show();//보여줌!

      }

  }


fragment_signup_user_information.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:focusableInTouchMode="true"

  android:focusable="true">

  <LinearLayout

      android:layout_width="match_parent"

      android:layout_height="match_parent"

      android:orientation="vertical">

      <TextView

          android:layout_width="match_parent"

          android:layout_height="wrap_content"

          android:text="회원가입"

          android:layout_marginTop="20dp"

          android:textSize="40sp"

          android:gravity="center_horizontal"

          android:textColor="@color/color_MAIN" />

      <LinearLayout

          android:layout_width="match_parent"

          android:layout_height="50dp"

          android:layout_marginLeft="30dp">

          <TextView

              android:layout_width="100dp"

              android:layout_height="50dp"

              android:text="아이디 : "

              android:textSize="13sp"/>

          <EditText

              android:id="@+id/user_id"

              android:layout_width="200dp"

              android:layout_height="50dp"

              android:hint=""

              android:focusable="false"

              android:focusableInTouchMode="false"

              android:cursorVisible="false"

              android:background="@drawable/apptheme_textfield_activated_holo_light"

              />

      </LinearLayout>

      <LinearLayout

          android:layout_width="match_parent"

          android:layout_height="50dp"

          android:layout_marginLeft="30dp">

          <TextView

              android:layout_width="100dp"

              android:layout_height="50dp"

              android:text="이름 : "

              android:textSize="13sp"/>

          <EditText

              android:id="@+id/user_name"

              android:layout_width="200dp"

              android:layout_height="50dp"

              android:hint=""

              android:focusable="false"

              android:focusableInTouchMode="false"

              android:cursorVisible="false"

              android:background="@drawable/apptheme_textfield_activated_holo_light"/>

      </LinearLayout>

      <LinearLayout

          android:layout_width="match_parent"

          android:layout_height="50dp"

          android:layout_marginLeft="30dp">

          <TextView

              android:layout_width="100dp"

              android:layout_height="50dp"

              android:text="비밀번호 : "

              android:textSize="13sp"/>

          <EditText

              android:id="@+id/user_passWord"

              android:layout_width="200dp"

              android:layout_height="50dp"

              android:inputType="textPassword"

              android:hint=""

              android:background="@drawable/apptheme_textfield_activated_holo_light"/>

      </LinearLayout>

      <LinearLayout

          android:layout_width="match_parent"

          android:layout_height="50dp"

          android:layout_marginLeft="30dp">

          <TextView

              android:layout_width="100dp"

              android:layout_height="50dp"

              android:text="비밀번호 확인 : "

              android:textSize="13sp"/>

          <EditText

              android:id="@+id/user_passWordAgain"

              android:layout_width="200dp"

              android:layout_height="50dp"

              android:inputType="textPassword"

              android:hint=""

              android:background="@drawable/apptheme_textfield_activated_holo_light"/>

      </LinearLayout>

      <LinearLayout

          android:layout_width="match_parent"

          android:layout_height="50dp"

          android:layout_marginLeft="30dp">

          <TextView

              android:layout_width="100dp"

              android:layout_height="50dp"

              android:text="핸드폰번호 : "

              android:textSize="13sp"/>

          <EditText

              android:id="@+id/user_Phone"

              android:layout_width="200dp"

              android:layout_height="50dp"

              android:focusable="false"

              android:focusableInTouchMode="false"

              android:cursorVisible="false"

              android:background="@drawable/apptheme_textfield_activated_holo_light"/>


      </LinearLayout>

      <LinearLayout

          android:layout_width="match_parent"

          android:layout_height="50dp"

          android:layout_marginLeft="30dp">

          <TextView

              android:layout_width="100dp"

              android:layout_height="50dp"

              android:text="이메일 : "

              android:textSize="13sp" />

          <EditText

              android:id="@+id/user_Email"

              android:layout_width="200dp"

              android:layout_height="50dp"

              android:hint=""

              android:focusable="false"

              android:focusableInTouchMode="false"

              android:cursorVisible="false"

              android:background="@drawable/apptheme_textfield_activated_holo_light"

              />

      </LinearLayout>


      <CheckBox

          android:id="@+id/personalInfo"

          android:layout_width="300dp"

          android:layout_height="50dp"

          android:layout_marginLeft="30dp"

          android:text="Do you agree to the Terms of use and privacy?"/>

      <Button

          android:id="@+id/btn_agreeJoin"

          android:layout_width="300dp"

          android:layout_height="50dp"

          android:layout_marginLeft="30dp"

          android:text="다음"

          android:textSize="15sp"

          android:onClick="onClick"

          android:background="@color/color_button"/>

  </LinearLayout>

</LinearLayout>



Fragment로 구성했기때문에 Activity가 필요합니다.

activity_signup.xml

<LinearLayout

  xmlns:android="http://schemas.android.com/apk/res/android"

  android:layout_height="match_parent"

  android:layout_width="match_parent"

  android:layout_gravity="center">

  <FrameLayout

      android:id="@+id/frame_container_signup"

      android:layout_width="match_parent"

      android:layout_height="match_parent" />

</LinearLayout>


SignUpActivity.java

package sincere.kimjungchul.smartwheel.SignUp;



import android.os.Bundle;

import android.support.v4.app.FragmentActivity;

import android.support.v4.app.FragmentTransaction;


import sincere.kimjungchul.smartwheel.R;



/**

* Created by user on 2015-08-01.

*/

public class SignUpActivity extends FragmentActivity{

  @Override

  protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      setContentView(R.layout.activity_signup);


      FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

      ft.replace(R.id.frame_container_signup, new SignUpUserInformationFragment());

      ft.commit();


  }

}


AndroidManifest.xml

user-permission 추가해야 됩니다.

<uses-permission android:name="android.permission.INTERNET"/>

<uses-permission android:name="android.permission.READ_PHONE_STATE" />


<activity

  android:name=".SignUp.SignUpActivity"

  android:label="@string/app_name" >

</activity>


추가하고 실행하시면됩니다.


MySQL phpMyAdmin에 user_app 테이블을 보면 값이 들어와있는 것을 확인할 수 있습니다.






Comments