'프로그래밍'에 해당되는 글 534건


실행화면
1. 로그인을 합니다.


2. COURSE LIST 클릭


3. 다음과 같은 레이아웃을 구성하는 것이 이번 강의 목표



res/layout/fragment_course.xml

COUSE LIST를 눌렀을 때 보여주는 xml 파일입니다.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.kch.registration_v9.CourseFragment"
    android:orientation="vertical"

    >

    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/courseUniversityGroup"
        android:layout_gravity="center_horizontal"
        android:gravity="center_horizontal"
        android:orientation="horizontal"
        android:layout_marginTop="10dp"
        >

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="undergraduate"
            android:id="@+id/university"
            />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="graduate"
            android:id="@+id/graduate"
            />

    </RadioGroup>

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="10dp"
            android:layout_gravity="center_horizontal"
            android:paddingRight="10dp">

            <Spinner
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginLeft="10dp"
                android:id="@+id/yearSpinner"></Spinner>

            <Spinner
                android:layout_width="100dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginLeft="10dp"
                android:id="@+id/termSpinner"></Spinner>

            <Spinner
                android:layout_width="140dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginLeft="10dp"
                android:id="@+id/areaSpinner"></Spinner>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="10dp"
            android:layout_gravity="center"
            android:gravity="center"
            android:paddingRight="10dp"
            >

            <Spinner
                android:layout_width="230dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginLeft="10dp"
                android:id="@+id/majorSpinner"></Spinner>

            <Button
                android:layout_width="80dp"
                android:layout_height="40dp"
                android:textSize="15dp"
                android:textStyle="bold"
                android:textColor="#ffffff"
                android:background="@color/colorWarning"
                android:text="Course Search"
                android:layout_gravity="center"
                android:id="@+id/searchButton"
                android:layout_marginLeft="10dp"/>


        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="10dp"
            android:background="#ffffff"
            >

            <ListView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/courseListView"
                android:dividerHeight="10dp"
                android:divider="#ffffff"
                ></ListView>



        </LinearLayout>


</LinearLayout>

res/values/arrays.xml

Spinner를 클릭했을때 넣어줄 데이터를 여기에 정의 해줍니다.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="major">
        <item>정보통신공학</item>
        <item>기계공학</item>
        <item>화학공학과</item>
    </string-array>
    <string-array name="term">
        <item>1학기</item>
        <item>여름학기</item>
        <item>2학기</item>
        <item>계절학기</item>
    </string-array>
    <string-array name="graduateArea">
        <item>전공선택과목</item>
        <item>교양과목</item>
        <item>전공필수과목</item>
    </string-array>
    <string-array name="universityArea">
        <item>전공필수과목</item>
        <item>전공선택과목</item>
    </string-array>
    <string-array name="year">
        <item>2018년도</item>
        <item>2019년도</item>
        <item>2020년도</item>
        <item>2021년도</item>
        <item>2022년도</item>
        <item>2023년도</item>
        <item>2024년도</item>
        <item>2025년도</item>
        <item>2026년도</item>
    </string-array>
</resources>


CourseFragment.java

스피너와 라디오버튼 그룹을 만들고 값을 넣어줍니다.

package com.example.kch.registration_v9;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;


/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link CourseFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link CourseFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class CourseFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public CourseFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment CourseFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static CourseFragment newInstance(String param1, String param2) {
        CourseFragment fragment = new CourseFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    //9강에 추가된 부분
    private ArrayAdapter yearAdapter;
    private Spinner yearSpinner;
    private ArrayAdapter termAdapter;

    private Spinner termSpinner;
    private ArrayAdapter areaAdapter;
    private Spinner areaSpinner;

    private String courseUniversity = "";
    private String courseYear = "";
    private String courseTerm = "";
    private String courseArea = "";


    //9강에 추가된 부분
    //Life Cycle 상 onCreate다음에 onActivityCreated가 실행됨
    //Activity의 모든 View가 만들어지고 난 다음이기 때문에 View를 변경하는 등의 작업을 할 수 있다.

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        final RadioGroup courseUniversityGroup = (RadioGroup)getView().findViewById(R.id.courseUniversityGroup);
        yearSpinner = (Spinner)getView().findViewById(R.id.yearSpinner);
        termSpinner = (Spinner)getView().findViewById(R.id.termSpinner);
        areaSpinner = (Spinner)getView().findViewById(R.id.areaSpinner);

        //라디오 버튼에 따라서 달라짐
        courseUniversityGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                //라디오 버튼 그룹 선언
                RadioButton courseButton = (RadioButton)getView().findViewById(checkedId);

                //현재 라디오 버튼이 눌린 값의 text를 가져옴
                courseUniversity = courseButton.getText().toString();

                //arrays.xml의 내용을 이용해서 단순한 스피너를 만드는 부분
                yearAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.year, android.R.layout.simple_spinner_dropdown_item);
                yearSpinner.setAdapter(yearAdapter);//여기서 스피너뷰에 어댑터패턴을 이용해서 데이터를 연결해줌


                //위와 동일
                termAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.term, android.R.layout.simple_spinner_dropdown_item);
                termSpinner.setAdapter(termAdapter);

                //라디오버튼의 상태에 따라서 학부와 대학원으로 나눔
                if(courseUniversity.equals("undergraduate")){
                    areaAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.universityArea, android.R.layout.simple_spinner_dropdown_item);
                    areaSpinner.setAdapter(areaAdapter);
                }else{
                    areaAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.graduateArea, android.R.layout.simple_spinner_dropdown_item);
                    areaSpinner.setAdapter(areaAdapter);
                }

            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_course, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    /*
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

강의에서 삭제함    */

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}



 MainActivity.java

