컴퓨터/android, ios

[Android Studio] 아래로 swipe해서 새로고침 하는 listview 구현하기

정석이 2021. 8. 22. 17:59

 

 

 

아래로 스와이프해서 새로고침하는 listview 구현하기!

 

 

 

 

내가 구현한건 userID = user2일 때 서버에서 가져온 값을 listview에 넣어서 보여주는 것이다.

 

 

 

 

 

 

이런 느낌^^

 

 

 


 

 

JSON 형식

 

 

 

 

JSON으로 가져올 것이기 때문에 필요 조건은 서버에서 JSON 형식으로 받아와야 한다.

 

 

그래서 형식이 {"JSONArray로 받아올 값" :[{"받을값이름1":"받을값1", "받을값이름2":"받을값2"}, {어쩌구}]} 이런식이어야함

 

 

 

 

내가 받아올 JSON 형식

 

 

 

 

 

 

 

 

listview.xml

 

 

listview.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"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/saleImage"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_marginVertical="5dp"
            android:layout_marginHorizontal="10dp"
            tools:srcCompat="@tools:sample/avatars"
            android:background="@drawable/item_style"/>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginVertical="5dp"
            android:layout_marginHorizontal="10dp"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="제품명:  "
                    android:textColor="@color/black"
                    />

                <TextView
                    android:id="@+id/Product_Name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="(제품명)"
                    android:textColor="@color/black"
                    />

            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">


                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="제품브랜드:  "
                    android:textColor="@color/black"
                    android:layout_marginTop="5dp"
                    />

                <TextView
                    android:id="@+id/Product_Brand"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="(브랜드)"
                    android:textColor="@color/black"
                    android:layout_marginTop="5dp"
                    />

            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="시리얼넘버:  "
                    android:textColor="@color/black"
                    android:layout_marginTop="5dp"
                    />

                <TextView
                    android:id="@+id/Product_Serial"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="(시리얼)"
                    android:textColor="@color/black"
                    android:layout_marginTop="5dp"
                    />

            </LinearLayout>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

 

 

 

 

 

 

 

 

home.xml

 

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

    <!-- "(name)님, 환영합니다." -->
    
    <TextView
        android:id="@+id/csmHi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="30dp"
        android:text="(소비자) 님, 환영합니다."
        android:textColor="@color/black"
        android:layout_gravity="center" />


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


        <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
            android:id="@+id/swipe_layout"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="6"
            android:layout_margin="5dp">

        <!-- 버튼  -->
        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="6"
            android:layout_margin="5dp"
            android:padding="5dp"
            android:background="@drawable/layout_style"
            android:id="@+id/listView_main_list" />

    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>


    </LinearLayout>

</LinearLayout>

 

 

 

 

여기서

 

 

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

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/swipe_layout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="6"
android:layout_margin="5dp">


<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="6"
android:layout_margin="5dp"
android:padding="5dp"
android:background="@drawable/layout_style"
android:id="@+id/listView_main_list" />

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

 

 

 

이부분이! swipe로 새로고침 되는 listview를 보여주는 부분이다.

 

 

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout 여기가 swipe 부분이고

 

<androidx.recyclerview.widget.RecyclerView 여기가 recyclerview로 구현한 listview 부분이다.

 

 

 

 

 

 

 

 

home_activity.class

 

 

 

public class home_Activity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{

    private static String IP_ADDRESS = "IP주소";
    private static String TAG = "home activity";

    public ArrayList<PersonalData> mArrayList;
    public UserAdapter mAdapter;
    private RecyclerView mRecyclerView;
    private String mJsonString;
    public String id, sserial;
    boolean check = true;

    SwipeRefreshLayout mSwipeRefreshLayout;  //swipe layout 부분


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

	//정보 받아오기 이건 로그인 부분에서 받아오는 값이다. 이 포스팅에는 없다.
        Intent intent = getIntent();
        String name = intent.getStringExtra("name");
        id = intent.getStringExtra("id");


        TextView hi = (TextView) findViewById(R.id.csmHi);    // 관리자 이름 + 님 환영합니다.
        hi.setText(name + " 님 환영합니다.");


