• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Can't access fragment's elemenst

przemekh10

Lurker
Sep 27, 2015
1
0
I want to use SlidingTabLayout. I was following this tutorial: http://www.android4d...iding-tabs.html. Screen is presenting MainActivity with two tabs (that is Tab1.xml and Tab2.xml). Classes Tab1 and Tab2 extends Fragment.

I want to change text ("You Are in Tab 1") which is part of Tab1. I can do it using onCreateView() function. As I understand this function is called only once, so I can change the text only at the beginning. I want to change it later, e.g. function in MainActivity should change it. To achieve it I created static variable textView which references to the text in the Tab1.

Java:
public class Tab1 extends Fragment {

public static TextView textView;

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tab_1,container,false);
    textView = (TextView) view.findViewById(R.id.textView);
    textView.setText("It works so the textView cannot be null");
    return view;
}

Problem occurs when I want access the Tab1.textView like in example below:

Java:
public class MainActivity extends AppCompatActivity {

Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Home","Events"};
int Numboftabs =2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    InitializeToolbarAndTabs();
    Tab1.textView.setText("This doesn't work, null exception");
}

In this moment I receive null exception:
java.lang.NullPointerException:Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a nullobject reference

I was trying several methods, I always receive NullPointerException. I cannot find also fragment using findFragmentByTag() neither findFragmentById() function - allways null.

Even List<android.support.v4.app.Fragment> allFragments = getSupportFragmentManager().getFragments(); returns empty list allFragments.

I have no idea how to solve this problem. If someone want to help me and try the code, I created new project based on the android4dev's tutorial mentioned above: http://www13.zippyshare.com/v/7ObQHYzW/file.html

VirusTotal scan: https://www.virustotal.com/pl/file/...7d9ada6b897e4b643ff1f335/analysis/1443358094/
 

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones