RecyclerView와 Retrofit2를 이용하여 JsonArray 데이터를 수신하여 파싱 한 후에 필요한 데이터 목록을 만들기 위한 예제입니다.

 

 

결과 미리보기

 

준비

 

1. build.gradle(Module.app)에 retrofit2 implementation

dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    }

2. build.gradle(Module.app)에 recyclerview implementation

    implementation 'androidx.recyclerview:recyclerview:1.1.0'

 

3. AndroidManifest에 Internet Permission 추가

<uses-permission android:name="android.permission.INTERNET" />

 

 

layout

 

1. data를 띄우기 위한 RecyclerView

  <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recylerView"
        android:layout_width="320dp"
        android:layout_height="220dp"
        android:background="#000000"

        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintVertical_bias="0.05" >
    </androidx.recyclerview.widget.RecyclerView>

2. RecyclerView 에 띄울 데이터를 표시할 layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="#ffffff"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textview_number"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="100dp"
            android:text="num"
            android:textColor="#000000" />

        <TextView
            android:id="@+id/textview_price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="100dp"
            android:text="price"
            android:textColor="#000000" />
            
    </LinearLayout>
</LinearLayout>

 

java

 

1. data클래스

package com.example.userapplication.mainview.data;

import com.google.gson.annotations.SerializedName;

public class Selldata {

    @SerializedName("count")
    private int count;

    @SerializedName("price")
    private int price;

    public Selldata(int count,int price)
    {
        this.count=count;
        this.price=price;
    }

    public int getPrice() {
        return price;
    }

    public int getCount() {
        return count;
    }
}

2. dataRequest클래스

package com.example.userapplication.mainview.data;

import com.google.gson.annotations.SerializedName;

public class SelldataRequest {

    @SerializedName("ownerEmail")
    private String ownerEmail;

    @SerializedName("startDate")
    private String startDate;

    @SerializedName("endDate")
    private String endDate;

    public SelldataRequest() { 
    }

    public SelldataRequest(String ownerEmail, String startDate, String endDate) {
        this.ownerEmail=ownerEmail;
        this.startDate = startDate;
        this.endDate = endDate;
    }
}

3. dataResponse클래스

package com.example.userapplication.mainview.data;
import com.google.gson.annotations.SerializedName;
import org.json.JSONException;
import java.util.List;

public class SelldataResponse {

    @SerializedName("code")
    private int code;

    @SerializedName("resultArray")
    private List<Selldata> result_Array;

    public SelldataResponse(List<Selldata> result_array) throws JSONException {
        result_Array = result_array;
    }

    public int getCode() { return code; }
    public List getObject() { return result_Array; }
}

4. main activity

 public class SellStatusActivity extends AppCompatActivity {

 	Button mConfirm;

	private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    private List<Selldata> list=new ArrayList<>();
    private ServiceApi service;

	<생략>
    
  @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sellstatus);
        
        service = RetrofitClient.getClient().create(ServiceApi.class);
         
		getData(new SelldataRequest(saved_email,mStartDate,mEndDate));
         
        }

	<생략>
        
 	private void getData(SelldataRequest data) {
              service.ownerSellData(data).enqueue(new Callback<SelldataResponse>() {
                 @Override
                 public void onResponse(Call<SelldataResponse> call, Response<SelldataResponse> response) {
                 SelldataResponse result = response.body();
                 List<Selldata> list=new ArrayList<>();
                 if (result.getCode()==200) {
                     //count(int), price(int)
                     list.clear();
                     list = result.getObject();
                     recyclerView = (RecyclerView)findViewById(R.id.recylerView); //아이디 연결
                     recyclerView.setHasFixedSize(true); // 리사이클뷰 기존성능 강화
                     layoutManager = new LinearLayoutManager(getApplicationContext());
                     recyclerView.setLayoutManager(layoutManager);
                     adapter = new SellAdapter(list);
                     recyclerView.setAdapter(adapter); //리사이클러뷰에 어댑터 연결
                     adapter.notifyDataSetChanged();
                     //mSellCountView.setText(Integer.toString(adapter.getItemCount()));
                     //mTotalAmountView.setText(Integer.toString(getItemTotalAmount(list)));
                  }
             }

            @Override
            public void onFailure(Call<SelldataResponse> call, Throwable t) {
                Toast.makeText(SellStatusActivity.this, "에러", Toast.LENGTH_SHORT).show();
                Log.e("에러", t.getMessage());
            }
        });
    }
    
    
 }

 

 

'안드로이드' 카테고리의 다른 글

(안드로이드) [Java] DatePickerDialog  (0) 2020.07.02

사용자로부터 날짜 정보를 입력받기 위해서 DatePickerDialog를 사용할 수 있다.

날짜를 선택하는 뷰를 생성하기 위해 DatePicker를 사용할 수 도 있지만 Dialog를 띄워 사용하는 경우가 많다.

 

다음과 같이 DatePickerDialog 를 사용하였을 때 버튼을 클릭하여 Dialog를 띄우고 선택한 날짜를 표시한다.

 

 

레이아웃

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background"
    android:orientation="vertical"
    tools:context=".mainview.activity.SellStatusActivity">
    
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="기간 선택"
        android:textColor="#ffffff"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.08"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.125" />
        
          <Button
        android:id="@+id/date"
        android:layout_width="310dp"
        android:layout_height="34dp"
        android:background="#ffffff"
        android:text="선택"
        android:textColor="#000000"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.25" />
        
</androidx.constraintlayout.widget.ConstraintLayout>

 

엑티비티

import android.widget.DatePicker;
import android.app.DatePickerDialog;
import java.util.Calendar;
 Calendar c = Calendar.getInstance();
        int mYear = c.get(Calendar.YEAR);
        int mMonth = c.get(Calendar.MONTH);
        int mDay = c.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                date.setText(dayOfMonth+"/" + (month+1) + "/" + year);
            }
        }, mYear, mMonth, mDay);

        date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (date.isClickable()) {
                    datePickerDialog.show();
                }
            }
        });

 

+ Recent posts