Change TextView inside Fragment gives me NullPointerException - java

I'm trying to change a Textview's text inside a fragment, but it gaves me a NullPointerException at the setName method.
I have already tried 2 ways to do this:
public class MemberFragment extends Fragment {
private TextView tvName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view;
view = inflater.inflate(R.layout.fragment_member,container, false);
tvName = (TextView) getView().findViewById(R.id.tvProfileName);
return view;
}
public void setName(String name) {
tvName.setText(name);
}
or:
public class MemberFragment extends Fragment {
private static TextView tvName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view;
view = inflater.inflate(R.layout.fragment_member,container, false);
return view;
}
public void setName(String name) {
tvName = (TextView) getView().findViewById(R.id.tvProfileName);
tvName.setText(name);
}
but none gave me success. Here is where I instantiate the fragment:
MemberFragment fragment = new MemberFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
fragment.setName(map.get(Tags.NAME));
and the fragment_member.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="#style/ActionBar.Transparent.MyStyle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="top" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="446dp" >
<TextView
android:id="#+id/tvProfileName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
</ScrollView>
Can someone help me?
Thanks.

view in your onCreateView method is the rootView of your fragment.
So just add the following code in your onCreateView method to change the text of your TextView:
((TextView)view.findViewById(R.id.tvProfileName)).setText("Your new text");

try this:
tvName = (TextView) view.findViewById(R.id.tvProfileName);
instead of :
tvName = (TextView) getView().findViewById(R.id.tvProfileName);

Related

TextView in Fragment Returning Null in Android Studio

i am new to Android Studio.. i am facing null pointer exception error on my TextView inside a Fragment, please help..here is my code. this is nothing but a simple interface between two fragments. i am getting Null pointer exception error when i click on an item in ListView Fragment. for sure the TextView in DetailsFragment didn't assign or point to the source of whatever it is. please help on solving this.
public class MainActivity extends AppCompatActivity implements list_Fragment.ItemSelected {
ArrayList<String> Descriptions = new ArrayList<String>();;
TextView tvDescription;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Descriptions.add("Description for Item 1");
Descriptions.add("Description for Item 2");
Descriptions.add("Description for Item 3");
Descriptions.add("Description for Item 4");
tvDescription = findViewById(R.id.tvDescription);
}
#Override
public void onItemSelected(int index) {
tvDescription.setText(Descriptions.get(index));
}}
list_fragment
public class list_Fragment extends ListFragment {
ArrayList<String> Data = new ArrayList<String>();
ItemSelected activity;
public interface ItemSelected{
void onItemSelected(int index);
}
public list_Fragment() {
// Required empty public constructor
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
activity=(ItemSelected) context;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Data.add("Item 1");
Data.add("Item 2");
Data.add("Item 3");
Data.add("Item 4");
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, Data));
}
#Override
public void onListItemClick(#NonNull ListView l, #NonNull View v, int position, long id) {
activity.onItemSelected(position);
}
}
and the details Fragment code, where i am getting the error i believe, is
public class DetailsFragment extends Fragment {
public DetailsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return (LinearLayout) inflater.inflate(R.layout.fragment_details, container, false);
}
}
Main XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="#+id/ll_Horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/listfragmentView"
android:name="com.example.fragmentcheck.list_Fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3"
android:background="#android:color/holo_blue_dark"
tools:layout="#layout/fragment_list_" />
<androidx.fragment.app.FragmentContainerView
android:id="#+id/detailsfragmentView"
android:name="com.example.fragmentcheck.DetailsFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#color/purple_200"
tools:layout="#layout/fragment_details" />
</LinearLayout>
ListFragment XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/design_default_color_primary_variant"
android:orientation="vertical"
tools:context=".list_Fragment">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
DetailsFragment XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/design_default_color_on_secondary"
android:orientation="vertical"
tools:context=".DetailsFragment">
<TextView
android:id="#+id/tvDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/textview"
android:textColor="#FFFFFF"
android:textSize="20sp" />
</LinearLayout>
Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fragmentcheck, PID: 28112
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object r*emphasized text*eference
at com.example.fragmentcheck.MainActivity.onItemSelected(MainActivity.java:34)
at com.example.fragmentcheck.list_Fragment.onListItemClick(list_Fragment.java:54)
tvDescription is in the DetailsFragment layout, you need to do any layout configuration in the code for that Class
i.e.
class DetailsFragment extends Fragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_details, container, false)
tvDescription = view.findViewById(R.id.tvDescription);
tvDescription.setText("some text");
return view
}
}
You have tvDescription in DetailsFragment xml, while you are finding it's id in MainAcitvity. MainActivity just have FragmentContainerView , it doen't have any text view inside it.
You need to inflate the Fragment's view and call findViewById() on the View it returns.
Updated DetailsFragment
public class DetailsFragment extends Fragment {
TextView tvDescription;
public DetailsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_details, container, false)
tvDescription = view.findViewById(R.id.tvDescription);
tvDescription.setText("some text");
return view
}
}
Change both: androidx.fragment.app.FragmentContainerView
To: fragment
In the main_activity xml

