I am new to Android and are working on an app to show the communication between two fragments in a single activity. When I click on an item from a customed listview in the first fragment, the view in the second fragment change in the runtime.
public class FirstFragment extends Fragment {
onSelectedCitySendListener selectedCitySendListener;
public interface onSelectedCitySendListener{
public void onSelectedCitySend(int city) ;
}
public FirstFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
String[] cities = {"Kamloops", "Calgary", "Toronto","Vancouver"};
ListView listView = (ListView) view.findViewById(R.id.cityList);
ArrayAdapter<String> listViewAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, cities);
listView.setAdapter(listViewAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int pos = position;
selectedCitySendListener.onSelectedCitySend(pos);
}
});
// Inflate the layout for this fragment
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
Activity activity = (Activity)context;
selectedCitySendListener = (onSelectedCitySendListener) activity;
}
}
public class SecondFragment extends Fragment {
public SecondFragment() {
// Required empty public constructor
}
private static TextView textView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, container, false);
textView = view.findViewById(R.id.frameLayout2);
Bundle bundle = getArguments();
int position = bundle.getInt("Position");
if(position == 0)
textView.setText("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.");
if(position == 1)
textView.setText("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.");
if(position == 2)
textView.setText("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.");
if(position == 3)
textView.setText("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.");
return view;
}
}
public class MainActivity extends AppCompatActivity implements FirstFragment.onSelectedCitySendListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirstFragment firstFragment = new FirstFragment();
getSupportFragmentManager().beginTransaction().add(R.id.frameLayout, firstFragment).commit();
SecondFragment secondFragment = new SecondFragment();
getSupportFragmentManager().beginTransaction().add(R.id.frameLayout2, secondFragment).commit();
}
@Override
public void onSelectedCitySend(int pos) {
Bundle bundle = new Bundle();
bundle.putInt("Position", pos);
SecondFragment secondFragment = new SecondFragment();
secondFragment.setArguments(bundle);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout2, secondFragment, null);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
There no any errors in compile time but the app keeps crashing. I so panic now :'(
I can suggest a simple solution for sharing variables between fragments attached to a parent activity:
In MainActivity create a static variable (this variable will be common for all instances of MainActivity):
private static int position = 0;
In MainActivity create a setter and a getter for it:
int getPosition() { return position; }
void setPosition(int position) { this.position = position; }
In your FirstFragment, set the value of the variable to what you want (for example in an OnClickEventListener):
((MainActivity)requireActivity()).setPosition(1);
In your SecondFragment, retrieve the value of the variable whenever you wish (for example in onCreate(), but perhaps better in onResume()):
((MainActivity)requireActivity()).getPosition();
Hope this helps.