맨 마지막부분에 메인화면에서 백버튼을 두번 누르면 앱이 종료되게 추가했습니다.


package com.example.kch.registration_v9;

import android.os.AsyncTask;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    //7강때 추가된 부분
    private ListView noticeListView;
    private NoticeListAdapter adapter;
    private List<Notice> noticedList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //7강때 추가된 부분
        noticeListView = (ListView)findViewById(R.id.noticeListView);
        noticedList = new ArrayList<Notice>();
        //8강때 삭제됨
       /* noticedList.add(new Notice("공지사항", "gakari", "2018-09-09"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-10"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-11"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-12"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-13"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-14"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-15"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-16"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-17"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-18"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-19"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-20"));*/
        adapter = new NoticeListAdapter(getApplicationContext(), noticedList);
        noticeListView.setAdapter(adapter);


        final Button courseButton = (Button)findViewById(R.id.courseButton);
        final Button statisticsButton = (Button)findViewById(R.id.statisticsButton);
        final Button scheduleButton = (Button)findViewById(R.id.scheduleButton);
        final LinearLayout notice = (LinearLayout)findViewById(R.id.notice);

        courseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                notice.setVisibility(View.GONE);//공지사항이 안보임
                courseButton.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
                statisticsButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                scheduleButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));

                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.fragment, new CourseFragment());//프래그먼트를 바꿔줌
                fragmentTransaction.commit();
            }
        });

        statisticsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                notice.setVisibility(View.GONE);//공지사항이 안보임
                courseButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                statisticsButton.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
                scheduleButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));

                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.fragment, new StatisticsFragment());//프래그먼트를 바꿔줌
                fragmentTransaction.commit();
            }
        });

        scheduleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                notice.setVisibility(View.GONE);//공지사항이 안보임
                courseButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                statisticsButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                scheduleButton.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));

                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.fragment, new ScheduleFragment());//프래그먼트를 바꿔줌
                fragmentTransaction.commit();
            }
        });

        //8강때 추가된부분
        //AsyncTask 실행 부분
        new BackgroundTask().execute();

    }

    //PHP서버에 접속해서 JSON타입으로 데이터를 가져옴
    class BackgroundTask extends AsyncTask<Void, Void, String>{
        String target;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            target = "http://10.0.2.2:8080/registration/NoticeList.php";

        }

        //실제 데이터를 가져오는 부분임
        @Override
        protected String doInBackground(Void... voids) {
            try{

                URL url = new URL(target);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String temp;//결과 값을 여기에 저장함
                StringBuilder stringBuilder = new StringBuilder();

                //버퍼생성후 한줄씩 가져옴
                while((temp = bufferedReader.readLine()) != null){
                    stringBuilder.append(temp + "\n");
                }

                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();

                return stringBuilder.toString().trim();//결과값이 여기에 리턴되면 이 값이 onPostExcute의 파라미터로 넘어감

            }catch(Exception e){
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        //여기서는 가져온 데이터를 Notice객체에 넣은뒤 리스트뷰 출력을 위한 List객체에 넣어주는 부분
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            try{
                JSONObject jsonObject = new JSONObject(result);
                JSONArray jsonArray = jsonObject.getJSONArray("response");
                int count = 0;
                String noticeContent, noticeName, noticeDate;


                //json타입의 값을 하나씩 빼서 Notice 객체에 저장후 리스트에 추가하는 부분
                while(count < jsonArray.length()){
                    JSONObject object = jsonArray.getJSONObject(count);
                    noticeContent = object.getString("noticeContent");
                    noticeName = object.getString("noticeName");
                    noticeDate = object.getString("noticeDate");
                    Notice notice = new Notice(noticeContent, noticeName, noticeDate);
                    noticedList.add(notice);
                    count++;
                }

            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }


    //9강때 추가된부분 백버튼을 두번 누르면 앱이 종료되게 함.
    private long pressedTime;

    @Override
    public void onBackPressed() {
       // super.onBackPressed();
        //백버튼이 눌리고 1.5초안에 또 눌리면 종료가됨

        if ( pressedTime == 0 ) {
            Toast.makeText(MainActivity.this, " 한 번 더 누르면 종료됩니다." , Toast.LENGTH_LONG).show();
            pressedTime = System.currentTimeMillis();
        }
        else {
            int seconds = (int) (System.currentTimeMillis() - pressedTime);

            if ( seconds > 1500 ) {
                Toast.makeText(MainActivity.this, " 한 번 더 누르면 종료됩니다." , Toast.LENGTH_LONG).show();
                pressedTime = 0 ;
            }
            else {
                super.onBackPressed();//이걸 따라가다보면 결국 finish()를 실행 시키는 부분이 나옴
                //출처 : http://itpangpang.xyz/135
//                finish(); // app 종료 시키기
            }
        }




    }
}










블로그 이미지

가카리

소프트웨어와 하드웨어 프로그래밍, 취업 및 직장생활 전문 블로그

예제 출처 : https://www.inflearn.com/course
예제 소스 : https://github.com/GaKaRi/gakari_android/tree/master/Registration_v8

실행화면




공지사항을 위한 테이블 생성
CREATE TABLE NOTICE (
   noticeContent VARCHAR(1000) NOT NULL,
   noticeName VARCHAR(50) NOT NULL,
   noticeDate DATE NOT NULL
);

테스트용 문자열 삽입
INSERT INTO NOTICE VALUES('NOTICE NUMBER1', 'GAKARI', '2017-01-01’);

mysql 디비 확인






NoticeList.php

<?php
    $con = mysqli_connect('localhost:3307', 'root', 'qwer1234', 'registration');
    //접속후에 테이블 내용 최신순서로 나오게
    $result = mysqli_query($con, "SELECT * FROM NOTICE ORDER BY noticeDate DESC;");
    $response = array();
    while($row = mysqli_fetch_array($result))
      array_push($response, array("noticeContent" => $row[0], "noticeName" => $row[1], "noticeDate" => $row[2]));
   
    //다음과 같이 출력함
    //"response":["noticeContent":"NOTICE NUMBER1","noticeName":"GAKARI","noticeDate":"2017-01-03",
    //"noticeContent":"NOTICE NUMBER1","noticeName":"GAKARI","noticeDate":"2017-01-02",
    //"noticeContent":"NOTICE NUMBER1","noticeName":"GAKARI","noticeDate":"2017-01-01"]
    echo json_encode(array("response" => $response));
   mysqli_close($con);
?>

res/layout/activity_main.xml

layout_marginRight만 수정됩니다.


<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
    tools:context="com.example.kch.registration_v8.MainActivity">
   <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="5dp"
        android:layout_marginRight="8dp"
        >
       <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:id="@+id/courseButton"
        android:text="course list"
        android:textStyle="bold"
        android:textColor="#FFFFFF"
        android:textSize="18dp"
        android:background="@color/colorPrimary"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        />
       <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/scheduleButton"
            android:text="schedule"
            android:textStyle="bold"
            android:textColor="#FFFFFF"
            android:textSize="18dp"
            android:background="@color/colorPrimary"
            android:layout_marginLeft="8dp"
            android:layout_marginTop="8dp"
            />
       <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/statisticsButton"
            android:text="statistics"
            android:textStyle="bold"
            android:textColor="#FFFFFF"
            android:textSize="18dp"
            android:background="@color/colorPrimary"
            android:layout_marginLeft="8dp"
            android:layout_marginTop="8dp"
            />
       </LinearLayout>
       <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
           <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:id="@+id/notice">
               <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    android:orientation="vertical"
                    android:background="@color/colorPrimary"
                    android:layout_marginTop="8dp">
                       <ImageButton
                            android:layout_width="wrap_content"
                            android:layout_height="150dp"
                            android:layout_gravity="center"
                            android:layout_marginTop="5dp"
                            android:src="@drawable/univlogo"
                            android:scaleType="fitCenter"
                            />
                       <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:text="Notice"
                            android:textColor="#ffffff"
                            android:textSize="25dp"
                            android:textStyle="bold"
                            android:layout_marginTop="10dp"
                            />
                   </LinearLayout>
                   <ListView
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:id="@+id/noticeListView"
                        android:layout_margin="10dp"
                        android:dividerHeight="10dp"
                        android:divider="#ffffff"
                        >
                   </ListView>
               </LinearLayout>
           <RelativeLayout
                android:id="@+id/fragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"></RelativeLayout>
       </FrameLayout>
</LinearLayout>


MainActivity.java

PHP 서버를 통해 디비값을 가져와서 공지사항을 띄워주게 수정합니다.

package com.example.kch.registration_v8;
import android.os.AsyncTask;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
    //7강때 추가된 부분
    private ListView noticeListView;
    private NoticeListAdapter adapter;
    private List<Notice> noticedList;
    @Override
    protected void onCreate(Bundle savedInstanceState)
        super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
        //7강때 추가된 부분
        noticeListView = (ListView)findViewById(R.id.noticeListView);
        noticedList = new ArrayList<Notice>();
        //8강때 삭제됨
      /* noticedList.add(new Notice("공지사항", "gakari", "2018-09-09"));
       noticedList.add(new Notice("공지사항", "gakari", "2018-09-10"));
       noticedList.add(new Notice("공지사항", "gakari", "2018-09-11"));
       noticedList.add(new Notice("공지사항", "gakari", "2018-09-12"));
       noticedList.add(new Notice("공지사항", "gakari", "2018-09-13"));
       noticedList.add(new Notice("공지사항", "gakari", "2018-09-14"));
       noticedList.add(new Notice("공지사항", "gakari", "2018-09-15"));
       noticedList.add(new Notice("공지사항", "gakari", "2018-09-16"));
       noticedList.add(new Notice("공지사항", "gakari", "2018-09-17"));
       noticedList.add(new Notice("공지사항", "gakari", "2018-09-18"));
       noticedList.add(new Notice("공지사항", "gakari", "2018-09-19"));
       noticedList.add(new Notice("공지사항", "gakari", "2018-09-20"));*/
        adapter = new NoticeListAdapter(getApplicationContext(), noticedList);
        noticeListView.setAdapter(adapter);
        final Button courseButton = (Button)findViewById(R.id.courseButton);
        final Button statisticsButton = (Button)findViewById(R.id.statisticsButton);
        final Button scheduleButton = (Button)findViewById(R.id.scheduleButton);
        final LinearLayout notice = (LinearLayout)findViewById(R.id.notice);
       courseButton.setOnClickListener(new View.OnClickListener()
            @Override
            public void onClick(View view)
                notice.setVisibility(View.GONE);//공지사항이 안보임
                courseButton.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
                statisticsButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                scheduleButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
               FragmentManager fragmentManager = getSupportFragmentManager();
               FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
               fragmentTransaction.replace(R.id.fragment, new CourseFragment());//프래그먼트를 바꿔줌
                fragmentTransaction.commit();
           
       );
       statisticsButton.setOnClickListener(new View.OnClickListener()
            @Override
            public void onClick(View view)
                notice.setVisibility(View.GONE);//공지사항이 안보임
                courseButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                statisticsButton.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
                scheduleButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
               FragmentManager fragmentManager = getSupportFragmentManager();
               FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
               fragmentTransaction.replace(R.id.fragment, new StatisticsFragment());//프래그먼트를 바꿔줌
                fragmentTransaction.commit();
           
       );
       scheduleButton.setOnClickListener(new View.OnClickListener()
            @Override
            public void onClick(View view)
                notice.setVisibility(View.GONE);//공지사항이 안보임
                courseButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                statisticsButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                scheduleButton.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
               FragmentManager fragmentManager = getSupportFragmentManager();
               FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
               fragmentTransaction.replace(R.id.fragment, new ScheduleFragment());//프래그먼트를 바꿔줌
                fragmentTransaction.commit();
           
       );
        //8강때 추가된부분
       //AsyncTask 실행 부분
        new BackgroundTask().execute();
   
    //PHP서버에 접속해서 JSON타입으로 데이터를 가져옴
    class BackgroundTask extends AsyncTask<Void, Void, String>
       String target;
        @Override
        protected void onPreExecute()
            super.onPreExecute();
            target = "http://10.0.2.2:8080/registration/NoticeList.php";
       
        //실제 데이터를 가져오는 부분임
        @Override
        protected String doInBackground(Void... voids)
            try
               URL url = new URL(target);
               HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
               InputStream inputStream = httpURLConnection.getInputStream();
               BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
               String temp;//결과 값을 여기에 저장함
                StringBuilder stringBuilder = new StringBuilder();
                //버퍼생성후 한줄씩 가져옴
                while((temp = bufferedReader.readLine()) != null)
                   stringBuilder.append(temp + "");
               
               bufferedReader.close();
               inputStream.close();
               httpURLConnection.disconnect();
                return stringBuilder.toString().trim();//결과값이 여기에 리턴되면 이 값이 onPostExcute의 파라미터로 넘어감
            catch(Exception e)
               e.printStackTrace();
           
            return null;
       
        @Override
        protected void onProgressUpdate(Void... values)
            super.onProgressUpdate(values);
       
        //여기서는 가져온 데이터를 Notice객체에 넣은뒤 리스트뷰 출력을 위한 List객체에 넣어주는 부분
        @Override
        protected void onPostExecute(String result)
            super.onPostExecute(result);
            try
               JSONObject jsonObject = new JSONObject(result);
               JSONArray jsonArray = jsonObject.getJSONArray("response");
                int count = 0;
               String noticeContent, noticeName, noticeDate;
                //json타입의 값을 하나씩 빼서 Notice 객체에 저장후 리스트에 추가하는 부분
                while(count <jsonArray.length())
                   JSONObject object = jsonArray.getJSONObject(count);
                   noticeContent = object.getString("noticeContent");
                   noticeName = object.getString("noticeName");
                   noticeDate = object.getString("noticeDate");
                   Notice notice = new Notice(noticeContent, noticeName, noticeDate);
                    noticedList.add(notice);
                   count++;
               
           catch (Exception e)
               e.printStackTrace();
           
       
   

 

블로그 이미지

가카리

소프트웨어와 하드웨어 프로그래밍, 취업 및 직장생활 전문 블로그

예제 출처 : https://www.inflearn.com/course
예제 소스 : https://github.com/GaKaRi/gakari_android/commit/595d4bd0a74854d8b0d52ea185d5aac8e0b79f0f

실행화면

1. 먼저 로그인을 합니다.



2. 로그인에 성공 후 다음과 같이 리스트뷰로 공지사항이 올라오는 것을 볼 수 있습니다.





예제 구현 시작
 
  1. res/drawable 에서 오른쪽 누르고 Vector Asset선택 후 다음과 같이 Clip Art를 선택해서 지정해줍니다.




res/drawable/ic_textsms_black_24dp.xml
아래 fillColor를 #FFFFFFFF 로 지정합니다.

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
   <path
        android:fillColor="#FFFFFFFF"
        android:pathData="M20,2L4,2c-1.1,0 -1.99,0.9 -1.99,2L2,22l4,-4h14c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2zM9,11L7,11L7,9h2v2zM13,11h-2L11,9h2v2zM17,11h-2L15,9h2v2z"/>
</vector>

res/layout/notice.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">
   <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="notice"
        android:layout_gravity="center"
        android:padding="10dp"
        android:textColor="#ffffff"
        android:id="@+id/noticeText"
        android:drawableStart="@drawable/ic_textsms_black_24dp"
        android:drawableLeft="@drawable/ic_textsms_black_24dp"
        android:background="@color/colorPrimary"
        android:textStyle="bold"
        />
   <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary">
       <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="gakari"
            android:layout_gravity="center"
            android:padding="3dp"
            android:layout_marginLeft="8dp"
            android:textColor="#ffffff"
            android:textColorHint="#ffffff"
            android:id="@+id/nameText"
        />
       <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="2017-01-01"
            android:layout_gravity="center"
            android:padding="3dp"
            android:textColor="#ffffff"
            android:textColorHint="#ffffff"
            android:id="@+id/dateText"
            />
   </LinearLayout>
</LinearLayout>
res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
    tools:context="com.example.kch.registration_v7.MainActivity">
   <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="5dp">
       <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:id="@+id/courseButton"
        android:text="course list"
        android:textStyle="bold"
        android:textColor="#FFFFFF"
        android:textSize="18dp"
        android:background="@color/colorPrimary"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        />
       <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/scheduleButton"
            android:text="schedule"
            android:textStyle="bold"
            android:textColor="#FFFFFF"
            android:textSize="18dp"
            android:background="@color/colorPrimary"
            android:layout_marginLeft="8dp"
            android:layout_marginTop="8dp"
            />
       <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/statisticsButton"
            android:text="statistics"
            android:textStyle="bold"
            android:textColor="#FFFFFF"
            android:textSize="18dp"
            android:background="@color/colorPrimary"
            android:layout_marginLeft="8dp"
            android:layout_marginTop="8dp"
            />
       </LinearLayout>
       <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
           <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:id="@+id/notice">
               <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    android:orientation="vertical"
                    android:background="@color/colorPrimary"
                    android:layout_marginTop="8dp">
                       <ImageButton
                            android:layout_width="wrap_content"
                            android:layout_height="150dp"
                            android:layout_gravity="center"
                            android:layout_marginTop="5dp"
                            android:src="@drawable/univlogo"
                            android:scaleType="fitCenter"
                            />
                       <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:text="Notice"
                            android:textColor="#ffffff"
                            android:textSize="25dp"
                            android:textStyle="bold"
                            android:layout_marginTop="10dp"
                            />
                   </LinearLayout>
              //아래 부분이 추가됬습니다. 리스트뷰를 뿌려주기 위한 부분입니다.
                   <ListView
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:id="@+id/noticeListView"
                        android:layout_margin="10dp"
                        android:dividerHeight="10dp"
                        android:divider="#ffffff"
                        >
                   </ListView>
               </LinearLayout>
           <RelativeLayout
                android:id="@+id/fragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"></RelativeLayout>
       </FrameLayout>
</LinearLayout>


Notice.java

리스트뷰에 뿌려주는 데이터를 담기 위한 클래스입니다.

package com.example.kch.registration_v7;

public class Notice
   String notice;
   String name;
    public Notice(String notice, String name, String date)
        this.notice = notice;
        this.name = name;
        this.date = date;
   
   String date;
    public String getNotice()
        return notice;
   
    public void setNotice(String notice)
        this.notice = notice;
   
    public String getName()
        return name;
   
    public void setName(String name)
        this.name = name;
   
    public String getDate()
        return date;
   
    public void setDate(String date)
        this.date = date;
   



NoticeListAdapter.java

리스트뷰에 데이터를 어떻게 뿌려줄지 구현하는 부분입니다.

package com.example.kch.registration_v7;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.List;
public class NoticeListAdapter extends BaseAdapter
    private Context context;
    private List<Notice> noticedList;
    public NoticeListAdapter(Context context, List<Notice> noticedList)
        this.context = context;
        this.noticedList = noticedList;
   
    @Override
    public int getCount()
        return noticedList.size();//리스트뷰의 총 갯수
   
    @Override
    public Object getItem(int position)
        return noticedList.get(position);//해당 위치의 값을 리스트뷰에 뿌려줌
   
    @Override
    public long getItemId(int position)
        return position;
   
    //리스트뷰에서 실질적으로 뿌려주는 부분임
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
       View v = View.inflate(context, R.layout.notice, null);
       TextView noticeText = (TextView)v.findViewById(R.id.noticeText);
       TextView nameText = (TextView)v.findViewById(R.id.nameText);
       TextView dateText = (TextView)v.findViewById(R.id.dateText);
       noticeText.setText(noticedList.get(position).getNotice());
       nameText.setText(noticedList.get(position).getName());
       dateText.setText(noticedList.get(position).getDate());
       v.setTag(noticedList.get(position).getNotice());
        return v;
   



 MainActivity.java

리스트뷰에 어떤 데이터를 뿌려줄지 연결하는 부분입니다.

package com.example.kch.registration_v7;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
    //7강때 추가된 부분
    private ListView noticeListView;
    private NoticeListAdapter adapter;
    private List<Notice> noticedList;
    @Override
    protected void onCreate(Bundle savedInstanceState)
        super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
        //7강때 추가된 부분
        noticeListView = (ListView)findViewById(R.id.noticeListView);
        noticedList = new ArrayList<Notice>();
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-09"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-10"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-11"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-12"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-13"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-14"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-15"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-16"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-17"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-18"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-19"));
        noticedList.add(new Notice("공지사항", "gakari", "2018-09-20"));
        adapter = new NoticeListAdapter(getApplicationContext(), noticedList);
        noticeListView.setAdapter(adapter);
        final Button courseButton = (Button)findViewById(R.id.courseButton);
        final Button statisticsButton = (Button)findViewById(R.id.statisticsButton);
        final Button scheduleButton = (Button)findViewById(R.id.scheduleButton);
        final LinearLayout notice = (LinearLayout)findViewById(R.id.notice);
       courseButton.setOnClickListener(new View.OnClickListener()
            @Override
            public void onClick(View view)
                notice.setVisibility(View.GONE);//공지사항이 안보임
                courseButton.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
                statisticsButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                scheduleButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
               FragmentManager fragmentManager = getSupportFragmentManager();
               FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
               fragmentTransaction.replace(R.id.fragment, new CourseFragment());//프래그먼트를 바꿔줌
                fragmentTransaction.commit();
           
       );
       statisticsButton.setOnClickListener(new View.OnClickListener()
            @Override
            public void onClick(View view)
                notice.setVisibility(View.GONE);//공지사항이 안보임
                courseButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                statisticsButton.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
                scheduleButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
               FragmentManager fragmentManager = getSupportFragmentManager();
               FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
               fragmentTransaction.replace(R.id.fragment, new StatisticsFragment());//프래그먼트를 바꿔줌
                fragmentTransaction.commit();
           
       );
       scheduleButton.setOnClickListener(new View.OnClickListener()
            @Override
            public void onClick(View view)
                notice.setVisibility(View.GONE);//공지사항이 안보임
                courseButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                statisticsButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                scheduleButton.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
               FragmentManager fragmentManager = getSupportFragmentManager();
               FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
               fragmentTransaction.replace(R.id.fragment, new ScheduleFragment());//프래그먼트를 바꿔줌
                fragmentTransaction.commit();
           
       );
   

블로그 이미지

가카리

소프트웨어와 하드웨어 프로그래밍, 취업 및 직장생활 전문 블로그




실행화면


 1 먼저 회원가입을 합니다.


2 회원 정보를 입력한 뒤 REGISTER 버튼을 누릅니다.


3 다음과 같이 로그인을 합니다.



4 로그인에 성공하면 다음과 같은 메인화면이 나옵니다.



UserLogin.php(180923 추가)

<?php
    $con = mysqli_connect('localhost', 'root', '1234', 'registration');
     //안드로이드 앱으로부터 아래 값들을 받음
    $userID = $_POST["userID"];
    $userPassword = $_POST["userPassword"];
    $statement = mysqli_prepare($con, "SELECT userID FROM USER WHERE userID = ? AND userPassword = ?");
    mysqli_stmt_bind_param($statement, "ss", $userID, $userPassword);
    mysqli_stmt_execute($statement);
    mysqli_stmt_store_result($statement);
    mysqli_stmt_bind_result($statement, $userID);
    $response = array();
    $response["success"] = false;
    while(mysqli_stmt_fetch($statement)){
      $response["success"] = true;
      $response["userID"] = $userID;
    }
    echo json_encode($response);
?>


MainActivity.java


로그인 성공시 화면


package com.example.kch.registration_v5;


import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;


public class MainActivity extends AppCompatActivity {


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

    }

}



activity_main.xml


<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context="com.example.kch.registration_v5.MainActivity">


</android.support.constraint.ConstraintLayout>



LoginRequest.java


로그인 시도를 위한 StringRequest를 상속받는 클래스


package com.example.kch.registration_v5;


import com.android.volley.AuthFailureError;

import com.android.volley.Response;

import com.android.volley.toolbox.StringRequest;


import java.util.HashMap;

import java.util.Map;


/**

* Created by kch on 2018. 7. 23..

*/


public class LoginRequest extends StringRequest{


    final static private String URL = "http://10.0.2.2:8080/registration/UserLogin.php";

    private Map<String, String> parameters;


    public LoginRequest(String userID, String userPassword, Response.Listener<String> listener){

        super(Method.POST, URL, listener, null);//해당 URL에 POST방식으로 파마미터들을 전송함

        parameters = new HashMap<>();

        parameters.put("userID", userID);

        parameters.put("userPassword", userPassword);

    }


    @Override

    protected Map<String, String> getParams() throws AuthFailureError {

        return parameters;

    }



}




 LoginActivity.java


실제로 로그인을 위한 ID와 패스워드를 입력받고 서버로 넘겨줘서 인증하는 부분입니다.


package com.example.kch.registration_v5;


import android.content.Intent;

import android.support.v7.app.AlertDialog;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;


import com.android.volley.RequestQueue;

import com.android.volley.Response;

import com.android.volley.toolbox.Volley;


import org.json.JSONObject;


public class LoginActivity extends AppCompatActivity {


    private AlertDialog dialog;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);


        TextView registerButton = (TextView)findViewById(R.id.registerButton);


        //버튼이 눌리면 RegisterActivity로 가게함

        registerButton.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);

                LoginActivity.this.startActivity(registerIntent);

            }

        });


        final EditText idText = (EditText) findViewById(R.id.idText);

        final EditText passwordText = (EditText) findViewById(R.id.passwordText);

        final Button loginButton = (Button)findViewById(R.id.loginButton);


        loginButton.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                String userID = idText.getText().toString();

                String userPassword = passwordText.getText().toString();


                Response.Listener<String> responseLisner = new Response.Listener<String>(){


                    @Override

                    public void onResponse(String response) {

                        try{

                            JSONObject jsonResponse = new JSONObject(response);

                            boolean success = jsonResponse.getBoolean("success");


                            if(success){

                                AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);

                                dialog = builder.setMessage("로그인에 성공했습니다")

                                        .setPositiveButton("확인", null)

                                        .create();

                                dialog.show();

                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);

                                LoginActivity.this.startActivity(intent);

                                finish();

                            }else {

                                AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);

                                dialog = builder.setMessage("계정을 다시 확인하세요")

                                        .setNegativeButton("다시시도", null)

                                        .create();

                                dialog.show();

                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);

                                LoginActivity.this.startActivity(intent);

                                finish();

                            }


                        }catch (Exception e){

                            e.printStackTrace();

                        }

                    }

                };


                LoginRequest loginRequest = new LoginRequest(userID, userPassword, responseLisner);

                RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);

                queue.add(loginRequest);


            }

        });


    }


    @Override

    protected void onStop(){

        super.onStop();

        if(dialog != null){//다이얼로그가 켜져있을때 함부로 종료가 되지 않게함

            dialog.dismiss();

            dialog = null;

        }

    }



}



