Passing data from one fragment to next fragment in android - java

In one of my project I am using 2 fragments.One fragment is displaying a list of items.So I want when the topic will be selected in first fragment the details should be changed in another fragment.Data I am able to pass from one fragment to other but the view is not changing.In which method I should implement the view of second fragment so that it can change accordingly.
Please give me good tutorial or example for these.
Here I have to develop one android example, I have to run the app means displayed category name well on horizontal listview of my first fragment.I have to click any category means how can I pass the category name on 2nd fragment.Please give me solution for this problem.
I have used below code:
public class Home extends FragmentActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
1st fragment code:
public class MainActivity extends Fragment {
static final String URL = "http://dev2.mercuryminds.com/webservices/new_feed_articls.xml";
static String KEY_CATEGORY = "Categories";
static final String KEY_TITLE = "Category";
LazyAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main,
container, false);
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_TITLE);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String> ();
Element e = (Element) nl.item(i);
map.put( KEY_TITLE,((Element)nl.item(i)).getAttribute("name"));
// map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
songsList.add(map);
}
HorizontalListView list = (HorizontalListView) view.findViewById(R.id.listView1);
adapter = new LazyAdapter(getActivity(), songsList);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = songsList.get(position);
Intent in = new Intent();
in.setClass(getActivity(), SubCate.class);
// in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
startActivity(in);
}
});
return view;
}}
How can i display category name on 2nd Activity...pls give me code for these...
EDIT:
Hi i have changed code like on my first activity:
HashMap<String, String> map = songsList.get(position);
SubCate frag = (SubCate) getFragmentManager().findFragmentById(R.id.frag_2);
if (frag != null && frag.isInLayout()) {
frag.setText(getCapt(map));
}
}
private String getCapt(HashMap<String, String> map) {
if (map.containsValue("notchbolly")) {
return "dadad";
}
return "veeman";
on next activity:
public void setText(String item) {
TextView view = (TextView) getView().findViewById(R.id.cate);
view.setText(item);
}
its woked well while directly mention the name on if (map.containsValue("notchbolly")).but i have to display the name without mention name directly.if i have to click any category means that category name is displayed on next fragment.how can i do ?????

Using interface method we can transfer data between fragment to fragment
In fragmentA create interface and sent data to this interface and implement this interface method in fragmentB and get required data
the following code is useful for u
Code in FragmentA:
public class FragmentA extends Fragment {
// interface method
public InterfaceDataCommunicatorBetweenfragmentAToFragmentB iInterfaceDataCommunicatorBetweenfragmentAToFragmentB;
// Data to send
String mDataString;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// use this line where u send data
iInterfaceDataCommunicatorBetweenfragmentAToFragmentB.upDatedData(mDataString);
View view = inflater.inflate(R.layout.sent_box, container, false);
return view ;
}
/**
* Interface method to send data to fragmentB
*
*/
public interface InterfaceDataCommunicatorBetweenfragmentAToFragmentB {
public void upDatedData(String data);
}
}
Code in FragmentB:
class FragmentB extends Fragment implements InterfaceDataCommunicatorBetweenfragmentAToFragmentB {
// interface method
public InterfaceDataCommunicatorBetweenfragmentAToFragmentB iInterfaceDataCommunicatorBetweenfragmentAToFragmentB;
// fragmentA data
String mgetUpdatedData
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.get_box, container, false);
return view ;
}
/**
* Interface method coming from fragment a to fragmentB after implement interface in fragmentB
*/
public void upDatedData(String data) {
this.mgetUpdatedData = data;
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
try {
iInterfaceDataCommunicatorBetweenfragmentAToFragmentB = (InterfaceDataCommunicatorBetweenfragmentAToFragmentB ) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement interface");
}
}

You need to implement interface mechanism.
Refer following links for further details.
http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
http://developer.android.com/training/basics/fragments/communicating.html

Related

Android BottomSheetDialogFragment data changes the data in parent Fragment

