프로그래밍/안드로이드

안드로이드 - 프로젝트5. 회원목록 출력하기

가카리 2018. 2. 17. 12:14
반응형



AsyncTask를 사용하는데 파일다운로드와 같은 작업을 백그라운드에서 진행할때 사용합니다.



  1. execute( ) 명령어를 통해 AsyncTask을 실행합니다.
  2. AsyncTask로 백그라운드 작업을 실행하기 전에 onPreExcuted( )실행됩니다. 이 부분에는 이미지 로딩 작업이라면 로딩 중 이미지를 띄워 놓기 등, 스레드 작업 이전에 수행할 동작을 구현합니다. 
  3.  새로 만든 스레드에서 백그라운드 작업을 수행합니다. execute( ) 메소드를 호출할 때 사용된 파라미터를  전달 받습니다.
  4.  doInBackground( ) 에서 중간 중간 진행 상태를 UI에 업데이트 하도록 하려면 publishProgress( ) 메소드를 호출 합니다.
  5.  onProgressUpdate( ) 메소드는 publishProgress( )가 호출 될 때  마다 자동으로 호출됩니다.
  6.  doInBackground( ) 메소드에서 작업이 끝나면 onPostExcuted( ) 로 결과 파라미터를 리턴하면서 그 리턴값을 통해 스레드 작업이 끝났을 때의 동작을 구현합니다. 
여기서 핵심은 onPreExecute( ), onProgressUpadate( ), onPostExecute( ) 메소드는 메인 스레드에서 실행되므로 UI 객체에 자유롭게 접근할 수 있다는 것입니다.


출처: http://itmining.tistory.com/7 [IT 마이닝]



먼저 실행화면을 보고 소스를 봅시다.


실행 화면

  1. admin 계정으로 로그인을 합니다.



  1. 다음과 같이 MANAGE 버튼이 보입니다.



  1. 모든 회원정보에 관한 내용이 출력됩니다.




예제 설명

먼저 다음과 같이 MANAGE버튼을 만들어 봅시다.




서버단 php파일입니다. 데이터베이스에 접속해서 모든 회원 정보를 가져와서 화면에 JSON형식으로 뿌려주는 역할을 합니다.

<?php
$con = mysqli_connect('localhost', 'root', '****', 'proj_manager');
$result = mysqli_query($con, "SELECT * FROM USER;");
$response = array();//배열 선언
while($row = mysqli_fetch_array($result)){
//response["userID"]=$row[0] ....이런식으로 됨.
array_push($response, array("userID"=>$row[0], "userPassword"=>$row[1], "userName"=>$row[2], "userAge"=>$row[3]));
}
//response라는 변수명으로 JSON 타입으로 $response 내용을 출력
echo json_encode(array("response"=>$response));
mysqli_close($con);
?>


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="com.example.kch.proj_manager_v5.com.example.kch.proj_manager_v3.MainActivity">

    <TextView
        android:id="@+id/WelcomeMessage"
        android:layout_width="335dp"
        android:layout_height="42dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="33dp"
        android:text="welcome"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1"
        app:layout_constraintHorizontal_bias="0.515"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/idText"
        android:layout_width="333dp"
        android:layout_height="48dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="73dp"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1"
        app:layout_constraintHorizontal_bias="0.514"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/WelcomeMessage" />

    <TextView
        android:id="@+id/textView0"
        android:layout_width="333dp"
        android:layout_height="48dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="132dp"
        android:text="Password"
        android:textAppearance="@style/TextAppearance.AppCompat.Headline"
        app:layout_constraintHorizontal_bias="0.514"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/WelcomeMessage" />

    <TextView
        android:id="@+id/passwordText"
        android:layout_width="333dp"
        android:layout_height="48dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="195dp"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1"
        app:layout_constraintHorizontal_bias="0.514"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/WelcomeMessage" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="333dp"
        android:layout_height="48dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="12dp"
        android:text="ID"
        android:textAppearance="@style/TextAppearance.AppCompat.Headline"
        app:layout_constraintHorizontal_bias="0.514"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/WelcomeMessage" />

    <Button
        android:id="@+id/manageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:text="Manage"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/passwordText"
        app:layout_constraintVertical_bias="0.085" />

