2

first off I apologize if a similar question has already been asked and answered, but I have looked through tons of posts without any luck. Second, I am an absolute beginner (been coding for 6 weeks), so if I'm missing some concepts or if there is a better way to do things, feel free to enlighten me.

Now, here is my question: On my MainActivity, I have an EventsFragment which has a ListView. There is also a FloatingActionBar on the MainActivity, which when clicked loads another Activity called CreateEventActivity. The CreateEventActivity has an EditText field and a Create Button. What I wanna do is when the User enters some text in the EditText field and clicks the create Button, it should take the string from the EditText field and create an item on the ListView with String as it's name. Also, as soon as the create button is clicked, it should go back to the EventsFragment in the MainActivity.

I used startActivityForResults(), as suggested and it seems that I am able to pass an ArrayList as an intent from CreateEventActivity back to MainActivity, and that is as far as I'm able to get. I think the way I'm sending the list to the EventsFragment is wrong, as the listView is not updating.

MainActivity -

    public class MainActivity extends AppCompatActivity {

        /**
         * The {@link android.support.v4.view.PagerAdapter} that will provide
         * fragments for each of the sections. We use a
         * {@link FragmentPagerAdapter} derivative, which will keep every
         * loaded fragment in memory. If this becomes too memory intensive, it
         * may be best to switch to a
         * {@link android.support.v4.app.FragmentStatePagerAdapter}.
         */
        private SectionsPagerAdapter mSectionsPagerAdapter;

        /**
         * The {@link ViewPager} that will host the section contents.
         */
        private ViewPager mViewPager;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            // Create the adapter that will return a fragment for each of the three
            // primary sections of the activity.
            mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), MainActivity.this);

            // Set up the ViewPager with the sections adapter.
            mViewPager = (ViewPager) findViewById(R.id.container);
            mViewPager.setAdapter(mSectionsPagerAdapter);

            TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
            tabLayout.setupWithViewPager(mViewPager);

            //Iterate over all TabLayouts to set the custom View
            for (int i = 0; i < tabLayout.getTabCount(); i++){
                TabLayout.Tab tab = tabLayout.getTabAt(i);
                tab.setCustomView(mSectionsPagerAdapter.getTabView(i));
            }

            FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    loadCreateEventActivity();
    //                Snackbar.make(view, "Here the create a New Event Screen will be displayed", Snackbar.LENGTH_LONG)
    //                        .setAction("Action", null).show();
                }
            });

        }


        private void loadCreateEventActivity(){

            Intent intent = new Intent(MainActivity.this, CreateEventActivity.class);
            startActivityForResult(intent, 2);
        }

        public ArrayList<String>list = new ArrayList<>();

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == 2){
                if (resultCode == RESULT_OK) {

                    list = data.getStringArrayListExtra("LIST_ITEMS");
                }
            }
        }

        public ArrayList<String> getList() {
            return list;
        }

CreatEventsActivity -

public class CreateEventActivity extends AppCompatActivity {

    EditText createEventName;
    Button createButton;
    ArrayList<String> listItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_event);

        createEventName = (EditText) findViewById(R.id.createEventName);
        createButton = (Button) findViewById(R.id.createButton);
        listItems = new ArrayList<String>();
        listItems.add("First Item - added on Activity Create");

        createButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                listItems.add(createEventName.getText().toString());
                Intent intent = new Intent();
                intent.putStringArrayListExtra("LIST_ITEMS", listItems);
                setResult(RESULT_OK, intent);
                createEventName.setText("");
                finish();
            }
        });
    }
}

EventsFragment -

public class EventsFragment extends Fragment {


    public EventsFragment() {
        // Required empty public constructor
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_events, container, false);

        MainActivity mainActivity = (MainActivity) getActivity();
        ArrayList<String>list = mainActivity.getList();

        ListView listView = (ListView)view.findViewById(R.id.list_view);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1, list);
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        return view;
    }
}

Thanks for any help in advance :)

Souam Guha
  • 23
  • 4

1 Answers1

0

Solution 1 : You need to have one data set, that is common to both activities. Every time you click, you add add an item to that data set. The list view is populated using that very same data set. Since they are both in different activities, you need to persist that data set.

You can persist it locally, by storing it using a table(database) or as a json string, in [shared preference][1].

Another short cut to persist the data set is to have your data set as a property in your Application class, so you can add and access the dataSet from any activity in the app, as the application class is alive for the entire lifecycle of the app. I DON'T RECOMMEND THIS. This is easy and it works, but it is not good practice and leads to terrible code quality, but if you just want a quick way to do it, you can do it.

Solution 2 : In your main activity, start the second activity using startActivityForResult(). What this will let you do is let second activity talk back to the first one. So when it talks back, you can know in the first one, how many items were added in the second one and update your first activity's listView accordingly.

rgv
  • 1,186
  • 1
  • 17
  • 39
  • 1
    I tried your Solution 2, but I'm definitely doing something wrong as I'm getting a crash. Is there anyway I can post my revised code so you can see what I'm doing wrong? Thanks – Souam Guha Jun 26 '17 at 20:28
  • I have update my code. Could you please have a look? Thanks – Souam Guha Jun 28 '17 at 17:42
  • What is the crash you get ? Please post the logcat lines. Also debug the contents of the list, try to debug until what point things work, like you think it does. I can't debug it for you, plus it is an essential skill for a programmer. Here is a pro tip: Don't assume, Know! Keep that in mind till you die!! – rgv Jun 28 '17 at 19:04
  • Sorry, I probably should have mentioned this. I'm not getting a crash anymore. I fixed that. Now the code compiles and the app runs, but it doesn't do what it should: i.e the listView isn't updating. Just check the code where I'm passing the intent, getting the result and then passing the result to the fragment. I'll edit my post to that code only so it's easier for you – Souam Guha Jun 29 '17 at 01:11
  • 1
    Just an Update: your solution worked. The reason it was crashing was because I was making some rookie errors. And I got the list updating once I implemented onResume in the fragment. So thanks – Souam Guha Jul 04 '17 at 14:18
  • Glad to have helped! could you also up vote my answer ? – rgv Jul 04 '17 at 15:42