Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Android Fragments Introducing Fragments Making a List

Satyanarayana Akula
Satyanarayana Akula
1,264 Points

I'm trying to send intent from fragment to MainActivity. But while doing startActivity(intent)

But while doing startActivity(intent) at this point app is working good but every time i click on listview fragment is refreshing and listview starts from 0 index again. What is the best way to send the intent from fragment. I have two fragments and one main activity. So user can see both the fragments at same time. fist fragment is list of cities and second fragment is description of the city.. Please check my code below:

MainActivity.java
public class MainActivity extends AppCompatActivity {

    private String cityName;

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

        fragmentManage();


    }

    public void fragmentManage() {

        CityInformationFragment cityInformationFragment = new CityInformationFragment();
        CityList cityList = new CityList();


        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        fragmentTransaction.add(R.id.fragment2holder, cityList);
        fragmentTransaction.add(R.id.fragment1holder, cityInformationFragment);


        fragmentTransaction.commit();


        Intent intent = getIntent();
        cityName = intent.getStringExtra(CityList.PUT_EXTRA_KEY);

        Bundle bundle = new Bundle();
        bundle.putString(CityList.PUT_EXTRA_KEY, cityName);


        cityInformationFragment.setArguments(bundle);


    }

}
CityList.java
public class CityList extends Fragment implements AdapterView.OnItemClickListener {

  String[] cityList;
    ListView listView;
    protected static final String PUT_EXTRA_KEY = "city";



        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
            // arrayAdapter.addAll(cityList);

            cityList = getResources().getStringArray(R.array.cities);

            ArrayAdapter<CharSequence> arrayAdapter = new ArrayAdapter  <CharSequence>(getActivity(), android.R.layout.simple_list_item_1, cityList);
            View view = inflater.inflate(R.layout.citylistframent, container, false);

            listView = (ListView) view.findViewById(R.id.cityList);
            listView.setAdapter(arrayAdapter);
            listView.setOnItemClickListener(this);


        return view;
    }


    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        TextView textView = (TextView) view;

        String city = textView.getText().toString();
        Intent intent = new Intent(getActivity(), MainActivity.class);
        intent.putExtra(PUT_EXTRA_KEY, city);

        startActivity(intent);
    }
}
Cityinformation.java
public class CityInformationFragment extends Fragment {

    String vancouver = "Vancouver, a bustling west coast seaport in British Columbia, is among Canada’s densest, most ethnically diverse cities." +
            " A popular filming location, it’s surrounded by mountains, and also has thriving art, theatre and music scenes." +
            " Vancouver Art Gallery is known for its works by regional artists, while the Museum of Anthropology houses preeminent First Nations collections.";

    String calgary = "Calgary, a cosmopolitan Alberta city with numerous skyscrapers, owes its rapid growth to its status as the centre of Canada’s oil industry. However," +
            " it’s still steeped in the western culture that earned it the nickname “Cowtown,”" +
            " evident in the Calgary Stampede, its massive July rodeo and festival that grew out of the farming exhibitions once presented here.";

    String kamloops = "Kamloops is a Canadian city in British Columbia, where the North and South Thompson rivers meet." +
            " Sun Peaks Resort’s hiking trails, bike park and numerous ski runs lie to the northeast. Cougars and bears inhabit the British Columbia Wildlife Park east of town." +
            " West, above Kamloops Lake are clay hoodoos (or spires). The riverside Secwepemc Museum & Heritage Park features the remains of a 2,000-year-old village.";

    String toronto = "Toronto, the capital of the province of Ontario, is a major Canadian city along Lake Ontario’s northwestern shore." +
            " It's a dynamic metropolis with a core of soaring skyscrapers, all dwarfed by the iconic, free-standing CN Tower. " +
            "Toronto also has many green spaces, from the orderly oval of Queen’s Park to 400-acre High Park and its trails, sports facilities and zoo.";

    String saskatoon = "Saskatoon is a city straddling the South Saskatchewan River in Saskatchewan, Canada. " +
            "North along the riverside Meewasin Trail is Wanuskewin Heritage Park, with exhibitions exploring indigenous culture. " +
            "On the trail’s southern stretch, native wildlife inhabit the prairie grasslands of Beaver Creek Conservation Area. " +
            "East of the river, the Saskatoon Forestry Farm Park & Zoo has manicured gardens and a children’s zoo.";

    TextView textView;
    String cityName = "";


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

        textView = view.findViewById(R.id.cityInformation);

        cityName = getArguments().getString(CityList.PUT_EXTRA_KEY);
     //   Toast.makeText(getContext(), cityName, Toast.LENGTH_SHORT).show();
        setInformation();


        return view;
    }

    public String getVancouver() {
        return vancouver;
    }

    public String getCalgary() {
        return calgary;
    }

    public String getKamloops() {
        return kamloops;
    }

    public String getToronto() {
        return toronto;
    }

    public String getSaskatoon() {
        return saskatoon;
    }

    public void setInformation() {

        if (cityName != null) {

            if (cityName.equals("")) {
                textView.setText(getKamloops());
            } else if (cityName.equals("Calgary")) {
                textView.setText(getCalgary());
            } else if (cityName.equals("Kamloops")) {
                textView.setText(getKamloops());
            } else if(cityName.equals("Calgary")) {
                textView.setText(getCalgary());
            } else if(cityName.equals("Saskatoon")){
                textView.setText(getSaskatoon());
            } else if(cityName.equals("Toronto")) {
                textView.setText(getToronto());
            } else if(cityName.equals("Vancouver")){
                textView.setText(getVancouver());
            }

        } else {
            textView.setText(getKamloops());
        }
    }
}

Thanks in Advance....

[MOD: edited code blocks - srh]