android.support.v4.widget.NestedScrollView cannot be cast to android.support.v7.widget.RecyclerView

Good afternoon,
I am trying to create a fragment with a RecyclerView including items.
Above those items, I need to put a header with some filters.
Here is the fragment's xml (fragment_products_list) :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="12sp"
android:id="#+id/filters_frame">
<include layout="#layout/expandable_filters"/>
</RelativeLayout>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
Here is the OnCreateView in my Fragment java file (ListFragment.java) :
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RecyclerView rv = (RecyclerView) inflater.inflate(
R.layout.fragment_products_list, container, false);
//Product filters
expandFiltersButton = (ImageButton) getView().findViewById(R.id.expand_filters);
expandableZone = (LinearLayout) getView().findViewById(R.id.expandable_zone);
expandFiltersButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(expandableZone.isShown()){
expandableZone.setVisibility(View.GONE);
expandFiltersButton.setImageResource(R.drawable.ic_more_24dp);
}else{
expandableZone.setVisibility(View.VISIBLE);
expandFiltersButton.setImageResource(R.drawable.ic_less_24dp);
}
}
});
setupRecyclerView(rv);
mRecyclerView = rv;
loadUpdates();
return rv;
}
I have this error code when I am trying to run the app :
android.support.v4.widget.NestedScrollView cannot be cast to android.support.v7.widget.RecyclerView
What is the problem and how can I solve it?
Thanks for your help!
Try this:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(
R.layout.fragment_products_list, container, false);
//Product filters
RecyclerView rv = (RecyclerView) view.findViewById(R.id.recyclerview);
expandFiltersButton = (ImageButton) view.findViewById(R.id.expand_filters);
expandableZone = (LinearLayout) view.findViewById(R.id.expandable_zone);
expandFiltersButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(expandableZone.isShown()){
expandableZone.setVisibility(View.GONE);
expandFiltersButton.setImageResource(R.drawable.ic_more_24dp);
}else{
expandableZone.setVisibility(View.VISIBLE);
expandFiltersButton.setImageResource(R.drawable.ic_less_24dp);
}
}
});
setupRecyclerView(rv);
mRecyclerView = rv;
loadUpdates();
return view;
}

How do I dynamically make this child Fragment's TextView visible/invisible?

