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");
Related
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.
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 working on an app I need to send some data from ListFragment to ItemFragment. I use bundle but I get nullpointerexception. I should mention that i'm a newbie and this is my first app. so let me know if what I did is wrong or confusing. Here are my codes
ListFragment.java
if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
int position = recyclerView.getChildLayoutPosition(child);
selectedItem = mItems.get(position);
itemId = mItems.get(position).getId();
openFragment(new ItemFragment(), "MyApp");
ItemFragment if = new ItemFragment();
Bundle bundle = new Bundle();
bundle.putLong("selectedId", itemId);
if.setArguments(bundle);
}
return false;
}
ItemFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle bundledData = this.getArguments();
selectedId = bundledData.getLong("selectedId");//here is the line 105 in logcat
return mRootView;
}
Logcat
java.lang.NullPointerException
at me.myapp.fragments.ItemFragment.onCreateView(ItemFragment.java:105)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
---Added---
For some reason, I still get the same error when I tried the answers here except for nguyen's. From what I understand in nguyen's code, I use this
ListFragment.java
private long itemId;
if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
int position = recyclerView.getChildLayoutPosition(child);
selectedItem = mItems.get(position);
itemId = mItems.get(position).getId();
Bundle bundle = new Bundle();
bundle.putLong("selectedId", itemId);
ItemFragment itemFrag = ItemFragment.newInstance(bundle);
openFragment(new ItemFragment(), "Update Item");
Toast.makeText(getActivity(), "id = " + itemId, Toast.LENGTH_SHORT).show();
ItemFragment.java
private long selId;
public static ItemFragment newInstance(Bundle bundle) {
ItemFragment frag = new ItemFragment();
frag.setArguments(bundle);
return frag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (getArguments() != null) {
selId = getArguments().getLong("selectedId");
}
makeToast(""+selId);
return mRootView;
}
I didn't get any error with these codes. The toast in ListFragment does shows the correct value but the toast in ItemFragment always returns 0. what am i missing here??
To put bundle in Fragment you should use a static funtion newInstance(Bundle bundle) in your ItemFragment:
public static ItemFragment newInstance(Bundle bundle) {
ItemFragment myFragment = new ItemFragment();
myFragment.setArguments(bundle);
return myFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle bundle = getArguments();
// DO SOMETHING
return super.onCreateView(inflater, container, savedInstanceState);
}
And use it you call:
Bundle bundle = new Bundle();
//put data in bundle
ItemFragment itemfrag = ItemFragment.newInstance(bundle);
In ItemFragment, you should write in this way
Bundle bundledData = this.getArguments();
if (getArguments() != null) {
selectedId = bundledData.getLong("selectedId");
}
And you may add Toast inside the if block to check whether the selectedId get displayed or not.
Edited
ItemFragment.java
private long selId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View edit_details = inflater.inflate(R.layout.edit_staff_list, container, false);
Bundle bundle = this.getArguments();
if (getArguments() != null) {
selId = bundle.getLong("selectedId");
Toast.makeText(getActivity(), selId, Toast.LENGTH_LONG).show();
}
Try edit your code in listFragment to this.
if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
int position = recyclerView.getChildLayoutPosition(child);
selectedItem = mItems.get(position);
itemId = mItems.get(position).getId();
ItemFragment itemFragment = new ItemFragment();
Bundle bundle = new Bundle();
bundle.putLong("selectedId", itemId);
itemFragment.setArguments(bundle);
openFragment(itemFragment, "MyApp");
}
return false;
The problem with your code is you passed in a new instance of ItemFragment to openFragment() function instead of the one you created and added with a bundle.
You are creating two instances of the same fragment, setting the arguments on the second one, and showing the first one which doesn't have any arguments. Hence, the NullPointerException when you try to extract argument in onCreateView.
...
openFragment(new ItemFragment(), "MyApp"); // Show first fragment
ItemFragment if = new ItemFragment(); // Instantiate second fragment
Bundle bundle = new Bundle();
bundle.putLong("selectedId", itemId);
if.setArguments(bundle); // arguments go to the second one | The one which is never even displayed to the user.
...
After hours messing around with the code, trial and error, tried different codes, nguyen's code and the code here https://stackoverflow.com/a/16036693/5563156 gives me the idea. these codes seems to get the job done
ListFragment.java
mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
int position = recyclerView.getChildLayoutPosition(child);
selectedItem = mItems.get(position);
itemId = mItems.get(position).getId();
//pass selected item's ID to Main Activity
Intent i = new Intent(getActivity(), MainActivity.class);
i.putExtra("selectedId", itemId);
startActivity(i);
Toast.makeText(getActivity(), "id = " + itemId, Toast.LENGTH_SHORT).show();
}
return false;
}
In MainActivity's OnCreate
if(savedInstanceState == null){
//receives selected item's ID passed from ListFragment
Intent intent = getIntent();
long selId = intent.getLongExtra("selectedId", 0);
if (selId > 0) {
//send the selected item ID to ItemFragment
Bundle bundle = new Bundle();
bundle.putLong("selectedId", 0);
ItemFragment frag = new ItemFragment();
openFragment(ItemFragment.newInstance(selId), "Update Item");
frag.setArguments(bundle);
}}
ItemFragment.java
public static ItemFragment newInstance(long selId) {
ItemFragment fragment = new ItemFragment();
if (selId > 0) {
Bundle bundle = new Bundle();
bundle.putLong("selectedId", selId);
fragment.setArguments(bundle);
}
return fragment;
}
In ItemFragment's OnCreateView
Bundle args = getArguments();
if (args != null && args.containsKey("selectedId")) {
selId = args.getLong("selectedId");
}
Thanks to everyone who posted their codes! Appreciate the help.
I have two fragments and FilterFragment and LocationListFragment. when I am switching to LocationListFragment.java I am getting values in getArguments() and from LocationListFragment.java to FilterFragment.java getting null values by calling getArgument(); here is the details
In FilterFargment.java code is here for set values:
LocationListFragment locationListFragment = new LocationListFragment();
bundle = new Bundle();
Log.e("",""+locationList.getLocationListFilter().size());
bundle.putParcelable(Constant.LOCATION_LIST_FILTER, locationList);
bundle.putString(Constant.FROM_DATE_FILTER, textView_time_from.getText().toString());
locationListFragment.setArguments(bundle);
((DashbordActivity) getActivity()).switchFragment(locationListFragment, true);
In LocationListFragment.java (getting values)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
locationList = args.getParcelable(Constant.LOCATION_LIST_FILTER);
getFromDate = args.getString(Constant.FROM_DATE_FILTER);}}
And here from LocationListFragment on button click send data to FilterFragment sending new values with bundle:
FilterFragment filterFragment =new FilterFragment();//.newInstance(getFromDate, getEndDate, getLocation, getCategories);
Bundle bundle = new Bundle();
bundle.putString(Constant.FROM_DATE_FILTER, getFromDate);
bundle.putString(Constant.WHERE_FILTER, getLocation);
filterFragment.setArguments(bundle);
((DashbordActivity) getActivity()).switchFragment(filterFragment, true);
and in FilterFragment.java while returning back getting null value for getArguments(); code is here:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_filter, container, false);
Log.e("FilterFragment", "oncreateview");
Bundle args = getArguments();
Log.e("getArguments", "" + getArguments());//getting null here
Also, I have used this method for switching fragment,
public void switchFragment(BaseFragment fragment, boolean keep) {
FragmentManager manager = getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate(fragment.getClass().getSimpleName(), 0);
if (!fragmentPopped && manager.findFragmentByTag(fragment.getClass().getSimpleName()) == null) { //fragment not in back stack, create it.
FragmentTransaction tr = manager.beginTransaction();
tr.replace(R.id.container, fragment, fragment.getClass().getSimpleName());
if (keep) {
tr.addToBackStack(fragment.getClass().getSimpleName());
Log.e("keep", "BaseAct:" + keep);
}
tr.commit();
}
}
Can you tell me what I am missing? Any help will be appreciated.
I don't understand how to transfer data between two fragments. I've tried this:
public class Connection extends Fragment
{
SendMessage sender;
public interface SendMessage
{
public void send(String one, String two);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
//my data
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
send = (SendMessage) getActivity();
}
private class AlarmReceiver extends BroadcastReceiver
{
public void onReceive(final Context context, Intent intent)
{
if(message.equals("POS"))
{
sender.send(position,id);
}
}
}
in the first fragment; in the MainActivity:
public class MainActivity extends FragmentActivity implements Connection.SendMessage
{
protected void onCreate(Bundle savedInstanceState)
{
//my code
}
#Override
public void send(String one, String two)
{
Map map = new Map();
final Bundle bundle = new Bundle();
bundle.putString("Position",one);
bundle.putString("ID:",two);
map.setArguments(bundle);
}
}
and in the Map fragment(it need to receive this data):
public class Map extends Fragment
{
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Bundle bundle = new Bundle();
bundle.getArguments();
if (bundle != null)
{
String pos = bundle.getString("Position");
String id = bundle.getString("ID");
}
//then show this on googleMaps
}
}
but I don't understand why this code doesn't work..could you help me? thanks...
1) Please change your class name from Map.java to anything else. Because in java map is imported as java.util Package.
2)
Fragment map = new Fragment ();
final Bundle bundle = new Bundle();
bundle.putString("Position",one);
bundle.putString("ID:",two);
map.setArguments(bundle);
map.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, map).commit();
and in recieve
Bundle bundle = getArguments();
if (bundle != null)
{
String pos = bundle.getString("Position");
String id = bundle.getString("ID:"); (You miss : in ID)
}
Do This send fragment
String cid=id.getText().toString();
Fragment fr=new friendfragment();
FragmentManager fm=getFragmentManager();
android.app.FragmentTransaction ft=fm.beginTransaction();
Bundle args = new Bundle();
args.putString("CID", cid);
fr.setArguments(args);
ft.commit();
Received fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("CID");
return inflater.inflate(R.layout.fragment, container, false);
}
Well, firstly. Your receiving fragment is actually accessing an empty bundle. You are doing this:
Bundle bundle = new Bundle();
bundle.getArguments();
Instead of:
Bundle bundle = getArguments();
Secondly, a good way to communicate between two fragments is by using an interface. The interface communicates with the activity and the activity with the second fragment.
Here's google's tutorial:
http://developer.android.com/training/basics/fragments/communicating.html
Also, it doesn't seem like you are inflating any xml layout file for your Map Fragment or even adding it with FragmentTransaction after you have created it. Here is a short and sweet tutorial for that as well:
http://android-er.blogspot.com/2011/12/programmatically-add-fragment.html