activity_login.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"

    tools:context="com.example.kch.registration_v5.LoginActivity">

   

    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:orientation="vertical">

        <LinearLayout

            android:layout_width="match_parent"

            android:layout_height="225dp"

            android:orientation="vertical"

            android:background="@color/colorPrimary"

            >

            <ImageView

                android:layout_width="125dp"

                android:layout_height="125dp"

                android:layout_gravity="center"

                android:layout_marginTop="20dp"

                android:src="@drawable/univlogo"

                />

            <TextView

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:layout_gravity="center"

                android:text="Kyowon UNIV"

                android:textColor="#ffffff"

                android:textSize="25dp"

                android:textStyle="bold"

                android:layout_marginTop="10dp"

                />


            <TextView

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:layout_gravity="center"

                android:text="Registration Helper"

                android:textColor="#ffffff"

                android:textSize="18dp"

                android:textStyle="bold"

                />

        </LinearLayout>


        <LinearLayout

            android:layout_width="match_parent"

            android:layout_height="match_parent"

            android:orientation="vertical">

           

            <EditText

                android:layout_width="280dp"

                android:layout_height="wrap_content"

                android:hint="ID"

                android:layout_gravity="center"

                android:padding="10dp"

                android:textColor="#ffffff"

                android:textColorHint="#ffffff"

                android:id="@+id/idText"

                android:drawableStart="@drawable/ic_person_black_24dp"

                android:drawableLeft="@drawable/ic_person_black_24dp"

                android:layout_marginTop="50dp"

                android:background="@color/colorPrimary"

                />


            <EditText

                android:inputType="textPassword"

                android:layout_width="280dp"

                android:layout_height="wrap_content"

                android:hint="PASSWORD"

                android:layout_gravity="center"

                android:padding="10dp"

                android:textColor="#ffffff"

                android:textColorHint="#ffffff"

                android:id="@+id/passwordText"

                android:drawableStart="@drawable/ic_lock_outline_black_24dp"

                android:drawableLeft="@drawable/ic_lock_outline_black_24dp"

                android:layout_marginTop="10dp"

                android:background="@color/colorPrimary"

                />


            <Button

                android:layout_width="280dp"

                android:layout_height="wrap_content"

                android:textSize="20dp"

                android:textStyle="bold"

                android:textColor="#ffffff"

                android:background="@color/colorPrimary"

                android:text="Login"

                android:layout_marginTop="10dp"

                android:layout_gravity="center"

                android:id="@+id/loginButton"


                />

           

            <TextView

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:layout_gravity="center"

                android:textSize="18dp"

                android:layout_marginTop="10dp"

                android:text="Member Registration"

                android:id="@+id/registerButton"

                />



        </LinearLayout>

       

    </LinearLayout>




