프로그래밍/안드로이드

안드로이드 - 프로젝트6. 회원목록을 리스트뷰로 출력하기

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




이번에는 저번 강의때 했던 회원목록을 TextView로 출력했던 것을 리스트뷰로 바꿔보는 예제입니다.

실행 화면

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



2. 다음과 같이  MANAGE버튼이 보이면 눌러줍니다.



3. MANAGE버튼을 클릭하면 다음과 같이 리스트뷰로 회원목록을 출력합니다.





예제 분석

다음은 리스트뷰에 들어가는 내용들을 정의하는 부분입니다.
user.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:background="#ffffff"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/userID"
        android:text="ID"
        android:textSize="20dp"
        android:textColor="#00a7f5"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/userPassword"
        android:text="PASSWORD"
        android:textSize="20dp"
        android:textColor="#f92a3f"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/userName"
        android:text="NAME"
        android:textSize="16dp"
        android:textColor="#a902f0"
    />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/userAge"
        android:text="AGE"
        android:textSize="18dp"
        android:textColor="#00a7f5"
        />


</LinearLayout>

다음은 기본의 TextView를 ListView로 바꿔줬습니다.

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_v6.ManagementActivity">

   <LinearLayout
       android:layout_width="368dp"
       android:layout_height="495dp"
       android:orientation="vertical"
       android:background="#d1d1d1"
       tools:layout_editor_absoluteY="8dp"
       tools:layout_editor_absoluteX="8dp">
        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/listView"
            android:layout_marginTop="10dp"
            android:layout_marginRight="15dp"
            android:layout_marginLeft="15dp"
            android:dividerHeight="10dp"
            android:divider="#d1d1d1">
        </ListView>
</LinearLayout>
</android.support.constraint.ConstraintLayout>


아래는 ID, Password, Name, Age 값을 하나의 클래스에 담기 위한 선언입니다.

User.java

package com.example.kch.proj_manager_v6;

/**
 * Created by kch on 2018. 2. 17..
 */

public class User {
    String userID;
    String userPassword;
    String userAge;
    String userName;

    public String getUserID() {
        return userID;
    }

    public void setUserID(String userID) {
        this.userID = userID;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public String getUserAge() {
        return userAge;
    }

    public void setUserAge(String userAge) {
        this.userAge = userAge;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public User(String userID, String userPassword, String userAge, String userName) {
        this.userID = userID;
        this.userPassword = userPassword;
        this.userAge = userAge;
        this.userName = userName;
    }
}

아래는 User를 리스트뷰에 뿌려주기 위한 어댑터입니다. 이와 관련된 디자인 패턴은 어댑터패턴이 있죠...

UserListAdapter.java

package com.example.kch.proj_manager_v6;

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;

/**
 * Created by kch on 2018. 2. 17..
 */

public class UserListAdapter extends BaseAdapter {

    private Context context;
    private List<User> userList;

    public UserListAdapter(Context context, List<User> userList){
        this.context = context;
        this.userList = userList;
    }

    //출력할 총갯수를 설정하는 메소드
    @Override
    public int getCount() {
        return userList.size();
    }

    //특정한 유저를 반환하는 메소드
    @Override
    public Object getItem(int i) {
        return userList.get(i);
    }

    //아이템별 아이디를 반환하는 메소드
    @Override
    public long getItemId(int i) {
        return i;
    }

    //가장 중요한 부분
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View v = View.inflate(context, R.layout.user, null);

        //뷰에 다음 컴포넌트들을 연결시켜줌
        TextView userID = (TextView)v.findViewById(R.id.userID);
        TextView userPassword = (TextView)v.findViewById(R.id.userPassword);
        TextView userName = (TextView)v.findViewById(R.id.userName);
        TextView userAge = (TextView)v.findViewById(R.id.userAge);

        userID.setText(userList.get(i).getUserID());
        userPassword.setText(userList.get(i).getUserPassword());
        userName.setText(userList.get(i).getUserName());
        userAge.setText(userList.get(i).getUserAge());

        //이렇게하면 findViewWithTag 있음 없어도 되는 문장임
        v.setTag(userList.get(i).getUserID());

        //만든뷰를 반환함
        return v;
    }
}

리스트뷰와 어댑터를 연결하고 웹페이지(List.php)에서 가져온 값을 리스트뷰로 뿌려주는 부분입니다.

ManagementActivity.java

package com.example.kch.proj_manager_v6;

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

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

import java.util.ArrayList;
import java.util.List;

public class ManagementActivity extends AppCompatActivity {

    private ListView listView;
    private UserListAdapter adapter;
    private List<User> userList;

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

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

        Intent intent = getIntent();

        listView = (ListView)findViewById(R.id.listView);
        userList = new ArrayList<User>();

        //어댑터 초기화부분 userList 어댑터를 연결해준다.
        adapter = new UserListAdapter(getApplicationContext(), userList);
        listView.setAdapter(adapter);

        try{
            //intent 값을 가져옵니다 이때 JSONObject타입으로 가져옵니다
            JSONObject jsonObject = new JSONObject(intent.getStringExtra("userList"));


            //List.php 웹페이지에서 response라는 변수명으로 JSON 배열을 만들었음..
            JSONArray jsonArray = jsonObject.getJSONArray("response");
            int count = 0;

            String userID, userPassword, userName, userAge;

            //JSON 배열 길이만큼 반복문을 실행
            while(count < jsonArray.length()){
                //count 배열의 인덱스를 의미
                JSONObject object = jsonArray.getJSONObject(count);

                userID = object.getString("userID");//여기서 ID 대문자임을 유의
                userPassword = object.getString("userPassword");
                userName = object.getString("userName");
                userAge = object.getString("userAge");

                //값들을 User클래스에 묶어줍니다
                User user = new User(userID, userPassword, userName, userAge);
                userList.add(user);//리스트뷰에 값을 추가해줍니다
                count++;
            }


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

    }
}





반응형