</android.support.constraint.ConstraintLayout>

다음은 MANAGE버튼은 눌렀을 때 회원목록을 출력하기 위해 다음과 같이 activity_management.xml 파일을 만들어봅시다.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="com.example.kch.proj_manager_v5.ManagementActivity">

    <TextView
        android:id="@+id/userListTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp" />
</android.support.constraint.ConstraintLayout>


다음은 admin계정으로 로그인이 되었을 때 MANAGE 버튼을 활성화시키고  MANAGE버튼이 눌리면 

웹페이지로부터 회원정보를 가져오는 작업을 합니다.

MainActivity.java

package com.example.kch.proj_manager_v5;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
importjava.net.URL;

public class MainActivity extends AppCompatActivity {

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

        TextView idText = (TextView)findViewById(R.id.idText);
        TextView passwordText = (TextView)findViewById(R.id.passwordText);
        TextView welcome = (TextView)findViewById(R.id.WelcomeMessage);
        Button managementButton = (Button)findViewById(R.id.manageButton);

        Intent intent = getIntent();
        String userID = intent.getStringExtra("userID");
        String userPassword = intent.getStringExtra("userPassword");
        String msg = "Welcome" + userID;

        idText.setText(userID);
        passwordText.setText(userPassword);
        welcome.setText(msg);


        //admin 계정이 아니면 버튼 안보이게
        if(!userID.equals("admin")){
            //managementButton.setEnabled(false);
            managementButton.setVisibility(View.GONE);
        }

        //MANAGE버튼이 눌리면 여기로
        managementButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new BackgroundTask().execute();
            }
        });


    }

    //모든회원에 대한 정보를 가져오기 위한 쓰레드
    class BackgroundTask extends AsyncTask<Void, Void, String> {
        String target;

        @Override
        protected void onPreExecute() {
            //List.php 파싱으로 가져올 웹페이지
            target = "http://10.0.2.2:8080/List.php";
        }

        @Override
        protected String doInBackground(Void... voids) {

            try{
                URL url = new URL(target);//URL 객체 생성

                //URL 이용해서 웹페이지에 연결하는 부분
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();

                //바이트단위 입력스트림 생성 소스는 httpURLConnection
                InputStream inputStream = httpURLConnection.getInputStream();

                //웹페이지 출력물을 버퍼로 받음 버퍼로 하면 속도가 빨라짐
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String temp;

                //문자열 처리를 빠르게 하기 위해 StringBuilder클래스를 사용함
                StringBuilder stringBuilder = new StringBuilder();

                //한줄씩 읽어서 stringBuilder 저장함
                while((temp = bufferedReader.readLine()) != null){
                    stringBuilder.append(temp + "\n");//stringBuilder 넣어줌
                }

                //사용했던 것도 닫아줌
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return stringBuilder.toString().trim();//trim 앞뒤의 공백을 제거함

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

        }

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

        @Override
        protected void onPostExecute(String result) {
            Intent intent = new Intent(MainActivity.this, ManagementActivity.class);
            intent.putExtra("userList", result);//파싱한 값을 넘겨줌
            MainActivity.this.startActivity(intent);//ManagementActivity 넘어감

        }

    }

}

MainActivity에서 MANAGE버튼이 눌리면 값을 인텐트로 가져와서 단순히 TextView에 뿌려주는 역할을 합니다.

ManagementActivity.java

package com.example.kch.proj_manager_v5;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.content.Intent;

public class ManagementActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_management);
        TextView userListTextView = (TextView)findViewById(R.id.userListTextView);

        //ManagementActivity MainActivity에서 호출되므로 호출시 넘겨준 데이터를 뿌려주는 역할을 한다
        Intent intent = getIntent();
        //intent.putExtra("userList", result); 에서 userList 저장했으므로 아래와 같이 쓰게됨
        userListTextView.setText(intent.getStringExtra("userList"));
    }
}




반응형