Getting null while passing data through a bundle from Activity to Fragment - java

Losing data on the way when passing it through bundle, i get
Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object
reference at String bundlePassData = this.getArguments().getString("tagName");
Here it's a sample of my code. MainActivity->
tagsView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Bundle bundle = new Bundle();
TextView textView = (TextView) view.findViewById(R.id.tagName);
String selectedItemName = textView.getText().toString();
bundle.putString("tagName", selectedItemName);
TaskAssignFragment taskAssignFragment = new TaskAssignFragment();
taskAssignFragment.setArguments(bundle);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.commit();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new TaskAssignFragment()).addToBackStack(null).commit();
Log.i("ListView", selectedItemName);
}
});
TaskAssignFragment->
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_assign, container, false);
TextView test = view.findViewById(R.id.testerView);
String bundlePassData = this.getArguments().getString("tagName");
test.setText(bundlePassData);
return view;
}
Should I try interfaces? But if i would i need the data as a variable, not in only a function, because i would use it in more places in my fragment.

In your code You are creating new fragment when replacing.
TaskAssignFragment taskAssignFragment = new TaskAssignFragment();
taskAssignFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new TaskAssignFragment()).addToBackStack(null).commit();
use the fragment instance you already created in which you set arguments
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
taskAssignFragment).addToBackStack(null).commit();

You can call method directly on fragment e.g:
TaskAssignFragment taskAssignFragment = new TaskAssignFragment();
// Call here your own method (from fragment)
taskAssignFragment.setSelectedItemName(selectedItemName);
And in your fragment:
public void setSelectedItemName(String selectedItemName) {
// Store data as field in class
this.selectedName = selectedItemName
}
where selectedName is field in your class.

tagsView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Bundle bundle = new Bundle();
TextView textView = (TextView) view.findViewById(R.id.tagName);
String selectedItemName = textView.getText().toString();
bundle.putString("tagName", selectedItemName);
TaskAssignFragment taskAssignFragment = new TaskAssignFragment();
taskAssignFragment.setArguments(bundle);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.commit();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
taskAssignFragment).addToBackStack(null).commit();
Log.i("ListView", selectedItemName);
}
});
Please try this code, you create a new instance of TaskAssignFragment() and pass it without arguments

You are making a new object while replacing fragment.
TaskAssignFragment taskAssignFragment = new TaskAssignFragment();
taskAssignFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
taskAssignFragment).addToBackStack(null).commit();
Try this out

Related

In my code getArgument is returning null every time

I have tried each and every type of solution but the fragment get argument method is returning null always.
This is my fragment code.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main_activity, container, false);
**String data1 = getArguments().getString("data");
Toast.makeText(getActivity(), getArgument1, Toast.LENGTH_SHORT).show();**
}
In the above code data1 always return null.
This is my main activity code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
chipNavigationBar = findViewById(R.id.bottomNavBar);
chipNavigationBar.setItemSelected(R.id.home, true);
getSupportFragmentManager().beginTransaction().replace(R.id.container1, new mainActivityFragment()).commit();
chipNavigationBar.setOnItemSelectedListener(new ChipNavigationBar.OnItemSelectedListener() {
#Override
public void onItemSelected(int i) {
Fragment fragment = null;
switch (i) {
case R.id.home:
**fragment = new mainActivityFragment();
Bundle bundle = new Bundle();
bundle.putString("data","anything");
fragment.setArguments(bundle);**
break;
case R.id.menu:
fragment = new menuFragment();
break;
case R.id.corona:
fragment = new CoronaFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.container1, fragment).commit();
}
});
}
I am concerned that there are 2 places you load the mainActivityFragment() - the first is by default, when there are no bundle args, and the second time when the chipNavigationBar. setOnItemSelectedListener is called. Maybe try something like this:
static mainActivityFragment createMainActivityFragment() {
mainActivityFragment fragment = new mainActivityFragment();
Bundle bundle = new Bundle();
bundle.putString("data","anything");
fragment.setArguments(bundle);
return fragment;
}
//IN ONCREATE:
getSupportFragmentManager().beginTransaction().replace(R.id.container1, mainActivityFragment.createMainActivityFragment()).commit();
//IN THE SWITCH
case R.id.home:
fragment = mainActivityFragment.createMainActivityFragment()
break;
Then both instances should have the bundle

java.io.Serializable android.os.Bundle.getSerializable(java.lang.String)' on a null object reference

