728x90

이전 코드 구현에서 Gson 라이브러리를 사용하여 코드를 변경하는 부분이 핵심이다.


package com.link2me.android.recyclerviewjava.model

import android.os.Parcelable
import kotlinx.android.parcel.Parcelize

@Parcelize
data class Address_Item (
    // 결과를 받을 모델, 코틀린 혼용하다보니 코틀린의 문법 적용을 받게되어 null 처리를 조심해야 하더라.
    var uid: String="",
    var userNM: String="",
    var mobileNO: String?=null,
    var telNO: String?=null,
    var photo: String?=null,
    var checkBoxState: Boolean
): Parcelable


package com.link2me.android.recyclerviewjava;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.RelativeLayout;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.link2me.android.recyclerviewjava.adapter.RecyclerViewAdapter;
import com.link2me.android.recyclerviewjava.model.Address_Item;
import com.link2me.android.recyclerviewjava.model.DataCommAPI;

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

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {
    private final String TAG = this.getClass().getSimpleName();
    Context context;

    private ArrayList<Address_Item> addressItemList = new ArrayList<>(); // 서버 원본 데이터 리스트
    private ArrayList<Address_Item> searchItemList = new ArrayList<>(); // 검색한 데이터 리스트
    private RecyclerView mRecyclerView;
    private RecyclerViewAdapter mAdapter;
    private SearchView editsearch;

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

        initView();
    }

    private void initView() {
        // Adapter에 추가 데이터를 저장하기 위한 ArrayList
        getServerData(Value.IPADDRESS+"getJSONData.php"); // 서버 데이터 가져오기
    }

    private void getServerData(String SERVER_URL) {
        HashMap<String, String> params = new HashMap<>();
        params.put("keyword", Value.encrypt(Value.URLkey()));
        JSONObject jsonObject = new JSONObject(params);

        // 1. RequestQueue 생성 및 초기화
        RequestQueue requestQueue = Volley.newRequestQueue(context);

        // 2. Request Obejct인 StringRequest 생성
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, SERVER_URL,jsonObject,
                (Response.Listener<JSONObject>) response -> {
                    Log.e("result", "" + response);
                    try {
                        if(response.getString("status").equals("success")){
                            String jsondata = response.getString("addrinfo");
                            showJSONList(jsondata);
                        } else {
                            showAlert(response.getString("status"),response.getString("message"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                },
                error -> Log.d("error", "[" + error.getMessage() + "]")) {

        };

        // 3) 생성한 StringRequest를 RequestQueue에 추가
        requestQueue.add(request);
    }

    private void showJSONList(String JSONdata) {
        try {
            JSONArray peoples = new JSONArray(JSONdata); // [] 대괄호
            addressItemList.clear(); // 서버에서 가져온 데이터 초기화

            Gson gson = new Gson();
            Type listType = new TypeToken<ArrayList<Address_Item>>(){}.getType();
            addressItemList = gson.fromJson(peoples.toString(),listType);
            searchItemList = gson.fromJson(peoples.toString(),listType);

            mRecyclerView = findViewById(R.id.address_listview);
            mAdapter = new RecyclerViewAdapter(context,addressItemList);
            LinearLayoutManager manager = new LinearLayoutManager(context);
            DividerItemDecoration decoration = new DividerItemDecoration(context,manager.getOrientation());

            mRecyclerView.addItemDecoration(decoration);
            mRecyclerView.setLayoutManager(manager);
            mRecyclerView.setAdapter(mAdapter);


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

    public void showAlert(String title, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(title);
        builder.setMessage(message)
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.dismiss();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    public void onBackPressed() {
        backPressHandler.onBackPressed();
    }
}


728x90
블로그 이미지

Link2Me

,