Android fragments on back exists application - android

I am having a problem with fragments. I want to start a fragment when I click an item from a Contacts list and then, when I press the phone back button I wanna go back to the contacts list. The fragments starts, but when I press the back button it doesn't go to the contacts lists, it just exists the application and gets to the phone menu.
This is for the contacts list
public class ChatMainActivity extends FragmentActivity{
private static Button btnLogOut;
private static SessionManager sm;
private static ListView listView ;
private List<ContactData> contactsList;
private static class ContactListFragment extends Fragment
{
public static Fragment newInstance(){
ContactListFragment ourList = new ContactListFragment();
return ourList;
}
#Override
public View onCreateView(LayoutInflater inflater,final ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.contactlistfragment,container,true);
listView = (ListView) v.findViewById(R.id.listView);
btnLogOut = (Button) v.findViewById(R.id.btnLogOut);
btnLogOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SessionManager sm = new SessionManager(v.getContext());
sm.logoutUser();
Intent i = new Intent(v.getContext(),MainActivity.class);
startActivity(i);
getActivity().finish();
}
});
System.out.println("fetch" + sm.fetchContacts());
List<String> nume = new ArrayList<String>();
List<ContactData> contactsList = new ArrayList<ContactData>();
for(String contact : SessionManager.getUserObj().getContactsInfo())
{
for(int i=0; i< sm.fetchContacts().size(); i=i+2){
if(sm.fetchContacts().get(i+1).equals(contact)){
contactsList.add(new ContactData(sm.fetchContacts().get(i).toString(),sm.fetchContacts().get(i+1).toString(),true));
nume.add(sm.fetchContacts().get(i));
}
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, nume);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
int itemPosition = position;
// String itemValue = (String) listView.getItemAtPosition(position);
MessagingFragment cChat = new MessagingFragment();
ViewGroup parentViewGroup = (ViewGroup) view.getParent();
System.out.println("Removed Views? ");
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer,cChat).commit();
// Intent i = new Intent(view.getContext(), MessagingActivity.class);
// startActivity(i);
// Here is the tricky part
}
});
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Here we set our custom adapter. Now we have the reference to the activity
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_main_layout);
sm = new SessionManager(this);
if (SessionManager.getUserObj() == null){
// We are checking to see if the Singleton object is set, if it isn't we must send the user back to login screen.
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
finish();
}
ContactListFragment clist = new ContactListFragment();
getSupportFragmentManager().beginTransaction().add(R.id.fragmentContainer, clist).commit();
}
}
and this is the fragment
public class MessagingFragment extends Fragment {
private EditText et ;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
container.removeAllViews();
container.removeAllViewsInLayout();
View v = inflater.inflate(R.layout.messaging_screen,null,true);
et = (EditText) v.findViewById(R.id.etmessage);
v.findViewById(R.id.sendMessageButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateMessageHistory(et.getText().toString());
et.setText("");
}
});
System.out.println("Init1");
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
et = (EditText) view.findViewById(R.id.etmessage);
view.findViewById(R.id.sendMessageButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateMessageHistory(et.getText().toString());
et.setText("");
}
});
System.out.println("Init2");
}
public void updateMessageHistory(String newText){
TextView tv = (TextView) getView().findViewById(R.id.messageHistory);
String oldText = tv.getText().toString();
oldText = oldText + "\n" + newText ;
tv.setText(oldText);
}
}
Any help would be appreciated.

Back stack is not turned on for fragments by default. But you can enable it easily. Try in your Activity's onCreate() to replace:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer, clist)
.commit();
with
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer, clist)
.addToBackStack(null)
.commit();
More info on Back stack:
http://android-er.blogspot.com/2013/04/allow-navigate-back-through.html

Related

Open a fragment from a fragment's fragment?