Problem Statement
I have a problem of data being changed in fragment whenever the data is modified in the BottomSheetDialogFragment
App Description
In my app I have the MainActivity which host 2 Fragment in it's ViewPager. 1st Fragment for app content and 2nd Fragment (let's call it GalleryFragment) that shows the gallery view. User can tap on gallery item which loads up the BottomSheet (let's call it GalleryBottomSheet) - that hosts RecyclerView to show gallery item in full screen. Now initially app feeds the GalleryFragment with the ArrayList to show the gallery items. When user clicks on the Gallery item, this ArrayList is passed to the GalleryBottomSheet.
So What's Happening
What's happening is whenever I am removing an item from the ArrayList in my GalleryBottomSheet, It automatically also remove that item in the ArrayList of GalleryFragment. In short, Any update in the Arraylist from GalleryBottomSheet impacting the ArrayList in GalleryFragment
What do you want
I want seperation of concerns. I don't want the change made in the ArrayList of GalleryBottomSheet to impact the original ArrayList of GalleryFragment
Show me the damn code
To make this question concise, I am adding only the important part of the code.
~ GalleryFragment.java
public class GalleryFragment extends Fragment {
private RecyclerView recyclerView;
private ArrayList<String> arrayList = new ArrayList<>(); //This is the one which will be passed to the GalleryBottomSheet
private GalleryAdapter galleryAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
//setting up all the UI work...
arrayList = FindFiles(); //FindFiles is a private function searching for all file in the dir and adding the path as a string to the arraylist
galleryAdapter = new GalleryAdapter(getActivity()); //init the adapter
recyclerView.setAdapter(galleryAdapter); //setting the adapter
return view;
}
}
private class GalleryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Activity activity;
GalleryAdapter(Activity context) {
this.activity = context;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gallery_content_item, parent, false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
if(holder instanceof ItemViewHolder){
//setting up stuff..
}
}
#Override
public int getItemCount() {
return arrayList.size();
}
private class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView imageView;
ItemViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putStringArrayList("list", arrayList);
GalleryBottomSheet galleryBottomSheet= GalleryBottomSheet.newInstance();
galleryBottomSheet.setOnRefreshListener( new GalleryBottomSheet.GalleryInterface() {
#Override
public void onRefresh() {
//here the actual arrayList size reduced even though the arrayList that was modified exist in GalleryBottomSheet
System.out.println("CURRENT LIST SIZE: " + arrayList.size());
}
});
galleryBottomSheet.setArguments(bundle);
galleryBottomSheet.show(getParentFragmentManager(), "galleryPager");
}
}
~ GalleryBottomSheet.java
public class GalleryBottomSheet extends BottomSheetDialogFragment {
static GalleryBottomSheet newInstance() {
return new GalleryBottomSheet();
}
public interface GalleryInterface {
void onRefresh();
}
private RecyclerView recyclerView;
private ViewAdapter viewAdapter;
private Button deleteBtn;
private GalleryInterface galleryInterface;
public void setOnRefreshListener( GalleryInterface galleryInterface){
this.galleryInterface = galleryInterface;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//.. setting up sheetDialog
return bottomSheetDialog;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(BottomSheetDialogFragment.STYLE_NO_FRAME, R.style.GalleryBottomStyle);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.gallery_sheet, container, false);
Bundle bundle = getArguments();
ArrayList<String> filePathArr = bundle.getStringArrayList("list"); //here arrayList from GalleryFragment
//Setting up all UI views...
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int positionPager = recyclerView.computeVerticalScrollOffset(); //just for demo, in the actual app we are using addOnScrollListener for position
filePathArr.remove(positionPager);
viewAdapter.notifyItemRemoved(positionPager);
galleryInterface.onRefresh(); //this is where GalleryFragment shows that the arraylist is modified too.
Toast.makeText(getActivity(), "Deleted Successfully",Toast.LENGTH_SHORT).show();
}
});
return view;
}
//setting up viewAdapter and other stuff
}
Well, it turns out the main problem is that object is stored in memory by reference. By modifying the arrayList from GalleryBottomSheet it also changes the original arrayList since the exact arrayList was referred in GalleryBottomSheet from GalleryFragment. The solution is to simply initializing a new ArrayList in GalleryBottomSheet
Changing from:
ArrayList<String> filePathArr = bundle.getStringArrayList("list");
to:
ArrayList<String> filePathArr = new ArrayList<>(bundle.getStringArrayList("list"));

How can I pass a ArrayList<String> created in a fragment to the main activity

