ViewPager showing fragments with the same data when should be treating each fragment individually

450 Views Asked by At

I am a relative newbie to android programming and I am having some issues. I'm am trying to attach fragments to a view pager for a todo application. I have 7 fragments that repersent each day. Each fragment loads correctly, but when I add a task, it shows across all fragments instead of only the one I entered the task in. Code is below. Any help would be great, thank you!

ViewPager Activity

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseUser;

public class ToDoActivity extends FragmentActivity {
    MyPageAdapter pageAdapter;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_page_view);

        Parse.initialize(this, "uD7", "BrZkpvhY6Asi5oSq");
        //ParseAnalytics.trackAppOpened(getIntent());
        ParseObject.registerSubclass(Task.class);

        ParseUser currentUser = ParseUser.getCurrentUser();
        if(currentUser == null){
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
        }

        List<Fragment> fragments = getFragments();

        pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);

        ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
        pager.setAdapter(pageAdapter);

    }

    private List<Fragment> getFragments(){
        List<Fragment> fList = new ArrayList<Fragment>();

        fList.add(ToDoListFragment.newInstance("Important And Urgent"));
        fList.add(ToDoListFragment.newInstance("Important Not Urgent"));
        fList.add(ToDoListFragment.newInstance("Not Important But Urgent"));

        return fList;
    }

    private class MyPageAdapter extends FragmentPagerAdapter {
        private List<Fragment> fragments;

        public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
            super(fm);
            this.fragments = fragments;
        }
        @Override
        public Fragment getItem(int position) {
            return this.fragments.get(position);
        }

        @Override
        public int getCount() {
            return this.fragments.size();
        }
    }
}

FragmentActivity.java

    public class ToDoListFragment extends Fragment implements AdapterView.OnItemClickListener {

    public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
    private EditText mTaskInput;
    private ListView mListView;
    private TaskAdapter mAdapter = null;
    private Button mButton;

    public static final ToDoListFragment newInstance(String message)
    {
        ToDoListFragment f = new ToDoListFragment();
        Bundle bdl = new Bundle(1);
        bdl.putString(EXTRA_MESSAGE, message);
        f.setArguments(bdl);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
        Bundle savedInstanceState) {
        String message = getArguments().getString(EXTRA_MESSAGE);
        View v = inflater.inflate(R.layout.important_urgent, container, false);
        TextView messageTextView = (TextView)v.findViewById(R.id.textView);
        messageTextView.setText(message);

        mAdapter = new TaskAdapter(getActivity(), new ArrayList<Task>());

        mTaskInput = (EditText) v.findViewById(R.id.task_input);
        mListView = (ListView) v.findViewById(R.id.task_list);
        mButton = (Button) v.findViewById(R.id.submit_button);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(this);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mTaskInput.getText().length() > 0){
                    Task t = new Task();
                    t.setACL(new ParseACL(ParseUser.getCurrentUser()));
                    t.setUser(ParseUser.getCurrentUser());
                    t.setDescription(mTaskInput.getText().toString());
                    t.setCompleted(false);
                    t.saveEventually();
                    mAdapter.insert(t, 0);
                    mTaskInput.setText("");
                }
            }
        });

        updateData();

        return v;
    }

    public void updateData(){
        ParseQuery<Task> query = ParseQuery.getQuery(Task.class);
        query.whereEqualTo("user", ParseUser.getCurrentUser());
        query.setCachePolicy(ParseQuery.CachePolicy.CACHE_THEN_NETWORK);
        query.findInBackground(new FindCallback<Task>() {
            @Override
            public void done(List<Task> tasks, ParseException error) {
                if(tasks != null){
                    mAdapter.clear();
                    for (int i = 0; i < tasks.size(); i++) {
                        mAdapter.add(tasks.get(i));
                    }
                }
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        Task task = mAdapter.getItem(position);
        TextView taskDescription = (TextView) view.findViewById(R.id.task_description);

        task.setCompleted(!task.isCompleted());

        if(task.isCompleted()){
            taskDescription.setPaintFlags(taskDescription.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        }else{
            taskDescription.setPaintFlags(taskDescription.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
        }

        task.saveEventually();
    }
}

FragmentXML

   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:text="Hello"
        android:layout_gravity="center"
        android:id="@+id/textView"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        android:background="@color/red"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/task_input"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="text"
            android:hint="Enter a Task">
            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/submit_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Submit" />
    </LinearLayout>

    <ListView
        android:id="@+id/task_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
1

There are 1 best solutions below

0
BlackHatSamurai On

If you are using the same fragment XML file for each fragment, then when you update one, you are going to update all of them. You would need to create 7 different XML layouts (they could be the same layout, but would need different identifiers), and update that fragment layout individually.

Fragments are basically individual activities, running in a single Activity. You can reuse Fragments in different Activities, but each Fragment should have it's own layout.