I have a main Activity containing a parent Fragment, which in turn contains a child Fragment. I am trying to make a TextView in the child Fragment visible/invisible dynamically.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This text belongs to the Activity"
android:id="#+id/textView"/>
<FrameLayout
android:id="#+id/parent_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
fragment_parent.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This text belongs to the parent fragment"
android:id="#+id/textView"/>
<FrameLayout
android:id="#+id/child_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
fragment_child.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This text belongs to the child fragment"
android:id="#+id/textView"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="But make this text visible dynamically!"
android:id="#+id/make_this_text_visible"
android:visibility="invisible"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final String PARENT_TAG = "parent_tag";
private ParentFragment mParentFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
mParentFragment = ParentFragment.newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.parent_container, mParentFragment, PARENT_TAG).commit();
}
else {
mParentFragment = (ParentFragment) getSupportFragmentManager().findFragmentByTag(PARENT_TAG);
}
}
}
ParentFragment.java
public class ParentFragment extends Fragment {
public static final String CHILD_TAG = "child_tag";
private ChildFragment mChildFragment;
private List<Integer> mList;
public static ParentFragment newInstance() {
Bundle args = new Bundle();
ParentFragment fragment = new ParentFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_parent, container, false);
mList = new ArrayList<Integer>();
if (savedInstanceState == null) {
mChildFragment = ChildFragment.newInstance();
getChildFragmentManager().beginTransaction().replace(R.id.child_container, mChildFragment, CHILD_TAG).commit();
}
else {
mChildFragment = (ChildFragment) getChildFragmentManager().findFragmentByTag(CHILD_TAG);
}
getChildFragmentManager().executePendingTransactions(); //doesn't seem to do anything!
doStuff();
return view;
}
void doStuff() {
mList.add(4); //pretend this is actually querying a database.
//for simplicity it just receives a single 4.
if (mList.size() > 0) { //the list is not empty, display the text!
mChildFragment.setTextVisible(); //error! the textivew of the child fragment is null right now
}
else {
mChildFragment.setTextInvisible(); //error! the textivew of the child fragment is null right now
}
}
}
ChildFragment.java
public class ChildFragment extends Fragment {
private TextView mTextView;
public static ChildFragment newInstance() {
Bundle args = new Bundle();
ChildFragment fragment = new ChildFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
mTextView = (TextView) view.findViewById(R.id.make_this_text_visible);
return view;
}
public void setTextVisible() {
mTextView.setVisibility(View.VISIBLE);
}
public void setTextInvisible() {
mTextView.setVisibility(View.INVISIBLE);
}
}
How can I ensure that the child fragment is formed by the time I call doStuff() in the ParentFragment?
What I would do is keep the state of the text view visibility so it can be updated properly once the view has been created if it hasn't been already. Instead of separate methods for setTextVisible() and setTextInvisible have a single method setTextVisibile(boolean isVisible) and implement it as follows:
public class ChildFragment extends Fragment {
private TextView mTextView;
private boolean mIsTextVisible;
public static ChildFragment newInstance() {
Bundle args = new Bundle();
ChildFragment fragment = new ChildFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
mTextView = (TextView) view.findViewById(R.id.make_this_text_visible);
setTextVisible(mIsTextVisible);
return view;
}
public void setTextVisible(boolean isVisible) {
mIsTextVisible = isVisible;
if(mTextView != null) {
mTextView.setVisibility(isVisible ? View.VISIBLE : View.GONE);
}
}
}
and then in the parent fragment you can call doStuff() without worrying about the current state of the views in the ChildFragment since mIsTextVisible is properly set. If the mTextView is null at the time setTextVisible() is called the visibility will still be properly set in onCreateView().
Just take care to save and restore the mIsTextVisible flag when the fragment is recreated such as when the device is rotated.
Alternative Answer Using A Callback
Using callbacks update the ParentFragment to implement
ChildFragment.OnViewCreatedListener and its method.
public class ParentFragment extends Fragment
implements ChildFragment.OnViewCreatedListener {
#Override
public void onViewCreated() {
doStuff();
}
}
And then in ChildFragment
public class ChildFragment extends Fragment {
public interface OnViewCreatedListener {
void onViewCreated();
}
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
mTextView = (TextView) view.findViewById(R.id.make_this_text_visible);
if(getParentFragment() instanceof OnViewCreatedListener) {
((OnViewCreatedListener) getParentFragment()).onViewCreated();
} else if (getActivity() instanceof OnViewCreatedListener) {
((OnViewCreatedListener) getActivity()).onViewCreated();
}
return view;
}
}

Imagebutton inside a fragment clicked to open a new fragment