The MainFragment pass the data to ActivityContentFragment but got the error that "java.io.Serializable android.os.Bundle.getSerializable(java.lang.String)' on a null object reference"
Mainfragment
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ActivityInfo activityInfo =(ActivityInfo) listView.getItemAtPosition(position);
Fragment fragment = new Fragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.content,new ActivityContentFragment());
Bundle bundle = new Bundle();
bundle.putSerializable("eventName",activityInfo);
fragment.setArguments(bundle);
fragmentTransaction.commit();
}
});
}
ActivityContentFragment
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_activity_content, container, false);
activityInfo= (ActivityInfo)getArguments().getSerializable("eventName");
Log.d("why","eventName="+ activityInfo.eventName);
return view;
}
ActivityInfo class
public class ActivityInfo implements Serializable {
public String eventName;
public String date;
public String review;
public String toString(){
return this.eventName;
}
}
Fragment fragment = new Fragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
// The actual instance of the ActivityContentFragment is created here:
fragmentTransaction.replace(R.id.content,new ActivityContentFragment());
Bundle bundle = new Bundle();
bundle.putSerializable("eventName",activityInfo);
// This Fragment is not your ActivityContentFragment:
fragment.setArguments(bundle);
fragmentTransaction.commit();
You're creating an instance of Fragment and applying the Bundle to that instance. You never apply the Bundle to the ActivityContentFragment that you're actually committing.
Instead, you can use:
ActivityContentFragment fragment = new ActivityContentFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("eventName", activityInfo);
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.content, fragment).commit();

Getting a String to another activity

(i want to make an app to show 40 articles of a news website.) I have a problem with getting a String to another class. I have a String "link" in my "Menu1.java" and want to use it in the "Menu1_1_Artikel.java".
The Getter Method is working. But i dont know how to set the value of "link".. Every time i try it it only gets "null" instead of the link of the article which is clicked on the listview. :/
public class Menu1 extends Fragment {
private ListView lv; //Listview which shows 40 articles from a news website
private ArrayAdapter adapter;
public ArrayList liste = new ArrayList();
private ProgressDialog progressDialog;
private String[] myStringArray = new String[40]; //Array with 40 URLs
public String link;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu_1, container, false);
lv = (ListView)view.findViewById(R.id.list);
adapter = new ArrayAdapter(getActivity(), R.layout.list_item, liste);
new datenAbrufen().execute(); //Method which loads the 40 articles
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
link = myStringArray[position]; //Save the URL to the article which is clicked on the listview to "link"
Menu1 obj = new Menu1();
obj.setLink(link); //I think here is the problem because the value is not in the Getter Method..
Toast.makeText(getActivity(), link, Toast.LENGTH_LONG).show(); //Output: Shows the URL from article -> "link" have a value
//Fragment
Fragment fragment = null;
fragment = new Menu1_1_Artikel();
if (fragment != null) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
}
});
return view;
}
public String getLink(){
return this.link; //Problem: String "link" = null
}
public void setLink(String Str){
this.link= Str;
//Toast.makeText(getActivity(), link, Toast.LENGTH_LONG).show(); //Toast would show an Error: "Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference"
}
//[......]
}
public class Menu1_1_Artikel extends Fragment {
private String link;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_webview, container, false);
link= "Test";
Toast.makeText(getActivity(), "1.: "+link, Toast.LENGTH_LONG).show(); //Output: "Test"
Menu1 obj = new Menu1();
link= obj.getLink();
Toast.makeText(getActivity(), "2.: "+link, Toast.LENGTH_LONG).show(); //Output: "null"
return view;
}
//[......]
}
First you have to make the "Menu1" class to implement parcelable or serialisable,
Then, set the arguments to fragments,
Bundle bundle = new Bundle();
bundle.putParcelable("obj", obj);
Fragment fragment = null;
fragment = new Menu1_1_Artikel();
fragment.setArguments(bundle);
Then, retrieve it in another fragment like this as follows,
Menu1 latitude = getArguments().getParcelable("obj")
You should use bundle and extras:
Fragment fragment = null;
fragment = new Menu1_1_Artikel();
if (fragment != null) {
Bundle args = new Bundle();
args.putString("link", link);
fragment.setArguments(args);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
And receive the link ok Menu1_1_Artikel
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_webview, container, false);
Bundle bundle=getArguments();
link = bundle.getString("link");
Toast.makeText(getActivity(), "2.: "+link, Toast.LENGTH_LONG).show(); //Output: "null"
return view;
}

Passing data from listview in fragment to fragment

