Milan Gajera
Milan Gajera

Reputation: 970

Why ViewPager get wrong position in android?

I tried to find an answer everywhere but I have found none.

Explanation: I have a Viewpager in my fragment. I called an adapter into my fragment and set it into ViewPager. My ViewPager is dynamic according to the JSONArray data.I have a jsonArray which has five objects. I added every object into List and passed it to the adapter. So, my viewpager is created according to list.size(), but the problem is when my HomeFragment.java has loaded. The adapter is called twice (not sure) but log shows it is called twice.

Here is my Homefragment.java

private class TabJson extends AsyncTask<String,String,String> {

    String jsonStr="";

    private static final String url="http://10.0.2.2/JSON/recentmatch.php";
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {

        ServiceHandler sh=new ServiceHandler();
        jsonStr=sh.makeServiceCall(url,ServiceHandler.POST);
        try{
            JSONObject obj=new JSONObject(jsonStr);
            JSONObject data=obj.getJSONObject("data");
            JSONArray card=data.getJSONArray("cards");

            PagerLength=0;
            lst_obj=new ArrayList<>();
            for(int i=0;i<card.length();i++){
                JSONObject card_obj=card.getJSONObject(i);

                if(card_obj.getString("status").equals("started") || card_obj.getString("status").equals("notstarted")){
                    PagerLength++;
                    lst_obj.add(card_obj);
                }
            }
        }
        catch (JSONException e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        LiveAdapter adapterTabRecent=new LiveAdapter(getContext(),lst_obj);
        pagerRecentMatches.setAdapter(adapterTabRecent);
        pagerRecentMatches.setCurrentItem(0);

        float scaledDensity = getResources().getDisplayMetrics().scaledDensity;
        LinearLayout.LayoutParams param1=new LinearLayout.LayoutParams(10*(int)scaledDensity,10*(int)scaledDensity);
//        for(int i=0;i<PagerLength-1;i++){
//            ImageView img=new ImageView(getContext());
//            TextView space=new TextView(getContext());
//            img.setId(R.id.selected_id);
//            img.setLayoutParams(param1);
//            img.setImageResource(R.drawable.unselect);
//            space.setText(" ");
//            selector_dynamic.addView(img);
//        }
    }
}

Above is the code where I got the data from a JSON and where I set it to my adapter.

Here is my LiveAdapter.java

public class LiveAdapter extends PagerAdapter{

    private Context context;
    List<JSONObject> lst;
    JSONObject mainObj=null;
    View itemView;
    private LayoutInflater inflater;
    String status="";
    public LiveAdapter(Context context,List<JSONObject> lst){
        this.context=context;
        this.lst=lst;
        inflater=(LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        return lst.size();
    }

    @Override
    public int getItemPosition(Object object) {
        int index=lst.indexOf((List)object);

        if(lst.contains((List)object)){
            return index;
        }
        else{
            return POSITION_NONE;
        }
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view==((LinearLayout)object);
    }

    private class Holder{
        TextView txt_one_country_name;
        TextView txt_two_country_name;
        TextView txt_venue;
        TextView match;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        itemView=inflater.inflate(R.layout.tab_slider,container,false);
        Holder holder=new Holder();
        String[] parts;
        String[] state_parts;
        String[] match_parts;

        Log.e("POSITION",""+position);
        mainObj=this.lst.get(position);

        holder.txt_one_country_name=(TextView)itemView.findViewById(R.id.txt_one_country_name);
        holder.txt_two_country_name=(TextView)itemView.findViewById(R.id.txt_two_country_name);
        holder.txt_venue=(TextView)itemView.findViewById(R.id.venue);
        holder.match=(TextView)itemView.findViewById(R.id.match);

        try {

            status=mainObj.getString("status");
            Log.e("POSITION INSIDE TRY",""+position);
            Log.e("Status-->>>",""+status);
            String name = mainObj.getString("name");
            String state=mainObj.getString("venue");
            String title=mainObj.getString("title");

            parts=name.split("vs");
            match_parts=title.split("-");
            state_parts=state.split(",");

            holder.txt_one_country_name.setText(parts[0]);
            holder.txt_two_country_name.setText(parts[1]);
            holder.txt_venue.setText(state_parts[1]);
            holder.match.setText(match_parts[1]);
        }
        catch (JSONException e){
            e.printStackTrace();
        }
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(status.equals("notstarted")) {
                    Log.e("STATUS INSIDE ONCLICK",""+status);
                    Intent intent = new Intent(context, NotStartedMatchDetails.class);
                    context.startActivity(intent);
                }

            }
        });
        container.addView(itemView);
        return itemView;
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
//        super.setPrimaryItem(container, position, object);
        itemView=(View)object;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout)object);
    }
}

I set the log in instantiateItem(). When I run the application position set to me by default as 0 and 1.

Here, is my position value

01-18 15:47:02.295 31593-31593/com.example.myworld.materialdesign E/POSITION: 0
01-18 15:47:02.295 31593-31593/com.example.myworld.materialdesign E/POSITION INSIDE TRY: 0
01-18 15:47:02.295 31593-31593/com.example.myworld.materialdesign E/Status-->>>: notstarted
01-18 15:47:02.306 31593-31593/com.example.myworld.materialdesign E/POSITION: 1
01-18 15:47:02.306 31593-31593/com.example.myworld.materialdesign E/POSITION INSIDE TRY: 1
01-18 15:47:02.306 31593-31593/com.example.myworld.materialdesign E/Status-->>>: started

The problem is when I swipe right to left, the position value mentioned below: I have five tabs dynamically created it' value is 2,3,4 that's it. where is 0 and 1?

but when I swipe left to right, the position value mentioned below: 2,1,0 that's it where is 3 and 4?

Please, help me to overcome this problem.

Upvotes: 2

Views: 1469

Answers (1)

Avinash Joshi
Avinash Joshi

Reputation: 1308

do this when you instantiate the object

@Override
public Object instantiateItem(ViewGroup container, int position) {
.....
itemView.setTag(position);
.....

}
//now on click of the item view you can get it back as follows
itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();// v here is your itemView
}

Upvotes: 1

Related Questions