I am creating an application which consists of a viewpager with different fragments.And these fragments contains different imagebuttons.I want to open fragments when each of these image button is clicked.But i don't know how to do it.I am new to fragments and i don't know much about them.I am trying to make this code since 2 days.Please if you can help me out.So i will be able to complete my project app.
My layout for NoticeBoard.java is as below: This contains2 imagebuttons and a listview.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns : android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:id="#+id/relative">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:background="#AAAAAA"
android:id="#+id/line">
<ImageButton
android:id="#+id/ptu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:background="#CCCCCC"
android:clickable="true"
android:onClick="OnClick"
android:contentDescription="#string/mko"
android:paddingBottom="10dp"
android:paddingLeft="9.9dp"
android:paddingRight="20dp"
android:paddingTop="10dp"
android:src="#drawable/img" />
<ImageButton
android:id="#+id/ku"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:background="#CCCCCC"
android:clickable="true"
android:contentDescription="#string/mn"
android:paddingBottom="10dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="10dp"
android:src="#drawable/image" />
</LinearLayout>
<ListView
android:id="#+id/nb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/line"
android:layout_alignParentTop="true"
>
</ListView>
</RelativeLayout>
And my layout for the ptu,cu,ku,htu is same as above but with different adapter set on the above same listview.I have defined different adapters for ptu,hptu,cu and ku in their .java classes
My NoticeBoard.java class is a fragment with the noticeboard layout set as view and a listview.
public class Notice_Board extends Fragment {
ListView l;
ImageButton i1,i2,i3,i4;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_noticeboard, container, false);
l = (ListView) rootView.findViewById(R.id.nb);
String[] title = new String[]{"Important Announcements", "Datesheet", "Results","Placement Drives","Admissions","Entrance exams"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, title);
l.setAdapter(adapter);
i1 = (ImageButton ) rootView
.findViewById(R.id.ptu);
i2 = (ImageButton ) rootView
.findViewById(R.id.cu);
i3 = (ImageButton ) rootView
.findViewById(R.id.ku);
i4 = (ImageButton ) rootView
.findViewById(R.id.hptu);
i1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.layout.activity_noticeboard,new PTU(),"PTU");
}
return rootView;
}
}
Below is my ptu.java class that contains the same view and the listview same as noticeboard but setting different values to listview by setting adapter with different values on it.
public class PTU extends Fragment{
ListView l;
ImageButton i2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_noticeboard, container, false);
String[] array = new String[] {"Important Announcements", "Results",Programme","Syllabus","Fees","Events","Placement Drives"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, array);
l = (ListView) rootView.findViewById(R.id.nb);
l.setAdapter(adapter);
return rootView;
}
}
I want that each time a button is clicked the layout for notice board should appear but with different listview.And i also want when the noticeboard layout opens the ptu imagebutton should appear clicked having the listview in its fragment.
Below is my ku.java class that contains the same view and the listview that is for ptu but setting different values to listview by setting adapter with different values on it.
public class KU extends Fragment{
ListView l;
ImageButton i2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_noticeboard, container, false);
String[] array = new String[] {"Important Announcements", "Results",Programme","Syllabus","Fees","Events","Placement Drives"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, array);
l = (ListView) rootView.findViewById(R.id.nb);
l.setAdapter(adapter);
return rootView;
}
}
I think issue is in your initialisation of fragment manager.
FragmentManager fm = getFragmentManager();
Instead of it, use
FragmentManager fragmentManager = ((MainActivity)getActivity()).getSupportFragmentManager();
Here MainActivity is your fragment activity from which you are calling your all fragments.
You have a Main fragment manager Activity name fragment activity. this is the main fragment activity manager. you have to set all fragment using by this activity.
i1 = (ImageButton ) rootView
.findViewById(R.id.ptu);
i2 = (ImageButton ) rootView
.findViewById(R.id.cu);
i3 = (ImageButton ) rootView
.findViewById(R.id.ku);
i4 = (ImageButton ) rootView
.findViewById(R.id.hptu);
i1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
fragmentActiivty.setFragment();
}
Notes: :SetFragment function is made in fragment-activity class
public static void set_view_FAQ() {
FragmentManager fm = act.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment fragment = new yourFragnmentName();
ft.add(R.id.activity_main_content_fragment, fragment);
ft.commit();
}
Note: new yourFragmentNAme means yous fragment class likes Ku,ptu,etc

NullPointer Exception when assigning value to TextView

I just wanted to passing value from one activity to another but not able to find Textview value from the view.. I just passing one message from main activity to this activity through a text box and I'm seeing textbox value here but not able to assign that to textView...
here is my code..
public class DisplayMessageActivity extends Activity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
textView = (TextView) findViewById(R.id.displayText);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
textView.setText(message);
}
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.activityapps.DisplayMessageActivity$PlaceholderFragment" >
<TextView
android:id="#+id/displayText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView" />
Please help me out..
The TextView does not belong to the Activity layout. Move the initialization of TextView to onCreateView of PlaceholderFragment.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_display_message, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.displayText);
return rootView;
}
In Activity
if (savedInstanceState == null) {
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
Bundle bundle = new Bundle();
bundle.putString("key", message);
PlaceholderFragment fragobj = new PlaceholderFragment();
fragobj.setArguments(bundle);
getFragmentManager().beginTransaction()
.add(R.id.container, fragobj).commit();
}
Then
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_display_message, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.displayText);
String strtext = getArguments().getString("key");
textView.setText(strtext);
return rootView;
}
View view = inflater.inflate(R.layout.fragment_display_message, container, false);
TextView textView = (TextView) view.findViewById(R.id.displayText);
return view; //in onCreate method
you have extended from activity you can use also this
TextView textView = (TextView) findViewById(R.id.displayText);
//in onCreate method

Categories