I want to pass data from Activity to Fragment using Bundle (I used Bundle to passing data between 2 Fragment, and that's worked).
In my Activity I have a ListView, in the OnItemClickListener I want to open a new Fragment, and the Item, which clicked pass through the Activity to this Fragment. But the Item is null, so basically nothing is send to the Fragment.
Here is my Activity:
public class Jegyek extends AppCompatActivity {
View v;
DB mydb;
ListView listView;
private String teszt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jegyek);
listView = (ListView)findViewById(R.id.jegyekLista);
mydb = new DB(this);
final ArrayList<String> thelist = new ArrayList<>();
Cursor data = mydb.getTantargynev();
if (data.getCount() == 0) {
Toast.makeText(this, "Nincs jegyek hozzáadva", Toast.LENGTH_SHORT).show();
}
else {
while (data.moveToNext()) {
thelist.add(data.getString(0));
ListAdapter listadapter = new ArrayAdapter<>(this, 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();
bundle.putString("Tantárgy neve", teszt);
Toast.makeText(Jegyek.this, teszt, Toast.LENGTH_SHORT).show();
Fragment jegyekAllando = new jegyekAllando();
jegyekAllando.setArguments(bundle);
FragmentTransaction FragTan = getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.jegyekMenu, jegyekAllando);
ListView listaNezet = (ListView) findViewById(R.id.jegyekLista);
listaNezet.setVisibility(View.GONE);
FragTan.commit();
}
}
);
}
}
public String getTanNev () {
System.out.println("WARNING: "+ teszt);
return teszt;
}
}
And my 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 = new Bundle();
String tanNev = bundle.getStrin
g("Tantárgy neve");
Jegyek jegyAct = new Jegyek();
String tanNevv = jegyAct.getTanNev();
mydb = new DB(getActivity());
String jegyAtlag =String.valueOf(mydb.JegyekAtlaga(tanNev));
String jegyDarab =String.valueOf(mydb.JegyekDarabszama(tanNev));
return rootView;
}
}
When I realized, that the bundle is null, I try to pass that List Item through getter, so I changed my Fragment code for that:
Jegyek jegyek = new Jegyek();
String jegy = jegyek.getTanNev();
But that's not solved my problem, so I back to the Bundle, which also have some problem, but I can't find it. Intresting, that in the OnItemClickListener when I Toast the Item it's correct and works, but when I want to display in the console or pass to the Fragment, the value's is null.
From Activity you send data with intent as:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
Hope this helps
Please follow this example:
In your activity, Pass data like
Bundle bundle = new Bundle();
bundle.putString("test", "Test Data");
// set in your testFragment Arguments
TestFragment testFragment = new TestFragment();
testFragment.setArguments(bundle);
And Receive Data from your TestFragment Like
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String text = getArguments().getString("test");
return inflater.inflate(R.layout.fragment, container, false);
}
In fragment "jegyekAllando" you must get your string from onCreate() with Bundle data = getArguments(), but you create new bundle.
Related
I try to pass data from recyclerview viewholder adapter to another fragment, only i got is text but images do not show, i tries different codes but no image show, it shows blank, image not display. if i use picasso it gives target must not be zero error
my adapter
Picasso.with(context).load(image).fit().into(holder.clothImage);
holder.clothImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Clicked", Toast.LENGTH_SHORT).show();
holder.btn_add_to_cart.setText("Clicked");
GoodDetailFragment detailFragment = new GoodDetailFragment();
AppCompatActivity activity = (AppCompatActivity) v.getContext();
GoodDetailFragment detailFragment1 = new GoodDetailFragment().newInstance(itemList.get(pos).getPrice(), itemList.get(pos).getIcon(), itemList.get(pos).getName());
activity.getSupportFragmentManager()
.beginTransaction()
.replace(R.id.realtabcontent, detailFragment1)
.addToBackStack(null).commit();
}
});
and my next fragment (detail fragment)
*/
public class GoodDetailFragment extends BaseFragment {
private static final String GOOD_PRICE = "";
private static final String GOOD_IMG = "GOOD_IMG";
private static final String GOOD_TITLE = "GOOD_IMG";
#BindView(R.id.dela_img)
DraweeView goodImg;
#BindView(R.id.bei_dela)
TextView delaPrice;
public GoodDetailFragment newInstance(String price, int icon, String title) {
Bundle bundle = new Bundle();
//bundle.putInt(GOOD_IMG, icon);
bundle.putString(GOOD_PRICE, price);
bundle.putString(GOOD_TITLE, title);
bundle.getInt(GOOD_IMG, icon);
GoodDetailFragment detailFragment = new GoodDetailFragment();
detailFragment.setArguments(bundle);
return detailFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO: inflate a fragment view
View rootView = super.onCreateView(inflater, container, savedInstanceState);
ButterKnife.bind(this, rootView);
return rootView;
}
#Override
public View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_good_detail, container, false);
ButterKnife.bind(this, view);
return view;
}
#Override
public void init() {
int image = getArguments().getInt(GOOD_IMG);
String price = getArguments().getString(GOOD_PRICE);
String tittle = getArguments().getString(GOOD_TITLE);
Uri uri = Uri.parse(String.valueOf(image));
//Picasso.with(getContext()).load(image).fit().into(goodImg); //GIves Error : Resource ID must not be zero.
delaPrice.setText(price);
Bitmap bitmap = BitmapFactory.decodeFile(String.valueOf(new File(String.valueOf(image))));
// goodImg.setImageBitmap(bitmap); // no image show
goodImg.setImageURI(uri);// still no image show
//Picasso.with(getContext()).load(uri).into(goodImg);// still no image show
if there is way i can get image from recycler view to detail fragment, please help
This is my view holder class inside adapter class which is a separate class file. The recycler view is shown in a fragment and on click of the recycler view item I need to go to a new fragment activity and get the texts that was shown in the clicked item
public class BookViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public final BookRecyclerAdapter mAdapter;
private TextView titleTextView, authorTextView;
public BookViewHolder(View itemView, BookRecyclerAdapter adapter) {
super(itemView);
titleTextView = (TextView) itemView.findViewById(R.id.listItem_title_tView);
authorTextView = (TextView) itemView.findViewById(R.id.listItem_author_tView);
this.mAdapter = adapter;
itemView.setOnClickListener(this);
}
private void setBookCardView(String tText, String aText){
titleTextView.setText(tText);
authorTextView.setText(aText);
}
#Override
public void onClick(View v) {
String title = titleTextView.getText().toString();
String author = authorTextView.getText().toString();
//I NEED TO PASS THIS STRINGS TO NEW FRAGMENT
}
}
How can a start a new fragment activity which can access these two strings - title and author
In the onClick method of the view holder class
Bundle bundle = new Bundle();
bundle.putString("key", "value");
bundle.putString("key", "value");
SecondFragment secondFragment = new SecondFragment();
secondFragment.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) v.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, secondFragment).addToBackStack(null).commit();
After this you can start to retrieve the data in the fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment, container, false);
String strtext=getArguments().getString("string1"); //fetching value by key
String strtext1=getArguments().getString("string2");
}
Use Bundle to pass data adapter to fragment in your click Listener
Fragment fragment = new FragmentName();
FragmentManager fragmentManager = context.getSupportFragmentManager(); // this is basically context of the class
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Bundle bundle=new Bundle();
bundle.putString("string1", "your string");
bundle.putString("string2", "your string"); //key and value
//set Fragmentclass Arguments
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
and retrieve data in fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment, container, false);
String strtext=getArguments().getString("string1"); //fetching value by key
String strtext1=getArguments().getString("string2");
}
In the view holder class onClick:
Bundle bundle = new Bundle();
bundle.putString("key", "value");
bundle.putString("key", "value");
SecondFragment secondFragment = new SecondFragment();
secondFragment.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) v.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, secondFragment).addToBackStack(null).commit();
In the recieving fragment
View view = inflater.inflate(R.layout.fragment_book, container, false);
Bundle bundle = this.getArguments();
if(bundle != null){
Snackbar.make(view, bundle.get("key").toString(), Snackbar.LENGTH_LONG).show();
}
Actually i am sending bundle from my base adapter to a new fragment. how I send bundle from adapter to frament.
here is my adapter code:
textViewItemName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ExpandableCategoryList fragment = new ExpandableCategoryList();
Bundle bundle = new Bundle();
bundle.putInt("Id",Id);
fragment.setArguments(bundle);
((MainActivity)context).replaceFragment(fragment,
"TAG",null,false);
//Log.e("Hello",fragment.toString());
}
});
and i am receiving mu bundle as
int id = getArguments().getInt("Id",0);
but i am getting that getArguments().getInt() throws null point exception. How I handle it
In your Adapter, write the code
ExpandableCategoryList fragmentProductLaptop = new ExpandableCategoryList();
FragmentTransaction fragmentTransaction=context.getSupportFragmentManager().beginTransaction();
Bundle args = new Bundle();
args.putString("Name",category.getCategoryName());
args.putInt("Id",category.getId());
fragmentProductLaptop.setArguments(bundle);
fragmentTransaction.replace(R.id. homeFrameLayout, fragmentProductLaptop);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
In your Fragment Class, write the below code :
public class ExpandableCategoryList extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String name = getArguments().getString("Name");
String Id = getArguments().getInt("Id",0);
return inflater.inflate(R.layout.fragment, container, false);
}
}
I'm trying to pass a CategoryID from Firebase from one fragment to another
using an ImageView Click but my app crashes when an ImageView is clicked.
Here is my code;
MenuFragment.java
FirebaseRecyclerAdapter<Category, MenuViewHolder> adapter;
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
CarListFragment cfragment= new CarListFragment ();
Bundle bundle = new Bundle();
bundle.putString("CategoryID",adapter.getRef(position).getKey());
cfragment.setArguments(bundle);
getFragmentManager().beginTransaction()
.replace(R.id.frame_main, cfragment, cfragment.getTag())
.addToBackStack(null)
.commit();
}
});
CarListFragment.java
String CategoryID="";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.fragment_car_list, container, false);
Bundle bundle = this.getArguments();
if (bundle != null) {
CategoryID=getActivity().getIntent().getStringExtra("CategoryID");
}
if(!CategoryID.isEmpty()&& CategoryID!=null){
loadCarList(CategoryID);
}
return v;
}
Logcat
Use bundlebecause it has the data
Bundle bundle = this.getArguments();
if (bundle != null) {
CategoryID = bundle.getString("CategoryID");
// ^^^^^^
}
instead of
CategoryID=getActivity().getIntent().getStringExtra("CategoryID");
because getActivity().getIntent() will give you an Intent object which was previously used to start your activity
use this:
CarListFragment cfragment= new CarListFragment ();
Bundle bundle = new Bundle();
bundle.putString("CategoryID", adapter.getRef(position));
cfragment.setArguments(bundle);
getFragmentManager().beginTransaction()
.replace(R.id.frame_main, cfragment, cfragment.getTag())
.addToBackStack(null)
.commit();
get String:
String str = getArguments().getString("my_string");
I want to pass string value from activity to fragment. For that I'm using bundle for transferring string value.
PUT STRING ACTIVITY
Passing string value :-
Bundle bundle = new Bundle();
bundle.putString("Value", resultp.get(CurrentProjectActivity.VALUE));
Log.d(TAG, "Value ::: " + resultp.get(CurrentProjectActivity.VALUE));
// set Fragmentclass Arguments
AmenetiesFragment fragobj = new AmenetiesFragment();
fragobj.setArguments(bundle);
In log I got "Value" value as well.
GET STRING VALUE IN FRAGMENT (IT IS NOT WORKING).
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_listview, container, false);
Bundle bundle = this.getArguments();
Log.d(TAG, "Value's value:) ::: " + bundle);
String strtext = bundle.getString("Value");
return rootView;
}
In log I'm getting NULL value for BUNDLE. Please help me to resolve this Issue. Thanks in advance.
I advice you to follow this link1 and this . You should use interface. Check here
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in the Frament task
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
Suppose you want to send String data from Activity to Fragment
In Fragment.java file add the following code,
public static String name= null;
public void setName(String string){
name = string;
}
In MainActivity.java from which you want to send String add the following code,
String stringYouWantToSend;
Fragment fragment = new Fragment();
fragment.setName(stringYouWantToSend);
The savedInstance variable will be empty the first time you run your app,
it only gets filled when the onSaveInstanceState method is called, this usually happens when you rotate the screen, then savedInstance variable will be populated. Try this :
if(savedInstance != null){
Log.d(TAG, "There's is something");
}else{
Log.d(TAG, "Nothing in there");
}
First time in logcat you will see the first message, try turning your device and the message in the else will show.
As #james said, the recommended way is to use interfaces, or have a field class but this increases coupling and destroys the whole point of fragments.
make public first in activity that object you required in fragment.
then you can use like ((ACtivityName)getActivity()).objectName;
i hope it help.this is not best way to pass data into fragment.
there are some other way also.
create constructor of your fragment class and pass it and save in fragment like:
public MyFragment(String data){
this.data = data;
}
also you can use as bundle #james answer.
EDIT:-
First Way
private class MyFeagment extends Fragment {
private String data;
private Object myObject;
public MyFeagment(String data, Object anyObject) {
this.data = data;
this.myObject = myObject;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("My Fragment", "data :: " + data + " and myObject :"
+ myObject);
return super.onCreateView(inflater, container, savedInstanceState);
}
}
let's say it is your framgnet.
and put this code in your activity
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.fragment_container, new MyFeagment("My Data",
"data"));
transaction.commit();
Easiest Approach but not Recommended
You can access activity data from fragment:
Activity:
public class MyActivity extends Activity {
private String myString = "hello";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
...
}
public String getMyData() {
return myString;
}
}
Fragment:
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MyActivity activity = (MyActivity) getActivity();
String myDataFromActivity = activity.getMyData();
return view;
}
}