</LinearLayout>









블로그 이미지

가카리

소프트웨어와 하드웨어 프로그래밍, 취업 및 직장생활 전문 블로그




실행화면


  1. 메인 화면입니다. 여기서 Member Registration을 누릅니다.



  1. 아이디값에 abcd를 입력후 CHECK ID를 누릅니다.



  1. 해당 아이디를 사용할수있다고 나오네요


  1. 모든 항목을 입력해주고 REGISTER 버튼을 누릅니다.


  1. 다시 첫화면으로 돌아가게됩니다.


  1. 데이터베이스를 확인해보면 방금 입력한 abcd 계정이 정상적으로 생성되었음을 알 수 있습니다.


  1. 만약 abcd란 아이디로 다시 회원가입을 하려고 하면 다음과 같이 이미 사용중인 아이디라고 출력됩니다.





저번 3번째 강의인 회원 데이터베이스 구축에서 오류가 있어서 다음과 같이 UserValidate.php 파일을 다음과 같이 수정합니다.


UserValidate.php


<?php

    $con = mysqli_connect('localhost', 'root', 'qwer1234', 'registration');

     $userID = $_POST["userID"];

     $statement = mysqli_prepare($con, "SELECT userID FROM USER WHERE userID = ?");

     //위에서 * 하면 mysqli_stmt_bind_result에서 에러가 나서 정정함

     mysqli_stmt_bind_param($statement, "s", $userID);

     mysqli_stmt_execute($statement);

     mysqli_stmt_store_result($statement);//결과를 클라이언트에 저장함

     mysqli_stmt_bind_result($statement, $userID);//결과를 $userID 바인딩함

     $response = array();

     $response["success"] = true;

     while(mysqli_stmt_fetch($statement)){

       $response["success"] = false;//회원가입불가를 나타냄

       $response["userID"] = $userID;

     }

     //데이터베이스 작업이 성공 혹은 실패한것을 알려줌

     echo json_encode($response);

