마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

AsyncTask list를 다른 클래스에서 출력시키기

0 추천
안녕하세요 GetLocation1 class 의    Log.d("lalo", laloList.toString()); 에 출력되는 내용을

MapsActivity  class의 mMap.addPolyline((new PolylineOptions()).add(Brisbane, NewCastle, TamWorth).
에 넣어 mMap.addPolyline((new PolylineOptions()).add(laloList.toString()).

형식으로 사용하려고 합니다만 . 어떻게 하면될가요?

-----------------------------------------------------------------------------------------------------
public class GetLocation1 extends AsyncTask<String, Void, List<Lalo>> {
    OkHttpClient client = new OkHttpClient();
    
    public List<Lalo> doInBackground(String... params) {
        List<Lalo> laloList = new ArrayList<>();
        String strUrl = params[0];
        try {
            Request request = new Request.Builder()
                    .url(strUrl)
                    .build();

            Response response = client.newCall(request).execute();
            JSONArray jsonArray = new JSONArray(response.body().string());
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String num = jsonObject.getString("num");
                String email = jsonObject.getString("email");
                String lati = jsonObject.getString("lati");
                String longt = jsonObject.getString("longt");
                String time = jsonObject.getString("time");
                Lalo l = new Lalo(num, email, lati, longt, time);
                laloList.add(l);

            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return laloList;
    }

    @Override
    public void onPostExecute(List<Lalo> laloList) {
        super.onPostExecute(laloList);
        if (laloList != null) {
            Log.d("lalo", laloList.toString());

            //laloList.toString();

        }
    }

}

__________________________________________________

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private List<Marker> mMarkers = new ArrayList<>();
    private Polyline mPolyline;

 

    private GoogleMap mMap;
    private ActivityMapsBinding binding;

    // below are the latitude and longitude of 4 different locations.
    LatLng TamWorth = new LatLng(-31.083332, 150.916672);
    LatLng NewCastle = new LatLng(-32.916668, 151.750000);
    LatLng Brisbane = new LatLng(-27.470125, 153.021072);

 

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        GetLocation1 getLocation1 = new GetLocation1();
        getLocation1.execute("https://json address");

        Log.d("www", "2: ");

 

 

        binding = ActivityMapsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

 

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */

    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        // inside on map ready method
        // we will be displaying polygon on Google Maps.
        // on below line we will be adding polyline on Google Maps.
        mMap.addPolyline((new PolylineOptions()).add(Brisbane, NewCastle, TamWorth).
                // below line is use to specify the width of poly line.
                        width(5)
                // below line is use to add color to our poly line.
                .color(Color.RED)
                // below line is to make our poly line geodesic.
                .geodesic(true));
        // on below line we will be starting the drawing of polyline.
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Brisbane, 13));
    }

}
오필리아 (750 포인트) 님이 2022년 12월 4일 질문

1개의 답변

+1 추천
 
채택된 답변

GetLocation1에 콜백을 사용해 보세요. 아래처럼 Listener 인터페이스를 추가하고 외부에서 설정할 수 있도록 해줍니다.
onPostExecute에서 작업이 완료되면 listener를 통해 작업이 완료되었음을 알려줍니다.

public class GetLocation1 extends AsyncTask<String, Void, List<Lalo>> {
     public interface Listener {
          void onCompleted(List<Lalo> laloList);
          void onError(Exception e);
     }


    private Listener listener;
    public void setListener(Listener listener) {
         this.listener = listener;
   }

    ....


    @Override
    public void onPostExecute(List<Lalo> laloList) {
        super.onPostExecute(laloList);
        Log.d("lalo", laloList.toString());
        if (listener != null) {
            listener.onCompleted(laloList);
        }
    }
}


MapsActivity에서는 Listener를 넘겨주고 사용하면 됩니다.
 

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GetLocation1.Listener {

    ...
 

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        GetLocation1 getLocation1 = new GetLocation1();
        getLocation1.setListener(this);

        ...
    }

 
    @Override
    public void onCompleted(List<Lalo> laloList) {
          // 필요한 작업 
    }

    @Override
    public void onError(Exception e) {
        // 에러처리
    }
}

 

코드에서는 onError 메소드는 실제로 사용되지 않고 있는데, GetLocation1에서 에러가 발생할 때 적절하게 처리하시기 바랍니다. 그리고 doInBackground에서 무조건 리스트를 리턴하므로 onPostExecute에서 널 체크는 아무런 의미가 없어 보이네요.

 

spark (226,420 포인트) 님이 2022년 12월 4일 답변
오필리아님이 2022년 12월 5일 채택됨
참고로 OkHttpClient를 AsysncTask로 감싸서 사용해도 되지만 Retrofit + OkHttp3 + Gson Adapter 를 사용하시는게 쓸데없는 코드를 더 작성할 필요가 없고 가독성도 더  좋아 보입니다.
spark 님의 답변에 항상 감사 드립니다.
그동안 많은 답변에 저의 발전이 느껴집니다.~~
...