I have a Fragment with a ListView. When I click one of the item, a new Fragment is opened, and from this Fragment I want to open a new Fragment witha a Button.
I try to write the code, but it's a mess. When a click the Button, the program is crashed.
Should I use another way? I call the third Fragment like the second
Activity:
public class Grade extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceSt
ate);
setContentView(R.layout.activity_grade);
BottomNavigationView bottomNav = findViewById(R.id.lista_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_list,
new Objectlist()).commit();
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_tantargylista:
selectedFragment = new Objectlist();
break;
case R.id.nav_dolgozatlista:
selectedFragment = new Examlist();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_list,
selectedFragment).commit();
return true;
}
};
}
1st Fragment:
public class Objectlist extends Fragment {
View v;
DB mydb;
ListView listView;
private String teszt;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_objectlist, container, false);
listView = (ListView)v.findViewById(R.id.Gradeview);
mydb = new DB(getActivity());
final ArrayList<String> thelist = new ArrayList<>();
Cursor data = mydb.getTantargynev();
if (data.getCount() == 0) {
Toast.makeText(getActivity(), "Nincs jegyek hozzáadva", Toast.LENGTH_SHORT).show();
}
else {
while (data.moveToNext()) {
thelist.add(data.getString(0));
ListAdapter listadapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, thelist);
listView.setAdapter(listadapter);
}
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
teszt = thelist.get(i);
Bundle bundle = new Bundle();
String jegyAtlag="0";
Cursor data = mydb.JegyekAtlaga(teszt);
while (data.moveToNext()) jegyAtlag=data.getString(0);
String jegyDarab="0";
data = mydb.JegyekDarabszama(teszt);
while (data.moveToNext()) jegyDarab=data.getString(0);
if (jegyAtlag.equals("") || jegyDarab.equals(""))
else {
bundle.putString("Tantárgy átlaga", jegyAtlag);
bundle.putString("Tantárgy darabszáma", jegyDarab);
TextView jegyekHeader = (TextView) v.findViewById(R.id.header);
jegyekHeader.setText(teszt);
Fragment targyAdatok = new targyAdatok();
Fragment jegyekAllando = new jegyekAllando();
jegyekAllando.setArguments(bundle);
FragmentTransaction FragTan = getActivity().getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.jegyekMenu, targyAdatok);
ListView listaNezet = (ListView) v.findViewById(R.id.Gradeview);
listaNezet.setVisibility(View.GONE);
FragTan.commit();
}
}
}
);
}
return v;
}
}
2nd Fragment:
public class targyAdatok extends Fragment {
public targyAdatok() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_targy_adatok, container, false);
Button elemzes = (Button)v.findViewById(R.id.elemzes);
elemzes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment jegyekAllando = new jegyekAllando();
FragmentTransaction FragTan = getActivity().getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.targyAdatok,jegyekAllando);
FragTan.commit();
}
});
return v;
}
}
3rd Fragment:
public class jegyekAllando extends Fragment {
DB mydb;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_jegyek_allando, container, false);
Bundle bundle = getArguments();
String jegyAtlagSt = bundle.getString("Tantárgy átlaga");
String jegyDarabSt = bundle.getString("Tantárgy darabszáma");
return rootView;
}
}
I solved my problem. The problem was that a replaced the wrong fragment. Every time I have to replace the Activity's Fragment.

How to destroy fragment on Back press