?>


아래 파일에 colorWarning 과 colorGray를 추가시켜줍니다.


values/colors.xml


<?xml version="1.0" encoding="utf-8"?>

<resources>

    <color name="colorPrimary">#039BE5</color>

    <color name="colorPrimaryDark">#0277BD</color>

    <color name="colorAccent">#546E7A</color>

    <color name="colorWarning">#ED00CB</color>

    <color name="colorGray">#8C8C8C</color>

</resources>


layout/activity_register.xml


기존 레이아웃에서 입력한 id를 검증하기 위한 버튼을 추가해줍니다. 


<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
    tools:context="com.example.kch.registration_v4.RegisterActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:background="@color/colorPrimary"
            >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Member Registration"
                android:textColor="#ffffff"
                android:textSize="30dp"
                android:textStyle="bold"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="280dp"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="50dp"
                android:layout_gravity="center"
                >

                <EditText
                    android:layout_width="190dp"
                    android:layout_height="wrap_content"
                    android:hint="ID"
                    android:layout_gravity="center"
                    android:padding="10dp"
                    android:textColor="#ffffff"
                    android:textColorHint="#ffffff"
                    android:id="@+id/idText"
                    android:drawableStart="@drawable/ic_person_black_24dp"
                    android:drawableLeft="@drawable/ic_person_black_24dp"
                    android:layout_marginRight="10dp"
                    android:background="@color/colorPrimary"
                    />
               
                <Button
                    android:layout_width="80dp"
                    android:layout_height="40dp"
                    android:textSize="15dp"
                    android:textStyle="bold"
                    android:background="@color/colorWarning"
                    android:text="Check ID"
                    android:layout_gravity="center"
                    android:id="@+id/validateButton"
                    android:textColor="#ffffff"/>


            </LinearLayout>

            <EditText
                android:inputType="textPassword"
                android:layout_width="280dp"
                android:layout_height="wrap_content"
                android:hint="PASSWORD"
                android:layout_gravity="center"
                android:padding="10dp"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                android:id="@+id/passwordText"
                android:drawableStart="@drawable/ic_lock_outline_black_24dp"
                android:drawableLeft="@drawable/ic_lock_outline_black_24dp"
                android:layout_marginTop="10dp"
                android:background="@color/colorPrimary"
                />

            <EditText
                android:inputType="text"
                android:layout_width="280dp"
                android:layout_height="wrap_content"
                android:hint="E-mail"
                android:layout_gravity="center"
                android:padding="10dp"
                android:textColor="#ffffff"
                android:textColorHint="#ffffff"
                android:id="@+id/emailText"
                android:drawableStart="@drawable/ic_mail_outline_black_24dp"
                android:drawableLeft="@drawable/ic_mail_outline_black_24dp"
                android:layout_marginTop="10dp"
                android:background="@color/colorPrimary"
                />
           
            <RadioGroup
                android:layout_width="280dp"
                android:layout_height="wrap_content"
                android:id="@+id/genderGroup"
                android:layout_gravity="center_horizontal"
                android:orientation="horizontal"
                android:layout_marginTop="10dp"
                >
                <RadioButton
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:text="female"
                    android:id="@+id/genderWoman"
                    android:layout_weight="1"
                    android:checked="true"
                    />

                <RadioButton
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:text="male"
                    android:id="@+id/genderMan"
                    android:layout_weight="1"
                    />
            </RadioGroup>

            <Spinner
                android:layout_width="280dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="10dp"
                android:id="@+id/majorSpinner"
                ></Spinner>

            <Button
                android:layout_width="280dp"
                android:layout_height="wrap_content"
                android:textSize="20dp"
                android:textStyle="bold"
                android:textColor="#ffffff"
                android:background="@color/colorPrimary"
                android:text="Register"
                android:layout_marginTop="10dp"
                android:layout_gravity="center"
                android:id="@+id/registerButton"
                />


        </LinearLayout>

    </LinearLayout>