I have a drawer menu with 3 items (Restaurant, Movie, Food). They are basically 3 to do lists. Each list has its on fragment and in the view there is a way to add items to the list.
The restaurant list, the movie list ad the groceries list.
I need to be able to share that list (via any share-channel) by clicking the share icon that is in the toolbar.
This is my fragment where i populate the items list that i want to use when i click the share icon that is on the toolbar. Basically i need to pass "items" to the MainActivity and use it.
package com.example.mylists;
import android.content.Intent;
public class FoodFragment extends Fragment {
public FoodFragment() {
// Required empty public constructor
}
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
private static final String TAG = "FoodFragment";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.i(TAG, "in on onCreateView ");
View view = inflater.inflate(R.layout.fragment_food, container, false);
lvItems = (ListView) view.findViewById(R.id.lvItems);
items = new ArrayList<String>();
readItems();
itemsAdapter = new ArrayAdapter<String>(view.getContext(),android.R.layout.simple_list_item_1, items);
lvItems.setAdapter(itemsAdapter);
if (items.isEmpty())
items.add("Dummy Item");
final EditText newTask = (EditText) view.findViewById(R.id.etNewItem);
Button btnAdd = (Button) view.findViewById(R.id.btnAddItem);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String itemText = newTask.getText().toString();
itemsAdapter.add(itemText);
newTask.setText("");
writeItems();
Log.i(TAG, "in on send data ");
}
});
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Log.i(TAG, "in on onViewCreated ");
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.i(TAG, "in on onActivityCreated ");
super.onActivityCreated(savedInstanceState);
OnItemLongClickListener listener = new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long id) {
//Log.i(TAG, "in on onItemLongClick ");
//Toast.makeText( getActivity().getBaseContext() , "Long Clicked " , Toast.LENGTH_SHORT).show();
items.remove(position);
itemsAdapter.notifyDataSetChanged();
writeItems();
//return true;
return false;
}
};
lvItems.setOnItemLongClickListener(listener);
}
private void readItems() {
File filesDir = getContext().getFilesDir();
File todoFile = new File(filesDir, "todo.txt");
try {
items = new ArrayList<String>(FileUtils.readLines(todoFile));
} catch (IOException e) {
items = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getContext().getFilesDir();
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, items);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You should declare ArrayList<String> items in your MainActivity. Then create a public setter method for items.
public void setItems(ArrayList<String> items){
this.items = items;
}
Then you should call setItems() method in your fragment.
((MainActivity) getActivity()).setItems(items);
Interface for Callback
interface MyInterface {
void setItems(ArrayList<String> items);
}
In your activity:
class MyActivity {
ArrayList<String> items;
MyInterface itemsCallback = new MyInterface(){
#Override
void setItems(ArrayList<String> items){
this.items = items;
}
}
myFragment.setItemsCallback(itemsCallback);
}
And then in fragment
class MyFragment {
private MyInterface itemsCallback;
public void setItemsCallback(MyInterface itemsCallback){
this.itemsCallback = itemsCallback;
}
private void readItems(){
...
itemsCallback.setItems(items);
}
}
I guess it's better then public setter in MainActivity. Because, you know, it's like more SOLID code. In this case your Fragment doesnt hold reference to Activity and doesnt even know about it existence.
1.Define an interface , 2.Let your Activity implements the interface 3.use (interface)getActivity() to cast your Activity to that interface,then you can call the method in the interface to send your ArrayList "items"

Having problems while trying to populate a todo listview using a custom adaptor?

I want a user to input data through an editable text and I want to receive that data through a custom made listview, for that I am trying to use a custom adapter to add a textfield into my listview, through the tostring() method I have converted the data from the editable textview to a string and I am adding that string within my custom adapter to an Arraylist variable values and I’m trying to display that data through get(0) but either the Arraylist is not populating correctly or the data is not displaying properly because whenever I type something within my editable text and press the add button nothing happens, before this I added the string to an Array Adapter and the listview was populating normally, what am I doing wrong?
public class todoFragment extends ListFragment {
private EditText mToDoField;
private Button mAdd;
UsersAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setTitle(R.string.todo_title);
}
public class UsersAdapter extends ArrayAdapter<String> {
public Context context;
public ArrayList<String> values;
public UsersAdapter(Context context, ArrayList<String> values) {
super(context, 0, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = LayoutInflater.from(getContext()).inflate(R.layout.todo_list, parent, false);
TextView todoTextView = (TextView) convertView.findViewById(R.id.todo_TextView);
todoTextView.setText(values.get(0));
return convertView;
}
}
#TargetApi(9) // remember this for isEmpty()
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_todo, container, false);
ArrayList<String> todoList = new ArrayList<String>();
mAdapter = new UsersAdapter(getActivity(), todoList);
ListView listViewToDo = (ListView) v.findViewById (android.R.id.list);
listViewToDo.setAdapter(mAdapter);
mToDoField = (EditText) v.findViewById(R.id.todo_editText);
mAdd = (Button)v.findViewById(R.id.add_button);
mAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String toDo = mToDoField.getText().toString().trim();
if (toDo.isEmpty()){
return;
}
mAdapter.values.add(toDo);
mToDoField.setText("");
}
});
return v;
}
}
Firstly, you should not be doing
todoTextView.setText(values.get(0));
Because this will always return the first element of the values list. You should do
todoTextView.setText(values.get(position));
Secondly,
mAdapter.values.add(toDo);
is not really right. It will work, but its not the best practise. Try using something like
mAdapter.add(toDo);
or
values.add(toDo);
Now once you've added the data to the list, you need to notify the adapter that the data set has been changed. This is done by
mAdapter.notifyDataSetChanged();
When you manually update the data don't forget to call:
mAdapter.notifyDataSetChanged();
Instead of mAdapter.values.add(toDo); UsemAdapter.add(toDo);
Look at the Add Method Of ArrayAdpter Class, it Itself use notifyDataSetChanged() so need to write any extra line of code:
public void add(T object) {
synchronized (mLock) {
if (mOriginalValues != null) {
mOriginalValues.add(object);
} else {
mObjects.add(object);
}
}
if (mNotifyOnChange) notifyDataSetChanged();
}

