예제 출처 : 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();
           
       
   

 

블로그 이미지

가카리

프로그래밍, 취업 및 직장생활, 주식 부동산 재테크 전문 블로그

댓글을 달아 주세요