Ad

I Am Getting The Items In Listview Repeated . Here Is My Sample Code I Am Unable To Find The Bug In My Code ! Can Anyone Help Me Out Please?

- 1 answer

    //this is JOBListAdapter class

    package com.example.hellotest.adapters;

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.List;
    import java.util.Locale;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.TextView;

    import com.example.hellotest.R;
    import com.example.hellotest.model.Job;

    public class JobListAdapter extends BaseAdapter {

        private LayoutInflater mInflater ;
        private List<Job> mJobs;
        private SimpleDateFormat mDateFormat;
        private SimpleDateFormat mInputFormat;
        private String mPosterPrefix;

        public JobListAdapter(Context context) {
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mDateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US);
            mInputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.US);
            mPosterPrefix = context.getString(R.string.job_posted_by);
        }

        public void setJobList(List<Job> jobs) {
            mJobs = jobs;
        }

        @Override
        public int getCount() {
            if(null != mJobs) {
                return mJobs.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return mJobs.get(position);
        }

        @Override
        public long getItemId(int position) {
            return mJobs.get(position).getId();
        }
    //this is the method where I think that the problem is please somebody tell me.
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if(null == convertView) {
                convertView = mInflater.inflate(R.layout.job_list_row, null);
                holder = new ViewHolder();
                holder.created = (TextView) convertView.findViewById(R.id.job_listing_date);
                holder.location = (TextView) convertView.findViewById(R.id.job_listing_location);
                holder.title = (TextView) convertView.findViewById(R.id.job_listing_title);
                holder.experience = (TextView) convertView.findViewById(R.id.job_listing_experience);
                holder.poster = (TextView) convertView.findViewById(R.id.job_listing_posted_by);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }



            updateRow(holder, mJobs.get(position));
            return convertView;
        }

        private void updateRow(ViewHolder holder, Job job) {
            holder.title.setText(job.getTitle());
            int id = job.isPremium() ? R.drawable.icon_premium : 0;
            holder.created.setText(getDate(job.getCreated()));
            holder.created.setCompoundDrawablesWithIntrinsicBounds(0, 0, id, 0);
            holder.experience.setText(job.getExperience());
            holder.location.setText(job.getLocation());
            holder.poster.setText(mPosterPrefix + job.getPoster());
        }

        private CharSequence getDate(String created) {
            try {
                return mDateFormat.format(mInputFormat.parse(created));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return created;
        }

        private static class ViewHolder {
            TextView created;
            TextView title;
            TextView location;
            TextView experience;
            TextView poster;
        }

    }

   // layout for fragmentjob_listing even I make the listview height to fill_parent as suggested when      I googled the solution for the issue.

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

        <LinearLayout
            android:id="@+id/job_listing_filter_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/job_listing_tab_bg"
            android:gravity="center_vertical"
            android:minHeight="48dp" >

            <TextView
                android:id="@+id/job_listing_experience"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/selector_job_listing_tab"
                android:clickable="true"
                android:gravity="center"
                android:text="@string/job_listing_experience" />

            <ImageView
                android:id="@+id/space2"
                android:layout_width="1dp"
                android:layout_height="match_parent"
                android:contentDescription="@string/app_name"
                android:scaleType="fitXY"
                android:src="@drawable/job_listing_horizontal_divider" />

            <TextView
                android:id="@+id/job_listing_location"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/selector_job_listing_tab"
                android:clickable="true"
                android:gravity="center"
                android:text="@string/job_listing_location" />
        </LinearLayout>

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:contentDescription="@string/app_name"
            android:scaleType="fitXY"
            android:src="@drawable/job_listing_divider" />

        <TextView
            android:id="@+id/job_listing_message"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:gravity="center"
            android:visibility="gone"/>

        <ListView
            android:id="@+id/job_list"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"> 
        </ListView>

    </LinearLayout>

   // JobListingFragment Class where the joblistAdapter class called up

    package com.example.hellotest;

    import java.util.List;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.text.TextUtils;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.ViewGroup;
    import android.widget.AbsListView;
    import android.widget.AbsListView.OnScrollListener;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListView;
    import android.widget.ProgressBar;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.android.volley.Request.Method;
    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.Response.ErrorListener;
    import com.android.volley.Response.Listener;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.Volley;
    import com.example.hellotest.R;
    import com.example.hellotest.adapters.JobListAdapter;
    import com.example.hellotest.config.Constant;
    import com.example.hellotest.io.CookieStringRequest;
    import com.example.hellotest.io.json.JobsProcessor;
    import com.example.hellotest.model.Job;
    import com.example.hellotest.model.JobList;
    import com.example.hellotest.model.Pagination;
    import com.example.hellotest.tasks.JsonParserTask;
    import com.example.hellotest.tasks.JsonParsingListener;
    import com.example.hellotest.util.AccountUtils;
    import com.example.hellotest.util.Log;

    public class JobListingFragment extends Fragment {

        public static final String ARG_URL = "argument_url";
        public static final String ARG_IS_FILTER_ON = "argument_is_filtered";
        public static final String ARG_IS_DEFAULT_JOB_LIST = "argument_is_default_job_list";
        public static final String ARG_EMPTY_MESSAGE = "argument_empty_message";

        protected static final int REQUEST_EXPERIENCE = 0x11;
        protected static final int REQUEST_LOCATION = 0x12;
        private ListView mJobsList;
        private TextView mMessageView;
        private JobListAdapter mAdapter;
        private List<Job> mJobs;
        private Pagination mPagination;
        private boolean mIsFetching;
        private boolean mIsDefaultList;
        private boolean mIsFilterOn;
        private String mUrl;
        private String mLocId;
        private int mExperienceId = -1;
        private ProgressBar mFooterProgress;
        private Log mLogger = new Log(JobListingFragment.class);
        private Object mRequestTag = new Object();
        private RequestQueue mRequestQueue;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mAdapter = new JobListAdapter(getActivity());
            if (null != savedInstanceState) {
                getState(savedInstanceState);
            } else {
                getState(getArguments());
            }
    //      init();
        }

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            mRequestQueue = Volley.newRequestQueue(getActivity());
        }

        @Override
        public void onDetach() {
            mRequestQueue.cancelAll(mRequestTag);
            super.onDetach();
        }

        @Override
        public void onResume() {
            init();
            super.onResume();
        }

        private void getState(Bundle bundle) {
            mUrl = bundle.getString(ARG_URL);
            mIsFilterOn = bundle.getBoolean(ARG_IS_FILTER_ON);
            mIsDefaultList = bundle.getBoolean(ARG_IS_DEFAULT_JOB_LIST);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            View view = inflater.inflate(R.layout.fragment_job_listing, null);
            mJobsList = (ListView) view.findViewById(R.id.job_list);
            mMessageView = (TextView) view.findViewById(R.id.job_listing_message);
            return view;
        }

        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
            View footer = getLayoutInflater(savedInstanceState).inflate(R.layout.paginated_list_footer, null);
            mFooterProgress = (ProgressBar) footer.findViewById(R.id.footer_progress);
            if (!mIsFilterOn) {
                view.findViewById(R.id.job_listing_filter_container).setVisibility(View.GONE);
            } else {
                view.findViewById(R.id.job_listing_experience).setOnClickListener(mOnClickListener);
                view.findViewById(R.id.job_listing_location).setOnClickListener(mOnClickListener);
            }
            mJobsList.addFooterView(footer);
            mJobsList.setAdapter(mAdapter);
            mJobsList.setOnScrollListener(mOnScrollListener);
            mJobsList.setOnItemClickListener(mOnItemClickListener);
            super.onViewCreated(view, savedInstanceState);
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            outState.putString(ARG_URL, mUrl);
            outState.putBoolean(ARG_IS_FILTER_ON, mIsFilterOn);
            outState.putBoolean(ARG_IS_DEFAULT_JOB_LIST, mIsDefaultList);
            super.onSaveInstanceState(outState);
        }

        public void startAfresh(String url, boolean isPaginated) {
            mLogger.d("old fragment reused");
            mIsFilterOn = true;
            mUrl = url;
            reset();
            init();
        }

        private void init() {
            mLocId = AccountUtils.getLocationFilter();
            mExperienceId = AccountUtils.getExperienceFilter();
            String url = getUrl(1);
            fetchJobs(url);

        }

        private void reset() {
            mJobs = null;
            mPagination = null;
            mAdapter.setJobList(null);
            mAdapter.notifyDataSetChanged();
        }

        private String getUrl(int pageNumber) {
            String appender = "";
            if (mIsFilterOn) {
                if (null != mLocId || -1 < mExperienceId) {
                    if (null != mLocId) {
                        appender += "/loc-" + mLocId;
                    } else {
                        appender += "/loc-" + 0;
                    }

                    if (-1 < mExperienceId) {
                        appender += "/exp-" + mExperienceId;
                    } else {
                        appender += "/exp-" + 0;
                    }
                }
            }
            String url = mUrl + appender + "/pg-" + pageNumber;
            if (mIsDefaultList && AccountUtils.isLoggedIn()) {
                url += "?" + Constant.MAP_COOKIE_KEY + "=" + AccountUtils.getCookie();
            }
            return url;
        }

        private void fetchJobs(String url) {
            mIsFetching = true;
            mLogger.d("url :" + url);
            int method = mIsDefaultList ? Method.GET : Method.POST;
            CookieStringRequest request = new CookieStringRequest(method, url, mListener, mErrorListener);
            request.setTag(mRequestTag);
            mRequestQueue.add(request);
        }

        private Response.Listener<String> mListener = new Listener<String>() {

            @Override
            public void onResponse(String response) {
                mLogger.d("response :" + response);
                JsonParserTask<JobList> jsonTask = new JsonParserTask<JobList>(new JobsProcessor());
                jsonTask.setListener(mJsonListener);
                jsonTask.execute(response);

            }
        };

        private Response.ErrorListener mErrorListener = new ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                mIsFetching = false;
                Toast.makeText(getActivity(), R.string.network_error, Toast.LENGTH_LONG).show();
            }
        };

        private JsonParsingListener<JobList> mJsonListener = new JsonParsingListener<JobList>() {

            @Override
            public void onSuccess(JobList result) {
                if (null == mPagination) {
                    mPagination = result.getPagination();
                    mPagination.setCurrentPage(0);
                    if(null == result.getJobs() || 0 == result.getJobs().size()) {
                        mMessageView.setText(getArguments().getString(ARG_EMPTY_MESSAGE));
                        mMessageView.setVisibility(View.VISIBLE);
                    } else {
                        mMessageView.setVisibility(View.GONE);
                    }
                } else {
                    mPagination.updateData(result.getPagination());
                }

                if (null != mJobs) {
                    mJobs.addAll(result.getJobs());
                } else {
                    mJobs = result.getJobs();
                }
                mAdapter.setJobList(mJobs);
                mAdapter.notifyDataSetChanged();
                mIsFetching = false;
            }

            @Override
            public void onFailure(Exception e) {
                Toast.makeText(getActivity(), "Unable to process response", Toast.LENGTH_LONG).show();
                mIsFetching = false;
            }
        };

        private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Job job = (Job) mAdapter.getItem(position);
                Intent intent = new Intent(getActivity(), JobDetailsActivity.class);
                intent.putExtra(JobDetailsActivity.EXTRA_JOB, job);
                startActivity(intent);
            }
        };