I have 2 fragments A and B. First opens A fragment, there is button. onButtonClick it goes to fragment B. In fragment B the user selects some languages, or something else and onButtonClick comes to fragment A. So when it comes to Fragment A and i click back on phone, it goes back again on Fragment B. I want that when the user in Fragment B selects some information, languages and other things and then clicked next button, it destroyed. Something like this. When it goes from A to B, then after selecting information goes from B to A i want to destroy the B fragment. In fragment i can't to override the onBackPressed method because this is for activity. Any ideas? Found in internet some samples but they don't helped. If you need the code please say. Thanks for help.
Ok here's the Fragment A.
public class PersonalInfoFragment extends BaseFragment {
View mainView;
public static final String TEXT = "TEXT";
TextView dots;
EditText skills_description;
Button clear, save, languages;
CircleImageView circleImageView1, circleImageView2, circleImageView3,
circleImageView4, circleImageView5, circleImageView6;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.personal_info, container, false);
init(mainView);
Bundle bundle = getArguments();
if (bundle != null) {
ArrayList<Integer> s = bundle.getIntegerArrayList("IMAGE");
if (s != null) {
for (int i = 0; i < s.size(); i++) {
switch (i) {
case 0:
circleImageView1.setImageResource(s.get(i));
break;
case 1:
circleImageView2.setImageResource(s.get(i));
break;
case 2:
circleImageView3.setImageResource(s.get(i));
break;
case 3:
circleImageView4.setImageResource(s.get(i));
break;
case 4:
circleImageView5.setImageResource(s.get(i));
break;
case 5:
circleImageView6.setImageResource(s.get(i));
break;
default:
break;
}
}
}
}
return mainView;
}
private void init(View v) {
skills_description = v.findViewById(R.id.skills);
clear = v.findViewById(R.id.clear);
languages = v.findViewById(R.id.select_language);
dots = v.findViewById(R.id.dots);
save = v.findViewById(R.id.save);
circleImageView1 = v.findViewById(R.id.language1);
circleImageView2 = v.findViewById(R.id.language2);
circleImageView3 = v.findViewById(R.id.language3);
circleImageView4 = v.findViewById(R.id.language4);
circleImageView5 = v.findViewById(R.id.language5);
circleImageView6 = v.findViewById(R.id.language6);
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
skills_description.setText("");
}
});
languages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction().replace(R.id.container,
new FragmentLanguage()).addToBackStack(null).commit();
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}}
On languages.setOnClickListener it goes to Fragment B.
languages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction().replace(R.id.container,
new FragmentLanguage()).addToBackStack(null).commit();
}
});
Here's the Fragment B.
public class FragmentLanguage extends BaseFragment {
public static final String TEXT = "TEXT";
MyAdapter adapter;
View mainView;
ListView listView;
Button next;
PersonalInfoFragment info = new PersonalInfoFragment();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.listview, container, false);
listView = mainView.findViewById(R.id.list_view);
fillData();
showResult();
return mainView;
}
public void fillData() {
ArrayList<Item_obj> objS = new ArrayList<>();
//Array list of Languages
objS.add(new Item_obj("Armenian", R.drawable.download, false));
objS.add(new Item_obj("Russian", R.drawable.russian, false));
objS.add(new Item_obj("US English", R.drawable.usa, false));
objS.add(new Item_obj("Portugal", R.drawable.france, false));
objS.add(new Item_obj("Spanish", R.drawable.italy, false));
objS.add(new Item_obj("Georgian", R.drawable.download, false));
objS.add(new Item_obj("French", R.drawable.download, false));
objS.add(new Item_obj("Italian", R.drawable.download, false));
adapter = new MyAdapter(getActivity(), objS);
listView.setAdapter(adapter);
}
public void showResult() {
next = mainView.findViewById(R.id.next);
clear = mainView.findViewById(R.id.clear_lang);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Item_obj> it = adapter.getCheck();
Bundle bundle = new Bundle();
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < adapter.getCheck().size(); i++) {
Item_obj items = it.get(i);
if (items.isSelected) {
list.add(items.image);
}
}
if (list.size() > 6) {
Toast.makeText(getActivity(), "You can't select more than 6 elements", Toast.LENGTH_SHORT).show();
list.clear();
}
bundle.putIntegerArrayList("IMAGE", list);
info.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.container, info).addToBackStack(null).commit();
listView.setAdapter(adapter);
}
});
}}
In next.setOnClickListener it goes back again to fragment A, with selected languages.
Don't create a new instance of PersonalInfoFragment from FragmentLanguage fragment, instead on pressing of next button you should pass the bundle value to PersonalInfoFragment by creating a callback with interface and call onBackPressed method.
Callback creation code inside FragmentLanguage:
private OnNextClickListener mOnNextClickListener;
interface OnNextClickListener{
void onNextButtonClicked(Bundle bundle);
}
public void setOnNextClickListener(OnNextClickListener
mOnNextClickListener) {
this.mOnNextClickListener = mOnNextClickListener;
}
Call mOnNextClickListener.onNextButtonClicked(bundle); when next button pressed and implement the interface in PersonalInfoFragment.
fragmentTransaction.remove(yourfragment).commit()
add to onBackPressed() or where you set intent from B to A

