I was trying to inflate a same fragment through a fragment and passing arguments, its working but the arguments which are passed are applied on the previous fragment but not on the new fragment.
The fragment contains a TextView and a Spinner.
fragment class:
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.myfragment,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle b = getArguments();
qust = b.getString("Question","");
id = b.getInt("id");
final connection con = (connection) getActivity();
question = (TextView) getActivity().findViewById(R.id.question);
spinner = (Spinner) getActivity().findViewById(R.id.spinner);
question.setText(qust);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),id,R.layout.support_simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (i!=0)
con.inflate();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
I am inflating a fragment when the user selects any item in the previous fragment spinner.
MainActivity class:
public class MainActivity extends AppCompatActivity implements connection {
int count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyFragments mF = new MyFragments();
Bundle b = new Bundle();
b.putString("Question","Where are you?");
b.putInt("id",R.array.planets_array);
mF.setArguments(b);
FragmentManager manage = getFragmentManager();
FragmentTransaction trans = manage.beginTransaction();
trans.add(R.id.root,mF,"frag");
trans.commit();
}
#Override
public void inflate() {
MyFragments f = new MyFragments();
Bundle b = new Bundle();
b.putString("Question","what are you doing?");
b.putInt("id",R.array.colours);
f.setArguments(b);
FragmentTransaction tran = getFragmentManager().beginTransaction();
tran.add(R.id.root,f,"added");
tran.commit();
}
}
interface to communicate b/w fragments:
public interface connection {
void inflate();
}
screenshot
I think that has been occurred, because you instantiate new fragment on
your inflate() method without unique TAG. Set up unique TAG or use different add(#IdRes int containerViewId, Fragment fragment) instead.
Related
I am frustrated.
i want to get value from child fragment to parent fragment
i had tries many method.
interface, viewModel, sharedpreferences but no one work.
I had follow this method
but it doesn't work for me.
here my code parent fragment:
public class Chart_Fragment extends Fragment
implements Product_Fragment.pf_interface {
String dt;
TextView tv;
public Chart_Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.chart_fragment, container, false);
// create product_fragment as childfragment
FragmentManager fm = getChildFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Product_Fragment product_fragment = new Product_Fragment();
ft.replace(R.id.fl_two, new Product_Fragment());
ft.commit();
return v;
}
public void onViewCreated(View v, Bundle savedInstanceState){
super.onViewCreated(v,savedInstanceState);
tv = (TextView)v.findViewById(R.id.rcv);
}
#Override
public void data(String d) {
FragmentManager fragmentManager = getChildFragmentManager();
Product_Fragment product_fragment =
(Product_Fragment)fragmentManager.findFragmentByTag("data");
if(product_fragment != null){
String dt = d;
tv.setText(dt);
}
}
}
and my childfragment is :
public class Product_Fragment extends Fragment {
private pf_interface pf;
public Product_Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.product_fragment, container, false);
Button b = (Button)v.findViewById(R.id.btn_sender);
b.setOnClickListener(new btnClick());
return v;
}
public void onAttachToParentFragment(Fragment fragment){
try {
pf = (pf_interface)fragment;
}catch (ClassCastException e){
throw new ClassCastException(
fragment.toString()+ "must implement pf_interface"
);
}
}
public void onCreate(Bundle savedInstanceState){
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
onAttachToParentFragment(getParentFragment());
}
private class btnClick implements View.OnClickListener{
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_sender:
if(pf != null){
pf.data("button click interface");
}break;
}
}
}
public interface pf_interface{
void data(String d);
}
}
textview on parent fragment didn't show the string d ("button click interface")from child fragment
Why you're checking for child fragment in callback on your parent fragment ?
#Override
public void data(String d) {
FragmentManager fragmentManager = getChildFragmentManager();
Product_Fragment product_fragment =
(Product_Fragment)fragmentManager.findFragmentByTag("data");
if(product_fragment != null){ // Why to check for child fragment nullability?
String dt = d;
tv.setText(dt);
}
}
You can directly use like this:
#Override
public void data(String d) {
tv.setText(d);
}
Note: on any certain scenario if any of object is null, your callback won't be executed. You've already check for null reference.
i have made two fragments in my app.
1st fragment (EditFrag) and 2nd fragment (ListTable). i want to transfer the value of 1st fragment(from EditText of 1st fragment) to the recyclerView of 2nd fragment.
how should i do that.....i can't find right documentation.
Thank you for your concern!
MainActivity:
public class MainActivity extends AppCompatActivity implements EditFrag.TransferValue{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListTable frag1=new ListTable();
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.table_value_container,frag1,"fragment");
transaction.commit();
EditFrag frag2=new EditFrag();
FragmentManager manager1=getSupportFragmentManager();
FragmentTransaction transaction1=manager1.beginTransaction();
transaction1.add(R.id.table_container,frag2,"fragment_edit");
transaction1.commit();
}
#Override
public void sendValue(String value) {
Log.d("ashu","button is pressed");
ListTable listTable = (ListTable) getSupportFragmentManager().findFragmentById(R.id.table_value_container);
listTable.receiveValue(value);
}
}
2nd fragment(ListTable):
public class ListTable extends Fragment {
public TextView myEditText1;
private RecyclerView recyclerView;
public ListTable() {
// Required empty public constructor
}
public static ListTable newInstance(String param1, String param2) {
ListTable fragment = new ListTable();
Bundle args = new Bundle();
Log.d("ashu", "new instance is called :");
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("ashu", "oncreata called by inflating: ");
View view = inflater.inflate(R.layout.fragment_list_table, container, false);
myEditText1 = (TextView) container.findViewById(R.id.table_value);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
MyAdapter a = new MyAdapter();
recyclerView.setAdapter(a);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
public void receiveValue(String value) {
myEditText1.setText(value);
}
public class MyAdapter extends RecyclerView.Adapter<MyDataViewHolder> {
#Override
public MyDataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d("ashu", "oncreateview holder of adapter ia called");
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.fragment_list_table, parent, false);
return new MyDataViewHolder(view);
}
#Override
public void onBindViewHolder(MyDataViewHolder holder, int position) {
holder.myEditText.setText("Table: " + position);
}
#Override
public int getItemCount() {
return 10;
}
}
public class MyDataViewHolder extends RecyclerView.ViewHolder {
public TextView myEditText;
public MyDataViewHolder(View itemView) {
super(itemView);
Log.d("ashu", "DAta view holder is called: ");
myEditText = (TextView) itemView.findViewById(R.id.table_value);
}
}
}
1st Fragment(EditFrag):
public class EditFrag extends Fragment {
TransferValue SendData;
EditText inputvalue;
Button click;
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.edit_frag_layout, container, false);
inputvalue = (EditText) view.findViewById(R.id.edit_text);
click = (Button) view.findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String received = inputvalue.getText().toString();
SendData.sendValue(received);
}
});
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SendData = (TransferValue) context;
} catch (ClassCastException e) {
Log.d("ashu", "implement the methods");
throw new ClassCastException("implemented the methods");
}
}
public interface TransferValue {
public void sendValue(String value);
}
}
create the instance of fragment2 from where want to receive the value to:
public static Fragment2 createInstance(String data) {
Fragment2 fragment = new Fragment2();
Bundle bundle = new Bundle();
bundle.putString("keyword", data);
fragment.setArguments(bundle);
return fragment;
}
and the get the data as below:
Bundle bundle = getArguments();
if (bundle != null) {
String data = bundle.getString("data");
}
You can use bundle in an order to pass data to fragment:
Example:
// Set bundle as arguments to the fragment
Bundle bundle = new Bundle();
bundle.putString(MyKey1, MyValue1);
bundle.putString(MyKey2, MyValue2);
MyFragment myFragment = new MyFragment();
myFragment.setArguments(bundle);
Inside onCreateView of fragment:
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.repairer_part_details_fragment, container, false);
String value1 = getArguments().getString(MyKey1);
String value2 = getArguments().getString(MyKey2);
return view;
}
There are many ways to do that. I see your codes above, and 2 fragments loaded at the same time. I usaually use one of 2 ways below to do it.
The first solution: You can use this link using obserable pattern to communication 2 fragments.
The second solution: you can use EventBus lib for communication, it 's very simple
How to start a fragment Insted of opening new Activity, OnClick its opening new Activity, Is there any way I can open fragment.
#Override
protected void onPostExecute(List<MovieModel> result) {
super.onPostExecute(result);
final MovieAdapter adapter = new MovieAdapter( getActivity().getApplicationContext(), R.layout.rownew, result );
//// getApplicationContext() // getActivity is added by me
lvMovies.setAdapter(adapter);
//set data to list
lvMovies.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Toast.makeText(getActivity().getBaseContext(),parent.getItemIdAtPosition(position)+" is selected",Toast.LENGTH_LONG).show();
MovieModel movieModel = (MovieModel) adapter.getItem(position);
Intent intent = new Intent("sanjay.apackage.torcente.com.torcentemotors.productdesc");
intent.putExtra("productimage", movieModel.getProduct_image());
//sanjay //
intent.putExtra("productname",movieModel.getProduct_name());
intent.putExtra("productprice", movieModel.getProduct_price());
intent.putExtra("productcolor", movieModel.getProduct_color());
intent.putExtra("originalprice", movieModel.getOriginal_price());
intent.putExtra("appdesc", movieModel.getApp_desc());
startActivity(intent);
/*
Fragment fragment_productdesc = new fragment_productdesc();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.main_container, fragment_productdesc ); // give your fragment container id in first parameter
transaction.addToBackStack(null); // if written, this transaction will be added to backstack
transaction.commit(); */
}
});
}
I think you want to send data from activity to fragment so please try this method to send data from your activity to method.
Create a custom fragment extending fragment put arguments and initialize.
public class MyFragment extends Fragment {
private View rootView;
private int type;
public MyFragment() {
// Required empty public constructor
}
public static MyFragment newInstance(int type, Object object) {
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("type", type);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
type = getArguments().getInt(Key.TYPE);
}
}
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_slider, container,false);
return rootView;
}
Activity A
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ActivityA);
Bundle b = new Bundle();
b.putString("mobile", "123456789");
FragmentA fragmentA = new FragmentA ();
fragmentA .setArguments(b);}
FragmentA
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_fragmentA, container, false);
String txtMobile = getArguments().getString("mobile");
Log.i("mobile2",txtMobile);
mobile.setText(txtMobile);}
I have tried above solution but showing error that
Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
May be It's about the way you are adding fragment to the class:
Bundle b = new Bundle();
b.putString("mobile", "123456789");
FragmentA fragmentA = new FragmentA ();
fragmentA .setArguments(b);
fm.beginTransaction()
.replace(placeholder, new FragmentA(), tabId)
.commit();
can you provide more data about how did you add it ?
Create your fragment like this
public static MyFragment newInstance(String string) {
Bundle args = new Bundle();
args.putString("string",string);
MyFragment fragment = new MyFragment();
fragment.setArguments(args);
return fragment;
}
And then in Fragment onCreate use getArguments() for pulling that String. Don't forget to check getArguments() for null.
Try to fetch the argument in onCreate method of fragment with default value constructor:
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String txtMobile = getArguments().getString("mobile", "");
}
and make sure you commit the fragment transaction after settting the arguments in fragment. :)
First check that your argument is not null.
For example
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_fragmentA, container, false);
if(getArguments()!=null){
String txtMobile = getArguments().getString("mobile");
Log.i("mobile2",txtMobile);
mobile.setText(txtMobile);
}
}
try this:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null){
String txtMobile = savedInstanceState.getString("mobile");
}
}
you can use inteface to pass data from activity to fragment
In your activity
public interface FragmentRefreshListener {
void onRefresh(String mydata);
}
public FragmentRefreshListener fragmentRefreshListener;
public void setFragmentRefreshListener(FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListener = fragmentRefreshListener;
}
public FragmentRefreshListener getFragmentRefreshListener() {
return fragmentRefreshListener;
}
Then inside your fragment add below code
((MainActivity) getActivity()).setFragmentRefreshListener(new MainActivity.FragmentRefreshListener() {
#Override
public void onRefresh(String mydata) {
// write your logic here
}
});
use following in your activity to pass data from activity to fragment
getFragmentRefreshListener().onRefresh("dummy text");
I am making a list that will be placed under another view.
Based on the other article, i should contain the other view in the header of the listview.
I am using ListFragment and will be attached to several activity. So I am creating a method to set the header of the ListFragment.
The problem is the getListView() method is returning null, although I call the addHeader after the list is shown.
Why is the the getListView() is always null?
Here is my code:
public class NewsListFragment extends ListFragment {
private final int topNewsCount = 5;
private DBNewsDataSource dataSource;
private Activity myActivity;
private Context myContext;
private boolean isHome;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
isHome = true;
myActivity = getActivity();
Bundle extras = myActivity.getIntent().getExtras();
if (extras != null) {
isHome = extras.getBoolean("isHome");
}
dataSource = new DBNewsDataSource(getActivity());
dataSource.open();
List<DBNews> news = dataSource.getAllNews();
List<String> titleList = new ArrayList<String>();
dataSource.close();
for(int i = 0; i< (isHome?topNewsCount:news.size()); i++)
{
titleList.add(news.get(i).getTitle());
}
NewsListArrayAdapter adapter = new NewsListArrayAdapter(getActivity(),news,titleList,isHome);
setListAdapter(adapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Do something with the data
}
public void addHeader(View v)
{
ListView lv = getListView();
lv.addHeaderView(v);
}
Here is the activity that call the Fragment
public class HomeActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.template_activity_home);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
NewsListFragment frgNews = new NewsListFragment();
MainSlideShowFragment frgSS = new MainSlideShowFragment();
View vw = frgSS.getView();
frgNews.addHeader(vw);
fragmentTransaction.add(R.id.layout_news_list , (Fragment) frgNews);
fragmentTransaction.commit();
//frgNews.addHeader(vw);
}
Override onCreate view and let it returns a View wich contains a ListView with id android:id="#android:id/list"
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.cart_list,
null);
return view;
}
You are using a fragment but haven't called
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.example_fragment, container, false);
}
This is where the layout will be inflated. Hence it is null as it is not yet inflated.