// this is the function where I also found that might cause some problem because when I scrolls down the items in the list repeated. private OnScrollListener mOnScrollListener = new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                boolean loadMore = firstVisibleItem + visibleItemCount >= totalItemCount;
                if (loadMore && totalItemCount > 0 && null != mPagination) {
                    boolean isLastPage = mPagination.getCurrentPage() >= mPagination.getTotalPages();
                    if (isLastPage) {
                        mFooterProgress.setVisibility(View.GONE);
                    }
                    if (!mIsFetching && !isLastPage) {
                        fetchJobs(getUrl(mPagination.getCurrentPage()+1));
                    }
                }
            }
        };

        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (Activity.RESULT_OK == resultCode) {
                switch (requestCode) {
                case REQUEST_EXPERIENCE:
                    onExperienceSelection(data);
                    break;

                case REQUEST_LOCATION:
                    onLocationSelection(data);
                    break;
                }
            }
        }
Ad

Answer

add one more line in your function:

mjob.clear();


private JsonParsingListener<JobList> mJsonListener = new JsonParsingListener<JobList>() {

        @Override
        public void onSuccess(JobList result) {
            if (null == mPagination) {
                mPagination = result.getPagination();
                mPagination.setCurrentPage(0);
                if(null == result.getJobs() || 0 == result.getJobs().size()) {
                    mMessageView.setText(getArguments().getString(ARG_EMPTY_MESSAGE));
                    mMessageView.setVisibility(View.VISIBLE);
                } else {
                    mMessageView.setVisibility(View.GONE);
                }
            } else {
                mPagination.updateData(result.getPagination());
            }

            if (null != mJobs) {
                mJobs.clear();
                mJobs.addAll(result.getJobs());
            } else {
                mJobs = result.getJobs();
            }
            mAdapter.setJobList(mJobs);
            mAdapter.notifyDataSetChanged();
            mIsFetching = false;
        }
Ad
source: stackoverflow.com
Ad