        mRecyclerView = (RecyclerView) findViewById(R.id.listView_main_list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mArrayList = new ArrayList<>();
        mAdapter = new UserAdapter(this, mArrayList);
        mRecyclerView.setAdapter(mAdapter);


	//arraylist listview clear해주고 update
        mArrayList.clear();
        mAdapter.notifyDataSetChanged();


	// 서버에서 데이터 가져오라는 부분!
        GetData task = new GetData();
        task.execute( "http://" + IP_ADDRESS + ":8080/api/getProduct?userid=" + id, "");

		
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout);
        mSwipeRefreshLayout.setOnRefreshListener(this);

    }

    @Override
    public void onRefresh() { // listview swipe 했을 때

        mArrayList.clear();
        mAdapter.notifyDataSetChanged();

        GetData task = new GetData();
        task.execute( "http://" + IP_ADDRESS + ":8080/api/getProduct?userid=" + id, "");


	//새로 고침 완료!
        mSwipeRefreshLayout.setRefreshing(false);

    }


	//Json data 읽어오기
    public class GetData extends AsyncTask<String, Void, String> {

        ProgressDialog progressDialog;
        String errorString = null;

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

            progressDialog = ProgressDialog.show(home_Activity.this,
                    "Please Wait", null, true, true);
        }


        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            progressDialog.dismiss();
            Log.d(TAG, "response - " + result);

            if (result == null){

            }
            else {

                mJsonString = result;
                showResult();
            }
        }


        @Override
        protected String doInBackground(String... urls) {
            try {
                //JSONObject를 만들고 key value 형식으로 값을 저장해준다.
                JSONObject jsonObject = new JSONObject();


                HttpURLConnection con = null;
                BufferedReader reader = null;

                try{
                    URL url = new URL(urls[0]);
                    con = (HttpURLConnection) url.openConnection();
                    con.connect();

                    InputStream stream = con.getInputStream();

                    reader = new BufferedReader(new InputStreamReader(stream));

                    StringBuffer buffer = new StringBuffer();
                    
                    String line = "";
                    
                    while((line = reader.readLine()) != null){
                        buffer.append(line);
                    }

                    return buffer.toString();

                } catch (MalformedURLException e){
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if(con != null){
                        con.disconnect();
                    }
                    try {
                        if(reader != null){
                            reader.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;

        }
    }


    private void showResult(){

	// 서버에서 보내는 "user2"가 id이자 TAG_JSON이고 뒤의 세 값을 받아올 것이다. 
        String TAG_JSON = id;   //여기가 JSONArray로 받아오는 부분
        String TAG_Serial = "SerialNum";
        String TAG_NAME = "Name";
        String TAG_BRAND ="Brand";


        try {
            JSONObject jsonObject = new JSONObject(mJsonString);
            JSONArray jsonArray = jsonObject.getJSONArray(TAG_JSON);

            for(int i=0;i<jsonArray.length();i++){ // 여러 정보 받아오기!

                JSONObject item = jsonArray.getJSONObject(i);

                String name = item.getString(TAG_NAME);
                String serial = item.getString(TAG_Serial);
                String brand = item.getString(TAG_BRAND);


	//여기는 이름에 따라 url로 image 연결해주는 부분이다. 따로 포스팅 할 예정
                
                String p_name[] = {"583571 1X5CG 6775", "660195 17QDT 2582", "443496 DRWAR 9022", "AS2696 B06364 NE798", "AS2756 B06315 NF024", "AS2785 B06505 ND365"};
                String image[] = {"https://media.gucci.com/style/DarkGray_Center_0_0_800x800/1613669409/583571_1X5CG_6775_001_058_0020_Light-GG.jpg", "https://media.gucci.com/style/DarkGray_Center_0_0_650x650/1625733904/360_660195_17QDT_2582_001_100_0000_Light-.jpg",
                "https://media.gucci.com/style/DarkGray_Center_0_0_650x650/1626455703/360_443496_DRWAR_9022_001_100_0000_Light-GG-2016.jpg", "https://www.chanel.com/images/q_auto,f_auto,fl_lossy,dpr_auto/w_1920/flap-bag-black-white-tweed-aged-calfskin-aged-pale-yellow-metal-tweed-aged-calfskin-aged-pale-yellow-metal-packshot-default-as2696b06364ne798-8840481177630.jpg",
                "https://www.chanel.com/images/q_auto,f_auto,fl_lossy,dpr_auto/w_1920/e_trim:0/shopping-bag-black-white-shearling-lambskin-gold-tone-metal-shearling-lambskin-gold-tone-metal-packshot-default-as2756b06315nf024-8840469807134.jpg",
                "https://www.chanel.com/images/q_auto,f_auto,fl_lossy,dpr_auto/w_1920/flap-bag-black-pink-gray-embroidered-wool-tweed-ruthenium-finished-metal-embroidered-wool-tweed-ruthenium-finished-metal-packshot-default-as2785b06505nd365-8840473378846.jpg"};


	//PersonalData를 만들어서 보내줄 것이다.
                PersonalData personalData = new PersonalData();


	//이름에 따라 url 연결하고 personalData로 보내기
                for(int j = 0; j < p_name.length; j++){
                    if(p_name[j].equals(name)) {
                        personalData.setMember_image(image[j]);
                        break;
                    }
                    else{
                    }
                }


	//서버에서 받아온 값 보내기!
                personalData.setMember_name(name);
                personalData.setMember_brand(brand);
                personalData.setMember_serial(serial);

                mArrayList.add(personalData);
                mAdapter.notifyDataSetChanged();
            }



        } catch (JSONException e) {

            Log.d(TAG, "showResult : ", e);
        }

    }

}

 

 

 

 

 

 

여기서 personalData로 보내서 UserAdapter로 listview와 연결해 줄 것이다.

 

 

 

swipe해서 새로고침을 넣은 이유는 서버에서 listview에 update하면 새로고침해서 바뀐 부분을 받아오려고 넣었다.

 

서버로 update 해주는 부분은 여기서 보여줄 기능이 아니라서 지웠다.

 

 

 

 

 

 

 

 

personalData.class

 

 

 

public class PersonalData {
    private String member_name;
    private String member_brand;
    private String member_serial;
    private String member_image;
    private String id;

    public String getMember_name() {
        return member_name;
    }

    public String getMember_brand() {
        return member_brand;
    }

    public String getMember_serial() {
        return member_serial;
    }

    public String getMember_image() {
        return member_image;
    }

    public String get_id(){return id;}
    
    public void set_ID(String id) {this.id = id;}

    public void setMember_name(String member_name) {
        this.member_name = member_name;
    }

    public void setMember_brand(String member_brand) {
        this.member_brand = member_brand;
    }

    public void setMember_serial(String member_serial) {
        this.member_serial = member_serial;
    }

    public void setMember_image(String member_image) {
        this.member_image = member_image;
    }
}

 

 

 

 

데이터를 연결해주는 부분이다. 이 값을 UserAdapter에서 받아올 것이다.

 

 

 

 

 

 

 

 

 

UserAdapter.class

 

 

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.CustomViewHolder> {

    private ArrayList<PersonalData> mList = null;
    private Activity context = null;
    Bitmap bitmap; // 이미지 불러올 때 사용



    public UserAdapter(Activity context, ArrayList<PersonalData> list) {
        this.context = context;
        this.mList = list;
    }

    class CustomViewHolder extends RecyclerView.ViewHolder {
        protected TextView name;
        protected TextView brand;
        protected TextView serial;
        protected ImageView image;


        public CustomViewHolder(View view) {
            super(view);
            this.name = (TextView) view.findViewById(R.id.Product_Name);
            this.brand = (TextView) view.findViewById(R.id.Product_Brand);
            this.serial = (TextView) view.findViewById(R.id.Product_Serial);
            this.image = (ImageView) view.findViewById(R.id.saleImage);
        }
    }


    @Override
    public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.listview, null);
        CustomViewHolder viewHolder = new CustomViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull CustomViewHolder viewholder, int position) {

	//여기서 받아와 연결해준다.
        viewholder.name.setText(mList.get(position).getMember_name());
        viewholder.brand.setText(mList.get(position).getMember_brand());
        viewholder.serial.setText(mList.get(position).getMember_serial());


	//이미지 받아오는 부분
        Thread mThread = new Thread(){
            @Override
            public void run() {
                try{
                    URL url = new URL(mList.get(position).getMember_image());
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput(true);
                    conn.connect();

                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                } catch (MalformedURLException e){
                    e.printStackTrace();
                } catch (IOException e){
                    e.printStackTrace();
                }
            }
        };

        mThread.start();

        try{
            mThread.join();
            viewholder.image.setImageBitmap(bitmap);
        } catch (InterruptedException e){
            e.printStackTrace();
        }


    }

    @Override
    public int getItemCount() {
        return (null != mList ? mList.size() : 0);
    }

}

 

 

 

UserAdapter에서 listview.xml과 서버에서 JSON으로 받아온 값을 연결해준다.

 

 

 

 

 

 

 

결론

 

 1. 서버에서 JSON 형식으로 받아온다.

 2. JSON 형식으로 읽어온다.

 3. 읽어온걸 personalData로 보내고

 4. UserAdapter에서 읽어와 listview에 연결해준다.

 

 

 

 

 

 

 

 

포스팅 더 열심히 해야지... 화이팅!