How to save and restore custom arrayadapter data when switching fragments

I've tried different answers on this forum that are related to my problem but none seem to work for me.
ArrayAdapter Class
public class UserAdapter extends ArrayAdapter<User> {
public UserAdapter(Context context, ArrayList<User> users) {
super(context, 0, users);
}
private static class ViewHolder {
TextView water;
TextView amount;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
User user = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
// If there's no view to re-use, inflate a brand new view for row
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.card, parent, false);
viewHolder.water = (TextView) convertView.findViewById(R.id.WaterConsumed);
viewHolder.amount = (TextView) convertView.findViewById(R.id.WaterAmount);
// Cache the viewHolder object inside the fresh view
convertView.setTag(viewHolder);
} else {
// View is being recycled, retrieve the viewHolder object from tag
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.water.setText(user.waterconsum);
viewHolder.amount.setText(user.amount);
// Return the completed view to render on screen
return convertView;
}
User Class
public class User implements Serializable{
String waterconsum;
String amount;
public User(String waterconsum, String amount) {
this.waterconsum = waterconsum;
this.amount = amount;
}
One of the fragment class that shows the data
public class WaterFragment extends Fragment {
ArrayList<User> arrayOfUsers = new ArrayList<User>();
UserAdapter adapter;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setRetainInstance(true);
if (savedInstanceState != null) {
arrayOfUsers = (ArrayList<User>) savedInstanceState.getSerializable("List");
}
return view = inflater.inflate(R.layout.water, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
Button button = (Button) view.findViewById(R.id.additem);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showInputDialog();
}
});
adapter = new UserAdapter(getActivity(), arrayOfUsers);
ListView listView = (ListView) view.findViewById(R.id.listofitems);
if (listView.getAdapter() != null) {
listView.onRestoreInstanceState(savedInstanceState);
} else {
listView.setAdapter(adapter);
}
}
protected void showInputDialog() {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
final View promptView = layoutInflater.inflate(R.layout.input_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String text = editText.getText().toString();
addItems(text);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
public void addItems(String text) {
arrayOfUsers.add(new User("Water Consumed Today", text));
}
#Override
public void onSaveInstanceState(Bundle state) {
state.putSerializable("List", arrayOfUsers);
super.onSaveInstanceState(state);
}
Whenever i switch between different fragments, the array data is always reset. So im not sure on how to go about solving this, i've tried various solutions that involved saving the fragment state and the array data but none seem to work so far.
EDIT: Fragment Handler class
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
bottomBar = BottomBar.attach(this, savedInstanceState);
bottomBar.setItemsFromMenu(R.menu.three_buttons_menu, new OnMenuTabSelectedListener() {
#Override
public void onMenuItemSelected(#IdRes int menuItemId) {
if (menuItemId == R.id.Calendar) {
CalendarFragment f = new CalendarFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame, f).commit();
} else if (menuItemId == R.id.Water) {
WaterFragment wf = new WaterFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame,wf).commit();
} else if (menuItemId == R.id.Advice) {
AdviceFragment af = new AdviceFragment();
getSupportFragmentManager().beginTransaction().add(R.id.frame, af).commit();
} else if (menuItemId == R.id.Diary) {
AdviceFragment af = new AdviceFragment();
getSupportFragmentManager().beginTransaction().add(R.id.frame, af).commit();
} else if (menuItemId == R.id.Help) {
AdviceFragment af = new AdviceFragment();
getSupportFragmentManager().beginTransaction().add(R.id.frame, af).commit();
}
getFragmentManager().executePendingTransactions();
}
});
create your adaptor only once in onCreate of your fragment.
and in your onViewCreated set this adaptor to listview.
private UserAdapter adapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(adapter==null)
adapter = new UserAdapter(getActivity(), arrayOfUsers);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ListView listView = (ListView) view.findViewById(R.id.listofitems);
listView.setAdapter(adapter);
}
and whenever data changes add new items in adapter and call notifyDataSetChanged.
UPDATE: From your Fragment Handler class, you are creating new instance everytime you are replacing fragment like
CalendarFragment f = new CalendarFragment();
I'll suggest you to do like this..
private CalendarFragment calenderFragment;
private WaterFragment waterFragment;
private AdviceFragment adviceFragment;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
calenderFragment = new CalendarFragment();
waterFragment = new WaterFragment();
adviceFragment = new AdviceFragment();
bottomBar = BottomBar.attach(this, savedInstanceState);
bottomBar.setItemsFromMenu(R.menu.three_buttons_menu, new OnMenuTabSelectedListener() {
#Override
public void onMenuItemSelected(#IdRes int menuItemId) {
if (menuItemId == R.id.Calendar) {
if(calenderFragment==null)
calenderFragment = new CalendarFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame, calenderFragment)
.commit();
} else if (menuItemId == R.id.Water) {
if(waterFragment==null)
waterFragment = new WaterFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame, waterFragment)
.commit();
} else if (menuItemId == R.id.Advice) {
if(adviceFragment==null)
adviceFragment = new AdviceFragment();
getSupportFragmentManager().beginTransaction().add(R.id.frame, adviceFragment )
.commit();
} else if (menuItemId == R.id.Diary) {
if(adviceFragment==null)
adviceFragment = new AdviceFragment();
getSupportFragmentManager().beginTransaction().add(R.id.frame, adviceFragment )
.commit();
} else if (menuItemId == R.id.Help) {
if(adviceFragment==null)
adviceFragment = new AdviceFragment();
getSupportFragmentManager().beginTransaction().add(R.id.frame, adviceFragment )
.commit();
}
getFragmentManager().executePendingTransactions();
}
});