</LinearLayout>


RegisterRequest.java


해당 클래스는  URL에 POST방식으로 파라미터들을 전송하는 역할을 수행합니다. 여기서는 회원가입정보를 PHP서버에 보내서 데이터베이스에 저장시키게합니다.


package com.example.kch.registration_v4;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

/**
* Created by kch on 2018. 5. 14..
*/

public class RegisterRequest extends StringRequest {

    final static private String URL = "http://10.0.2.2:8080/registration/UserRegister.php";
    private Map<String, String> parameters;

    public RegisterRequest(String userID, String userPassword, String userGender, String userMajor, String userEmail, Response.Listener<String> listener){
        super(Method.POST, URL, listener, null);//해당 URL에 POST방식으로 파마미터들을 전송함
        parameters = new HashMap<>();
        parameters.put("userID", userID);
        parameters.put("userPassword", userPassword);
        parameters.put("userGender", userGender);
        parameters.put("userMajor", userMajor);
        parameters.put("userEmail", userEmail);

    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return parameters;
    }
}

ValidateRequest.java


해당 클래스도 아래 URL에 POST방식으로 파라미터들을 전송합니다. 여기서는 아이디값이 이미 가입된 아이디인지 검증합니다.


package com.example.kch.registration_v4;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

/**
* Created by kch on 2018. 5. 14..
*/

public class ValidateRequest extends StringRequest {

    final static private String URL = "http://10.0.2.2:8080/registration/UserValidate.php";