>

AsyncTask를 사용하여 서버를 호출하고 어댑터를 사용하여 목록보기 에서이 목록을 설정 한 후 서버에서 100 개 이상의 객체 목록을 가져 오는 MainActivity가 있습니다. 이번에 어떤 작업 앱을 수행하면 ANR이 표시되고 몇 번 후에 앱이 정상적으로 작동하면 해당 페이지를 다시 열고 동일한 작업을 수행하면 동일한 문제가 발생합니다.

참고 : AsyncTask를 사용하여 서버에서 객체를 가져옵니다. 백그라운드에서이 작업을 수행하는 데 시간이 더 걸리는 listView 어댑터 설정 이것을 피하기 위해 몇 가지 제안을 해주세요.

어댑터 코드 :

public abstract class MatchedRegularUsersAdapter extends BaseAdapter
{
    private final static String LOG_TAG = MatchedRegularUsersAdapter.class.getName();
    private LayoutInflater inflater = null;
    protected final List<MatchedRegularUser> availableMatches;
    protected Ride ride;
    protected final AppCompatActivity  activity;
    private boolean isConnectedMatch=false;
    private Drawable defaultFeMale,defaultMale;
    private List<MatchedRegularUser> matchedRegularUser = new ArrayList<>();
    private Map<Integer,UserHolder> userHolderMap = new HashMap<>();
    protected LongSparseArray<MatchedUserCachedDetails> cachedDetailsMap = new LongSparseArray<>();
    protected MatchedUsersDisplayActivity MatchedRegularUsersDisplayActivity ;
    protected MatchedRegularUsersAdapter(AppCompatActivity  activity, List<MatchedRegularUser> availableMatches,Ride ride,boolean isConnectedMatch)
    {
        super();
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.availableMatches = availableMatches;
        this.ride = ride;
        this.activity = activity;
        this.isConnectedMatch = isConnectedMatch;
    }
    @Override
    public int getCount()
    {
        return availableMatches.size();
    }
    @Override
    public MatchedRegularUser getItem(int index)
    {
        return availableMatches.get(index);
    }
    @Override
    public long getItemId(int position)
    {
        return position;
    }
    @Override
    public View getView(final int position, View convertView, ViewGroup parent)
    {
        View view = convertView;
        final UserHolder userHolder;
        try
        {
            if (view == null) {
                view = inflater.inflate(R.layout.row_regular_user_new, parent, false);
                userHolder = new UserHolder();
                userHolder.startLocation = (TextView) view.findViewById(R.id.regular_start_location_user);
                userHolder.endLocation = (TextView) view.findViewById(R.id.regular_end_location_user);
                userHolder.time = (TextView) view.findViewById(R.id.timeResults);
                userHolder.points = (TextView) view.findViewById(R.id.actual_fare);
                userHolder.pointsTv = (TextView)view.findViewById(R.id.points_textview);
                userHolder.pointsLayout = (LinearLayout)view.findViewById(R.id.points_layout);
                userHolder.userImage = (ImageView) view.findViewById(R.id.regular_userImageResults);
                userHolder.userName = (TextView) view.findViewById(R.id.regular_usernameResults);
                userHolder.pickUpTimeLayout = (LinearLayout)view.findViewById(R.id.user_trip_time_layout);
                userHolder.verificationStatusImageView = (ImageView) view.findViewById(R.id.verification_status_imageView);
                userHolder.companyNameTextView = (TextView) view.findViewById(R.id.companyNameTextView);
                userHolder.ratingLinearLayout = (LinearLayout) view.findViewById(R.id.ratingLinearLayout);
                userHolder.userRating = (ImageView) view.findViewById(R.id.regular_userratingResults);
                userHolder.noOfReviewsTv = (TextView) view.findViewById(R.id.noOfReviewsTv);
                userHolder.amOrPM = (TextView) view.findViewById(R.id.timeAMorPM);
                userHolder.vehicleModelIcon = (ImageView) view.findViewById(R.id.matched_user_vehicle_model_icon);
                userHolder.rideStatusTextView = (TextView) view.findViewById(R.id.rideStatusTV);
                userHolder.matchedPerTextView = (TextView) view.findViewById(R.id.matchingPerTextView);
                userHolder.percentageLayout = (LinearLayout) view.findViewById(R.id.percentageLayout);
                userHolder.lastRideCreatedTimeTextView = (TextView)view.findViewById(R.id.lastRideCreatedTime);
                userHolder.noOfSeatsAndInvitedLayout = (LinearLayout) view.findViewById(R.id.noOfSeatsAndInvitedLayout);
                userHolder.noOfSeatsTextView = (TextView) view.findViewById(R.id.noOfSeatsTextView);
                userHolder.seatsTextView = (TextView) view.findViewById(R.id.seats_textview);
                userHolder.longDistanceDateTv=(TextView)view.findViewById(R.id.long_distance_date);
                userHolder.callOptionLayout=(LinearLayout)view.findViewById(R.id.call_image_layout);
                userHolder.callImageLayout=(ImageView) view.findViewById(R.id.call_image);
                userHolder.favouriteUserIcon = (ImageView)view.findViewById(R.id.fav_user_icon);
                userHolder.verifiedStatus = (LinearLayout) view.findViewById(R.id.verification_layout);
                userHolder.startDate = (LinearLayout) view.findViewById(R.id.startDate);
                userHolder.endDate = (LinearLayout) view.findViewById(R.id.endtDate);
                userHolder.fromDate = (TextView) view.findViewById(R.id.regular_matched_fromDate);
                userHolder.toDate = (TextView) view.findViewById(R.id.regular_matched_toDate);
                userHolder.toDateLabel = (TextView) view.findViewById(R.id.regular_matched_toDate_label);
                userHolder.weekdaysLytLayout = (HorizontalScrollView) view.findViewById(R.id.regular_week_days_layout);
                userHolder.weekdaysLyt = (LinearLayout) view.findViewById(R.id.regular_week_day_view);
                userHolder.sendInviteLyt = (LinearLayout) view.findViewById(R.id.regular_send_invite_lyt);
                userHolder.actionLabel = (TextView) view.findViewById(R.id.regular_send_invite_text);
                userHolder.moreDetail = (LinearLayout) view.findViewById(R.id.moreDetailsLayout);
                userHolder.moreDetailsTv = (TextView) view.findViewById(R.id.more_details);
                userHolder.moreDetailImage = (ImageView) view.findViewById(R.id.arrow_down_image);
                userHolder.wholeWeekdaysLayout = (LinearLayout) view.findViewById(R.id.weekdaysLayout);
                userHolder.rideNote = (LinearLayout)view.findViewById(R.id.ride_note_layout);
                view.setTag(userHolder);
            } else {
                userHolder = (UserHolder) view.getTag();
            }
            final MatchedRegularUser userInfo = availableMatches.get(position);
            userHolder.startLocation.setText(LocationClientUtils.getConsolidatedNameFromFormattedAddressForLocationAlert(userInfo.getFromLocationAddress()));
            userHolder.endLocation.setText(LocationClientUtils.getConsolidatedNameFromFormattedAddressForLocationAlert(userInfo.getToLocationAddress()));
            userHolder.userImage.setId(position);
            userHolder.userName.setText(userInfo.getName());
            setRatingAndNoOfReviews(userHolder, userInfo);
            setRideTime(userHolder, userInfo);
            setVerificationStatusDetails(userHolder, userInfo,view);
            setUsersImage(userHolder, userInfo);
            setVehicleDetails(userHolder, userInfo);
            setPointsTextViewAndColors(userHolder,userInfo,position,view);
            setNoOfSeatsOrOnTime(userHolder,userInfo);
            setFavouriteUserIndication(userHolder,userInfo);
            setRideNote(userHolder,userInfo);
            setActionLayout(userHolder.actionLabel);
            userHolder.sendInviteLyt.setId(position);
            userHolder.sendInviteLyt.setOnClickListener(inviteOnClickListener);
            setBackgroundAndLastRideCreatedTimeIfRequired(view, userHolder, userInfo);

            setMatchedPercentageText(userHolder, userInfo);
            setWeekDays(userHolder.weekdaysLyt, userInfo);
            userHolder.fromDate.setText(DateUtils.getDateWithOutSpecialChars(userInfo.getMatchedFromDate()));
            if (userInfo.getMatchedToDate() == null) {
                userHolder.endDate.setVisibility(View.GONE);
                userHolder.toDate.setVisibility(View.GONE);
            } else {
                userHolder.toDate.setText(DateUtils.getDateWithOutSpecialChars(userInfo.getMatchedToDate()));
            }
            if(isConnectedMatch)
            {
                userHolder.moreDetail.setVisibility(View.GONE);
                userHolder.wholeWeekdaysLayout.setVisibility(View.VISIBLE);
            }
            userHolder.moreDetail.setId(position);
            userHolder.moreDetail.setTag(position);
            userHolder.moreDetail.setOnClickListener(moreOnClickListener);
            userHolderMap.put(position,userHolder);
            checkForSelectedUser(userInfo,userHolder);


        }
        catch (Throwable th)
        {
            Log.e(LOG_TAG,"getView() failed",th);
        }
        return view;
    }
    private final View.OnClickListener moreOnClickListener = new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            try {
                UserHolder userHolder = userHolderMap.get(v.getId());
                MatchedRegularUser matchedRegularuser = availableMatches.get(v.getId());
                if(!matchedRegularUser.contains(matchedRegularuser))
                {
                    userHolder.moreDetailImage.setImageDrawable(activity.getResources().getDrawable(R.drawable.dropdown_close_3x));
                    userHolder.moreDetailsTv.setText("Less");
                    userHolder.wholeWeekdaysLayout.setVisibility(View.VISIBLE);
                    matchedRegularUser.add(matchedRegularuser);
                    refreshAdapter();
                }
                else
                {
                    userHolder.wholeWeekdaysLayout.setVisibility(View.GONE);
                    userHolder.moreDetailsTv.setText("More");
                    userHolder.moreDetailImage.setImageDrawable(activity.getResources().getDrawable(R.drawable.dropdown_3x));
                    matchedRegularUser.remove(matchedRegularuser);
                    refreshAdapter();
                }

            }catch (Throwable th)
            {
                Log.i(LOG_TAG, "inside moreOnclickListener");
            }
        }
    };
    private void setMatchedPercentageText(UserHolder userHolder, MatchedRegularUser userInfo)
    {
        if(isConnectedMatch)
        {
            userHolder.percentageLayout.setVisibility(View.GONE);
        }
        else {
            userHolder.matchedPerTextView.setVisibility(View.VISIBLE);
            if ((MatchedRegularUser.REGULAR_PASSENGER.equalsIgnoreCase(userInfo.getUserRole())) && userInfo.getMatchPercentageOnMatchingUserRoute() != 0) {
                userHolder.matchedPerTextView.setText(userInfo.getMatchPercentage() + "%" + " (" + userInfo.getMatchPercentageOnMatchingUserRoute() + "%)");
            } else {
                userHolder.matchedPerTextView.setText(userInfo.getMatchPercentage() + "%");
            }
        }
    }
    private  void setNoOfSeatsOrOnTime(UserHolder userHolder, MatchedUser userInfo)
    {
        if(userInfo instanceof MatchedRegularUser)
        {
            if(((MatchedRegularUser)userInfo).getUserOnTimeComplianceRating()==null){
                userHolder.noOfSeatsAndInvitedLayout.setVisibility(View.INVISIBLE);
            }else {
                userHolder.noOfSeatsTextView.setText(((MatchedRegularUser)userInfo).getUserOnTimeComplianceRating()+"%");
                userHolder.noOfSeatsTextView.setSingleLine();
                userHolder.seatsTextView.setText("On Time");
                // userHolder.seatTextview.setTextColor(activity.getResources().getColor(R.color.fav_footer_bg_one));
            }
        }
        if(isConnectedMatch){
            userHolder.noOfSeatsAndInvitedLayout.setVisibility(View.GONE);
        }
    }
    private void setPointsTextViewAndColors(final UserHolder userHolder, MatchedRegularUser userInfo, int position, View view)
    {
        if(isConnectedMatch)
        {
            userHolder.pointsLayout.setVisibility(View.GONE);
        }
        else {
            userHolder.points.setVisibility(View.VISIBLE);
            double pointsToShow = userInfo.getPoints();
            userHolder.points.setText(String.valueOf(StringUtil.getPointsWithTwoDecimal(pointsToShow)));
        }
    }

    public  void navigateToProfile(MatchedRegularUser MatchedRegularUser) {
        boolean isContactOptionRequired =true;
        if (!RideViewUtils.getUserQualifiedToDisplayContact()) {
            isContactOptionRequired = false;
        }
        Intent viewIntent = new Intent(activity, ActivityUtils.getProfileDisplayClass(QuickRideApplication.getApplicationName(QuickRideApplication.getInstance().getApplicationContext())));
        viewIntent.putExtra(ProfileDisplayActivity.USER_ID, String.valueOf( MatchedRegularUser.getUserid()));
        viewIntent.putExtra(ProfileDisplayActivity.IS_JOIN_ACTION_REQUIRED, false);
        viewIntent.putExtra(ProfileDisplayActivity.IS_CONTACT_LAYOUT_REQUIRED, isContactOptionRequired);
        MatchedRegularUsersDisplayActivity.startActivity(viewIntent);
    }
    private void setImageAndTextColorsBasedOnMatchedRegularUser(UserHolder userHolder,MatchedRegularUser userInfo)
    {
        if(userInfo.getRideid()==0)
        {
            userHolder.userImage.setAlpha((float)0.5);
            userHolder.userName.setTextColor(activity.getResources().getColor(R.color._9B9B9B));
            userHolder.startLocation.setTextColor(activity.getResources().getColor(R.color._9B9B9B));
            userHolder.endLocation.setTextColor(activity.getResources().getColor(R.color._9B9B9B));
        }
        else
        {
            userHolder.userImage.setAlpha((float)1);
            userHolder.userName.setTextColor(activity.getResources().getColor(R.color._5050550));
            userHolder.startLocation.setTextColor(activity.getResources().getColor(R.color._363636));
            userHolder.endLocation.setTextColor(activity.getResources().getColor(R.color._363636));
        }
    }
    private void setBackgroundAndLastRideCreatedTimeIfRequired(View view,UserHolder userHolder,MatchedRegularUser userInfo)
    {
        if(userInfo.getRideid()==0)
        {
            view.setBackground(activity.getResources().getDrawable(R.drawable.listview_grey_selector));
            userHolder.lastRideCreatedTimeTextView.setVisibility(View.VISIBLE);
            userHolder.lastRideCreatedTimeTextView.setText(getTextForLastRideCreated(userInfo.getLastRideCreatedTime()));
        }
        else
        {
            view.setBackground(activity.getResources().getDrawable(R.drawable.listview_selector));
            userHolder.lastRideCreatedTimeTextView.setVisibility(View.GONE);
            userHolder.lastRideCreatedTimeTextView.setText(null);
        }
    }
    private String getTextForLastRideCreated(Date lastRideCreatedTime)
    {
        Date currentDate = new Date();
        int dateDifference = 1;
        if(lastRideCreatedTime !=null && lastRideCreatedTime.getTime() < currentDate.getTime())
        {
            dateDifference = DateUtils.calculateTimeDifferenceBetweenDatesInDays(currentDate,lastRideCreatedTime);
            if(dateDifference <1)
            {
                dateDifference = 1;
            }
        }
        String text = activity.getResources().getString(R.string.last_ride_created);
        if(dateDifference ==1)
        {
            text = text+dateDifference+activity.getResources().getString(R.string.day_ago);
        }
        else
        {
            text = text+dateDifference+activity.getResources().getString(R.string.days_ago);
        }
        return text;
    }
    private void setActionLayout( TextView actionLabel)
    {
        if(isConnectedMatch)
        {
            actionLabel.setText(activity.getString(R.string.remove));
        }
        else
        {
            actionLabel.setText(activity.getString(R.string.send_invite));
        }
    }
    private void setUsersImage(final UserHolder userHolder, MatchedRegularUser userInfo)
    {
        Log.i(LOG_TAG, "setting of users image");
        if(userInfo == null)
        {
            if(activity != null && !activity.isFinishing())Toast.makeText(activity,activity.getResources().getString(R.string.unableToProcess),Toast.LENGTH_SHORT).show();
            return;
        }
        ImageCache imageCache = ImageCache.getInstance();
        if(imageCache == null || userInfo.getImageURI()==null)
        {
            getDefaultUserImageForGuest(userHolder.userImage,userInfo);
        }
        else
        {getDefaultUserImageForGuest(userHolder.userImage, userInfo);
            if(userInfo.getImageURI() != null && !userInfo.getImageURI().isEmpty())
            {
                imageCache.getUserImage(userInfo.getImageURI(), userInfo.getGender(), ImageCache.SSIZE, userHolder.userImage, null,String.valueOf(userInfo.getUserid()),false);
            }
        }
    }
    private void getDefaultUserImageForGuest(ImageView userImageView, MatchedRegularUser userInfo)
    {..
    }
    private final View.OnClickListener inviteOnClickListener = new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            final MatchedRegularUser matchedRegularUser= availableMatches.get(v.getId());
            if(matchedRegularUser == null) return;
            if(isConnectedMatch)
            {
                QuickRideModalDialog.displayConfirmationsDialog(activity, activity.getResources().getString(R.string.confirm_cancel_title), new QuickRideModalDialog.ModelDialogActionListener() {
                    @Override
                    public void doPrimaryAction() {
                        onRemoveClick(matchedRegularUser);
                    }
                    @Override
                    public void doSecondaryAction() {
                    }
                });
            }
            else
            {
                onInviteClick(matchedRegularUser);
            }
        }
    };

    private void setFavouriteUserIndication(UserHolder userHolder, MatchedRegularUser MatchedRegularUser)
    {
        if(UserDataCache.getCacheInstance().isFavouritePartner(MatchedRegularUser.getUserid()))
        {
            userHolder.favouriteUserIcon.setVisibility(View.VISIBLE);
        }else {
            userHolder.favouriteUserIcon.setVisibility(View.GONE);
        }
    }
    private void setVerificationStatusDetails(UserHolder userHolder, MatchedRegularUser userInfo, View view)
    {
    }
    private void setRideTime(final UserHolder userHolder, final MatchedRegularUser userInfo)
    {     if(isConnectedMatch)
    {
        userHolder.pickUpTimeLayout.setVisibility(View.GONE);
    }
    else if(userInfo instanceof MatchedRegularPassenger && userInfo.getPassengerReachTimeToPickup() != null){
        userHolder.time.setText(DateUtils.getTimeStringFromDateForSingleDigitForHours(
                userInfo.getPassengerReachTimeToPickup()));
        userHolder.amOrPM.setText(DateUtils.getTimeStringFromDateOnlyMeridian(userInfo.getPassengerReachTimeToPickup()));

    }else{
        userHolder.time.setText(DateUtils.getTimeStringFromDateForSingleDigitForHours(
                userInfo.getPickupTime()));
        userHolder.amOrPM.setText(DateUtils.getTimeStringFromDateOnlyMeridian(
                userInfo.getPickupTime()));
    }
        LinearLayout.LayoutParams pickUpLayout = (LinearLayout.LayoutParams) userHolder.pickUpTimeLayout.getLayoutParams();
        LinearLayout.LayoutParams rateLayout = (LinearLayout.LayoutParams) userHolder.ratingLinearLayout.getLayoutParams();
    }
    private void setRatingAndNoOfReviews(UserHolder userHolder, MatchedRegularUser userInfo)
    {
    }
    private void setVehicleDetails(UserHolder userHolder, MatchedRegularUser userInfo)
    {
        if(userInfo instanceof MatchedRegularRider)
        {
        }
        else
        {
            userHolder.vehicleModelIcon.setVisibility(View.INVISIBLE);
        }
    }
    protected abstract void onInviteClick(MatchedRegularUser matchedRegularUser);
    protected abstract void onRemoveClick(MatchedRegularUser matchedRegularUser);
    protected abstract void completeInvite(MatchedRegularUser matchedRegularUser);
    private void setWeekDays(LinearLayout weekDays,MatchedRegularUser MatchedRegularUser)
    {
        ....
    }
   private void checkForSelectedUser(MatchedRegularUser matchedRegularuser, UserHolder userHolder)
    {           
        if(isConnectedMatch)
        {
            userHolder.moreDetail.setVisibility(View.GONE);
            userHolder.wholeWeekdaysLayout.setVisibility(View.VISIBLE);
        }
    }
   private void refreshAdapter()
    {
        if(activity !=null && activity instanceof CommonMapActivity)
        {
            CommonMapActivity commonMapActivity = (CommonMapActivity)activity;
            ..
        }
    }
    private boolean checkForMoreDetailsClicked(MatchedRegularUser matchedRegularuser,List<MatchedRegularUser> matchedRegularUser) {
        ..
        return isMatchedUserPresent;
    }
    private void addWeekDayView(Time timeOfDay,String nameOfDay,LinearLayout weekDays)
    {
        ......
    }
   static class UserHolder
    {
        ImageView userImage,moreDetailImage,favouriteUserIcon,userRating,verificationStatusImageView,vehicleModelIcon,callImageLayout;
        TextView userName, startLocation, endLocation,fromDate,toDate,actionLabel,toDateLabel,noOfReviewsTv,companyNameTextView,amOrPM,time,noOfSeatsTextView,seatsTextView;
        LinearLayout rideNote,wholeWeekdaysLayout,weekdaysLyt,startDate,endDate,sendInviteLyt,verifiedStatus,moreDetail,ratingLinearLayout,pickUpTimeLayout,percentageLayout,noOfSeatsAndInvitedLayout,pointsLayout,callOptionLayout;
        HorizontalScrollView weekdaysLytLayout;
        TextView longDistanceDateTv,moreDetailsTv,lastRideCreatedTimeTextView,points,pointsTv,rideStatusTextView,matchedPerTextView,sendInviteTextView;
    }
}

MainActivity.java

...

matchinglist.setOnclickListener(new onClickListener)
{
setAdapter();
...
}

  • 답변 # 1

    문제점은 애플리케이션이 모든 항목을 한 번에 처리하려고하는 것입니다.

    먼저 listview 대신 recyclerView를 사용하십시오. RecyclerView와 ListView

    두 번째로 응용 프로그램에 페이지 매김을 추가하십시오 https://developer.android.com/topic/libraries/architecture/paging/

관련 자료

  • 이전 html - mysql에서 가져온 값 선택
  • 다음 decimal point - 08이 아닌 08의 C # 수학 라운드