Android - Sending data from fragment to fragment using swipeview

Could be this is a dupe, but I've been looking for solutions and they always slightly differ from my problem.
So:
I'm currently creating an app that has 2 fragments that are swipeable. TaskGroupFragment shows a list and when you click on an item it wil slide to TasksFragment and show you a sublist. What I have to do now is send the id of the selected item from groups to tasks so I can get the sublist out of SQLite.
I know I'm supposed to communicate through the connected MainActivity and I'm already at the point that I've created an interface in TaskGroupsFragment and implemented this in the activity. Tried and tested and the activity receives the TaskGroupID.
The part where I'm stuck is getting this info in TasksFragment. Especially using swipeview makes this harder.
My code:
MainPagerAdapter:
public class MainPagerAdapter extends FragmentStatePagerAdapter {
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0: return TaskGroupFragment.newInstance();
case 1: return TasksFragment.newInstance();
default: return TaskGroupFragment.newInstance();
}
}
#Override
public int getCount() {
return 2;
}
}
TaskGroupActivity (sending fragment):
public class TaskGroupFragment extends ListFragment {
private DoItDataSource dataSource;
private List<TaskGroups> groups;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_group, container, false);
dataSource = new DoItDataSource(getActivity());
dataSource.open();
JSONContainer jsonContainer = dataSource.sqliteToContainer();
dataSource.close();
groups = jsonContainer.getTask_groups();
TaskGroupAdapter adapter = new TaskGroupAdapter(getActivity(), groups);
setListAdapter(adapter);
return view;
}
public static TaskGroupFragment newInstance() {
TaskGroupFragment tgf = new TaskGroupFragment();
return tgf;
}
public interface OnTaskGroupSelectedListener {
public void onTaskGroupSelected(String taskGroupId);
}
OnTaskGroupSelectedListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnTaskGroupSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " Interface not implemented in activity");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
((MainActivity)getActivity()).setCurrentItem(1, true);
mListener.onTaskGroupSelected(groups.get(position).getId());
}
}
MainActivity:
public class MainActivity extends FragmentActivity implements
TaskGroupFragment.OnTaskGroupSelectedListener{
private SharedPreferences savedValues;
private DoItDataSource dataSource = new DoItDataSource(this);
private String identifier, user, domain;
private JSONContainer containerToday;
private JSONContainer containerTomorrow;
public ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
identifier = savedValues.getString("Identifier", "");
pager = (ViewPager) findViewById(R.id.activity_main_pager);
pager.setAdapter(new MainPagerAdapter(getSupportFragmentManager()));
if (identifier == null || identifier.equals("")) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("APP_ID", APP_ID);
startActivity(intent);
}
}
#Override
protected void onResume() {
super.onResume();
identifier = savedValues.getString("Identifier", "");
user = savedValues.getString("User", "");
domain = savedValues.getString("Domain", "");
boolean onBackPressed = savedValues.getBoolean("OnBackPressed", false);
//
// getting lists
//
}
private void resultHandling(String json, String day) {
if (day.equals("today")) {
Gson gson = new Gson();
containerToday = gson.fromJson(json, JSONContainer.class);
jsonToSQLite(containerToday, "Today");
} else if (day.equals("tomorrow")) {
Gson gson = new Gson();
containerTomorrow= gson.fromJson(json, JSONContainer.class);
jsonToSQLite(containerTomorrow, "Tomorrow");
}
}
String taskGroupId = "";
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
// Enter missing link here?
}
}
TaskFragment (receiving fragment):
public class TasksFragment extends ListFragment
implements OnClickListener {
private final static String TAG = "TaskItemFragment logging";
private DoItDataSource dataSource;
private List<Tasks> tasks;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_item, container, false);
Button backButton = (Button)
view.findViewById(R.id.fragment_task_item_bar_back_button);
dataSource = new DoItDataSource(getActivity());
dataSource.open();
tasks = dataSource.getTasks("204"); // 204 is a placeholder, TaskGroupId should be here
dataSource.close();
TasksAdapter adapter = new TasksAdapter(getActivity(), tasks);
setListAdapter(adapter);
backButton.setOnClickListener(this);
return view;
}
public static TasksFragment newInstance() {
TasksFragment tif = new TasksFragment();
return tif;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), "Clicked item " + position, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.fragment_task_item_bar_back_button:
((MainActivity)getActivity()).setCurrentItem(0, true);
break;
}
}
}
Solution
Thanks to Alireza! I had to make several changes to his proposed code, but in the end it helped me in finding the solution!
MainPageAdapter:
public class MainPagerAdapter extends FragmentStatePagerAdapter {
// ADDED
private String taskGroupId;
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0: return TaskGroupFragment.newInstance();
// MODIFIED
case 1:
Bundle args = new Bundle();
logcat("before setBundle " + taskGroupId);
args.putString("taskGroupId",taskGroupId);
Fragment fragment = new TasksFragment();
fragment.setArguments(args);
return fragment;
default: return TaskGroupFragment.newInstance();
}
}
// ADDED
public void setTaskGroupId(String id){
this.taskGroupId = id;
}
#Override
public int getCount() {
return 2;
}
}
MainActivity:
public class MainActivity extends FragmentActivity implements
TaskGroupFragment.OnTaskGroupSelectedListener{
private SharedPreferences savedValues;
private DoItDataSource dataSource = new DoItDataSource(this);
private String identifier, user, domain;
private JSONContainer containerToday;
private JSONContainer containerTomorrow;
// ADDED
private MainPagerAdapter adapter;
public ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
identifier = savedValues.getString("Identifier", "");
// ADDED
adapter = new MainPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.activity_main_pager);
// MODIFIED
pager.setAdapter(adapter);
if (identifier == null || identifier.equals("")) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("APP_ID", APP_ID);
startActivity(intent);
}
}
#Override
protected void onResume() {
super.onResume();
identifier = savedValues.getString("Identifier", "");
user = savedValues.getString("User", "");
domain = savedValues.getString("Domain", "");
boolean onBackPressed = savedValues.getBoolean("OnBackPressed", false);
//
// Getting lists
//
}
String taskGroupId = "";
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
// ADDED
adapter.setTaskGroupId(taskGroupId);
pager.setAdapter(adapter);
pager.setCurrentItem(1);
}
}
TaskFragment (receiving fragment):
public class TasksFragment extends ListFragment implements OnClickListener {
private final static String TAG = "TaskItemFragment logging";
private DoItDataSource dataSource;
private List<Tasks> tasks;
private String taskGroupId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_item, container, false);
Button backButton = (Button) view.findViewById(R.id.fragment_task_item_bar_back_button);
dataSource = new DoItDataSource(getActivity());
// ADDED
Bundle bundle = getArguments();
taskGroupId = bundle.getString("taskGroupId");
// MODIFIED
dataSource.open();
tasks = dataSource.getTasks(taskGroupId);
dataSource.close();
TasksAdapter adapter = new TasksAdapter(getActivity(), tasks);
setListAdapter(adapter);
backButton.setOnClickListener(this);
return view;
}
// CAN BE REMOVED?
//public static TasksFragment newInstance() {
// TasksFragment tif = new TasksFragment();
// return tif;
//}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), "Clicked item " + position, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.fragment_task_item_bar_back_button:
((MainActivity)getActivity()).setCurrentItem(0, true);
break;
}
}
}
Please note that I'm using taskGroupId as a String, not an int.
First you need to make sure your adapter knows about taskGroupID. just add a variable and a public method to your adapter.
public class MainPagerAdapter extends FragmentStatePagerAdapter {
private int taskGroupId;
public void setTaskGroupId(int id){
this.taskGroupId = id;
}
}
then store a reference to your adapter in your activity. Now simply call this method whenever GroupId changes
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
adapter.setTastGroupId = taskGroupId; //data needed to initialize fragment.
adapter.setCurrentItem(1); //going to TasksFragment page
}
then you need to put some argumants before starting your fragment.
#Override
public Fragment getItem(int i) {
//this code is only for case 1:
Bundle args = new Bundle();
args.putInt("taskGroupId",taskGroupId);
Fragment fragment = new TasksFragment();
fragment.setArguments(args);
return fragment;
}
and lastly use this data in your TaskFragment to show the right content.