Updating ListView On Custom ArrayAdapter

I apologize if this is similar to other threads, but I have yet to find a good solution on how to update the ListView in my custom ArrayAdapter.
I'm extending FragmentActivity in order to create a custom Dialog popup for adding / updating new List entries (which works fine), but I can't seem to get the ListView in ServerActivityArrayAdapter to update after a change is made.
Obviously, adapter.notifyDataSetChanged(); in the ServersActivity class isn't enough, but I'm stumped as to how to get my ListView to update after the Save button is clicked in the ServerDialog popup. Any help would be greatly appreciated!
public class ServersActivity extends FragmentActivity {
private List<Server> server;
private ListView lv;
private ServerActivityArrayAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.server_list);
server = getServers();
lv = (ListView) findViewById(android.R.id.list);
adapter = new ServerActivityArrayAdapter(this, R.layout.server_list_item, server);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
showServerDialog(position);
}
});
}
...
private void showServerDialog(int position) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
ServerDialog serverDialog = new ServerDialog(position);
ServerDialog.newInstance();
serverDialog.show(fragmentManager, "server_dialog");
}
ServerDialog class for adding new List entries
public class ServerDialog extends DialogFragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.settings_fragment, container);
context = getActivity().getApplicationContext();
dbh = new DbHandler(context);
etName = (EditText) view.findViewById(R.id.etName);
etAddress = (EditText) view.findViewById(R.id.etAddress);
etPort = (EditText) view.findViewById(R.id.etPort);
swtchNumDoors = (Switch) view.findViewById(R.id.swtchNumDoors);
Button btnSave = (Button) view.findViewById(R.id.btnSave);
loadData();
String title = (!newServer) ? "Edit Server" : "Add A New Server " + ID;
getDialog().setTitle(title);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
server[ID] = String.valueOf(ID);
server[SERVER_NAME] = etName.getText().toString();
server[ADDRESS] = etAddress.getText().toString();
server[PORT] = etPort.getText().toString();
if (server[ADDRESS].isEmpty() || server[PORT].isEmpty()) {
Toast.makeText(context, "Invalid Entry", Toast.LENGTH_LONG).show();
} else {
saveData();
// TODO - notify ServersActivity of change
}
}
});
return view;
}
public class ServerActivityArrayAdapter extends ArrayAdapter<Server> {
private int layout;
private String[][] values;
private int defServer;
private static LayoutInflater inflater;
ServerActivityArrayAdapter class for displaying ListView
public ServerActivityArrayAdapter(Context context, int layout, List<Server> servers) {
super(context, layout, servers);
this.layout = layout;
int i = 0;
values = new String[servers.size()][5];
for (Server server : servers) {
values[i][0] = Integer.toString(server.id);
values[i][1] = server.name;
values[i][2] = server.address;
values[i][3] = Integer.toString(server.port);
values[i][4] = Integer.toString(server.num_doors);
defServer = (server.default_server) ? i : 0;
i++;
}
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private static class ViewHolder {
private TextView tvServerName;
private CheckBox cbDefault;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View v = convertView;
try {
if(v == null) {
v = inflater.inflate(layout, parent, false);
holder = new ViewHolder();
holder.tvServerName = (TextView) v.findViewById(R.id.tvServerName);
holder.cbDefault = (CheckBox) v.findViewById(R.id.cbDefault);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.tvServerName.setText(values[position][1]);
holder.cbDefault.setChecked(defServer==position);
} catch (Exception e){
System.out.println(e);
}
return v;
}
You could use an interface and have a method in it maybe named updateListView().
Implement this interface in your FragmentActivity. In the implemented method, add code to update the listView.
And in the button code of your dialog, call ((Interfacename) getActivity).updateListView()
Your problem is in the implementation of the adapter. You are instantiating the ArrayAdapter with a List<Server> object (The super call) but then creating your own two dimensional array values to contain the data. You use the values array for the getView() method yet make no mention or show through code how you actually modify that data to update the adapter.
You should be calling back into the adapter to update it. EG, calling add(), remove(), etc. You only mention updating the DB which has nothing to do with updating your adapter. It's not linked in anyway to the DB. Even if you were to call into the previously mentioned mutate methods on the adapter, they wouldn't work unless you specifically override them. The default ArrayAdapter implementation will modify the List<Server> data and not the values two-dim array you created.
But if you find yourself override those mutate methods to support your values two-dim array...there's no point in subclassing the ArrayAdapter. Part of the point of the ArrayAdapter is handling all the data management for you. In such a situation you should be instead subclassing BaseAdapter.

How to implement listener interface in fragment?

I am trying to communicate between an activity and the fragment that sits on top of it, I want new data (image/text - retrieved from the db) to be passed into the frag every time an onclick occurs (onclick is in the activity). I made a simple interface to test (let me know if this is not suitable for images or if it is too slow or inefficient), and I am trying to have it included in my fragment so when an onclick occurs the fragment changes the image and the text.
Here is the simple interface code:
public interface FragmentCommunicator {
public void passDataToFragment(String someValue);
}
Here is the activity code:
public class RandomActivity extends FragmentActivity implements ActivityCommunicator {
//viewpager adapter
private PageAdapter mAdapter;
private ViewPager viewPager;
//interface through which communication is made to fragment
public FragmentCommunicator fragmentCommunicator;
//Buttons for yes, no, skip
Button btnYesRandom, btnNoRandom, btnSkipRandom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random);
//set buttons
btnYesRandom = (Button) findViewById(R.id.btnYesRandom);
// Initializing pager
viewPager = (ViewPager) findViewById(R.id.random_pager);
//calling bundle to attach data to fragment
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
RandomFragment randFrag = new RandomFragment();
randFrag.setArguments(bundle);
//Setting up fragment
FragmentManager fm = getFragmentManager();
mAdapter = new PageAdapter(getSupportFragmentManager(), new UserUpVotesFragment(), randFrag, new UserDownVotesFragment());
viewPager.setAdapter(mAdapter);
// Here you would declare which page to visit on creation
viewPager.setCurrentItem(1);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
// Check if this is the page you want.
if(position !=1) {
//swiping to the right
if(position == 0) {
Log.e("Swiping", "SWIPING TO THE Right BUT RESET ERR");
getIntent().removeExtra("edttext");
}
//swiping to the left
if(position == 2) {
Log.e("Swiping", "SWIPING TO THE left BUT RESET ERR");
}
// RandomFragment randomFrag = (RandomFragment) getFragmentManager().findFragmentById(R.id.fra);
viewPager.setCurrentItem(1);
}
}
});
btnYesRandom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(fragmentCommunicator != null)
fragmentCommunicator.passDataToFragment("Hi from FragmentActivity");
}
});
}
Code for Fragment:
public class RandomFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//call data from activity bundle
String strtext = getArguments().getString("edttext");
View rootView = inflater.inflate(R.layout.fragment_random, container, false);
RelativeLayout random_frag_layout = (RelativeLayout) rootView.findViewById(R.id.random_frag_layout);
activityButton = (ImageView) rootView.findViewById(R.id.imagehere);
//setRetainInstance(true);
texthere = (TextView) rootView.findViewById(R.id.texthere);
texthere.setText(strtext);
return rootView;
}
//FragmentCommunicator interface implementation
public void passDataToFragment(String someValue){
activityAssignedValue = someValue;
Log.e("ACTIVITY", activityAssignedValue);
}
}
If you have only one fragment, then you can access it directly and send any data just via method: make your fragment a field and call your passDataToFragment() on it from activity.
To access an activity from fragment, call ((RandomActivity)getActivity()).activityMethod()
What is ActivityCommunicator?
If you wish to go down this route have your RandomActivity class implement the FragmentCommunicator interface, which should either be declared as an inner-public interface in the RandomFragment class say, or publicly (or package local) in its own file.

Categories