when i click on the listview the bundle can get the value, but cant pass the value to second fragment.
First Fragment
categorylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String category = ((TextView) view.findViewById(R.id.mainproductitem)).getText().toString();
details_fragment ldf = new details_fragment ();
Bundle args = new Bundle();
args.putString("category", category);
ldf.setArguments(args);
}
});
return view;
}
Second Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.my_fragment2, container, false);
test = (TextView)view.findViewById(R.id.textView);
Bundle args = getArguments();
if (args != null && args.containsKey("category")){
String userId = args.getString("category");
test.setText(userId);
}
return view;
}
You may be forget to start your second fragment
categorylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String category = ((TextView) view.findViewById(R.id.mainproductitem)).getText().toString();
details_fragment ldf = new details_fragment ();
Bundle args = new Bundle();
args.putString("category", category);
ldf.setArguments(args);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.yourContainer, ldf);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
and in you second activity
Bundle agrs = getArguments();
if (args != null) {
String category = agrs.getString("category");
test.setText(category);
}
In First Fragment
categorylist.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String category = ((TextView) view.findViewById(R.id.mainproductitem)).getText().toString();
MainActivity main=new MainActivity();
main.openSecondFrag();
}
});
return view;
}
In your MainActivity,put openSecondFrag() method
public void openSecondFrag(){
details_fragment ldf = new details_fragment ();
Bundle args = new Bundle();
args.putString("category", category);
ldf.setArguments(args);
}
In Second Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.my_fragment2, container, false);
test = (TextView)view.findViewById(R.id.textView);
Bundle args = getArguments();
if (args != null && args.containsKey("category")){
String userId = args.getString("category");
test.setText(userId);
}
return view;
}
I am sure it will work.
HomeActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.activity.HomeActivity"
tools:showIn="#layout/app_bar_home">
//View that will hold all the fragments
<FrameLayout
android:id="#+id/container_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
FirstFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment1, container, false);
view.setBackgroundColor(Color.WHITE);
listViewAdapter.SetOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
SecondFragment secondFrag = new SecondFragment();
Bundle args = new Bundle();
args.putString("Key","some value");
secondFrag .setArguments(args);
getFragmentManager()
.beginTransaction()
.replace(R.id.container_view, fragment)
.addToBackStack(null)
.commit();
}
});
return view;
}
SecondFragment
public class SecondFragment extends Fragment {
public SecondFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.second_fragment, container, false);
TextView textView = (TextView)view.findViewById(R.id.textView);
view.setBackgroundColor(Color.WHITE);
String key = getArguments().getString("Key");
//Set the value to your text view
textView.setText(key);
return view;
}
I tried this out and it works perfectly.
Try this: on your receiving Fragment:
Bundle agrs = this.getArguments();
if (args != null) {
String myStr = args.getString(key, defaultValue);
}
`Use this code in your categorylist.setOnItemClickListener`
// Create fragment and give it an argument specifying the article it should show
details_fragment newFragment = new details_fragment ();
Bundle args = new Bundle();
args.putString("category", category)
//Note: if your are in fragment than replace getSupportFragmentManager to getFragmentManager.
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
Use a Bundle. Here's an example:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString(key, value);
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.container_view, bundle).commit();
Bundle has put methods for lots of data types. See this
Then in your Fragment, retrieve the data (e.g. in onCreate() method) with:
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getString(key, defaultValue);
}

retrieve data from fragment

I want to retrieve String data from my fragment that sent from activity and I'm using this code to send :
Bundle bundle = new Bundle();
bundle.putString("name",texts.get(position));
CatSelected catSelected = new CatSelected();
catSelected.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.container, catSelected, "CatSelected").commit();
And this code to receive :
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.search_frag, container, false);
txt = (TextView) view.findViewById(R.id.textView);
txt.setText(getArguments().getString("name"));
return view;
}
But textview is showing the default text and does not change. What's the problem?
A common practice seen while using fragments is, not to directly instantiate the fragment. Instead, you a get a fragment object by doing something like below.
MyFragment = MyFragment.newInstance(int arg1, String args2); // pass your args here
getSupportFragmentManager().beginTransaction().replace(R.id.flContent, fragment).commit();
Now, the MyFragment is composed of
public static MyFragment newInstance(int arg1, String arg2) {
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("arg1Key", arg1);
args.putInt("arg1Key", arg2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
myArg1 = getArguments().getInt("arg1Key");
myArg2 = getArguments().getInt("arg2Key");
}
}
In your second fragment or in your fragment that you want to retrive the passed value first must create a bundle.Try this.
Bundle bundle = getArguments();
txt.setText = bundle.getString("name");

Categories

Resources