Android: get access to view elements in OnClickListener

I have a Fragment container and some buttons outside the fragment which interact with the content of the fragment. When I click on the button, I need to get the information inside the text elements. This is what I have right now, but it doesn't work.
The code comes from the fragment pager demos.
Button bm = (Button) findViewById(R.id.bm);
bm.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText editTextIn1 = (EditText) v.findViewById(R.id.editTextIn1);
}
});
edit
I use this sample:
http://developer.android.com/reference/android/support/v13/app/FragmentStatePagerAdapter.html
public class FragmentStatePagerSupport extends FragmentActivity {
static final int NUM_ITEMS = 10;
MyAdapter mAdapter;
ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
// Watch for button clicks.
Button button = (Button)findViewById(R.id.goto_first);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(0);
}
});
button = (Button)findViewById(R.id.goto_last);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(NUM_ITEMS-1);
}
});
}
public static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
return ArrayListFragment.newInstance(position);
}
}
public static class ArrayListFragment extends ListFragment {
int mNum;
/**
* Create a new instance of CountingFragment, providing "num"
* as an argument.
*/
static ArrayListFragment newInstance(int num) {
ArrayListFragment f = new ArrayListFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
/**
* When creating, retrieve this instance's number from its arguments.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
/**
* The Fragment's UI is just a simple text view showing its
* instance number.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
View tv = v.findViewById(R.id.text);
((TextView)tv).setText("Fragment #" + mNum);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, Cheeses.sCheeseStrings));
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList", "Item clicked: " + id);
}
}
}
The v in your onCLickListener is referring to the Button itself, and calling findViewByID on the button means that the button is looking through its children (it doesn't have any) to find an EditText element. if this code is running in an activity, you may be able to do:
Button bm = (Button) findViewById(R.id.bm);
bm.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText editTextIn1 = (EditText) findViewById(R.id.editTextIn1);
}
});
alternately, if you have a reference to the fragment's container (like a framelayout or something), you can do
Button bm = (Button) findViewById(R.id.bm);
bm.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText editTextIn1 = (EditText) myFragmentContainer.findViewById(R.id.editTextIn1);
}
});

Categories

Resources