Calling findViewById in fragment returns null - java

I'm trying to change TextView in my fragment layout, however I'm getting null value when calling findViewById no matter what.
Here's my fragment layout:
<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.kubacm.myweather.ShowMeWeather">
<TextView
android:id="#+id/city_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#android:color/white" />
</RelativeLayout>
Calling fragment from main activity:
#Override public void showWeather(JSONObject data){
Bundle bundle = new Bundle();
bundle.putString("data",data.toString());
ShowMeWeather wf = new ShowMeWeather();
wf.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.activity_main,wf).addToBackStack(null).commit();
}
and in fragment:
public class ShowMeWeather extends Fragment {
Typeface weatherFont;
TextView cityField;
public ShowMeWeather() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_show_me_weather, container, false);
cityField = (TextView)rootView.findViewById(R.id.city_field);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
weatherFont = Typeface.createFromAsset(getActivity().getAssets(),"fonts/weather.ttf");
renderWeather();
}
public void renderWeather(){
try{
cityField.setText("Here should go my text");
}catch (Exception e){
Log.e("Simple Weather","there was an errror");
}
}
}
I have tried cleaning and rebuilding my project in Android Studio and still keep getting NullPointerException when I try cityField.SetText

onCreateView method is called after onCreate method, so cityField is not yet initialized

Check fragment lifecycle here here
Call your renderWeather method after onCreateView is completed

Related

Android videoView not showing inside fragment

Hey all I am having a little bit of an issue with trying to call a fragment that has the videoview within it into my current fragment page.
When I click on the test button I set up it goes through the code without error but never shows the video fragment - I even gave it a background color of red so I could see it load into my current view.
My goal here is just to send a parameter of the video path to the video fragment videoview player and start playing it.
videoPlay.java
public class videoPlay extends Fragment {
public videoPlay(){
//constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout._fragvideoplay, container, false);
MediaController mc= new MediaController(getActivity());
VideoView view = (VideoView)rootView.findViewById(R.id.videoView);
String path = Environment.getExternalStorageDirectory().getAbsolutePath().toString() + "/sddir/Bubble Guppies.mp4";
view.setVideoURI(Uri.parse(path));
view.setMediaController(mc);
view.start();
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
}
}
_fragvideoplayer.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary">
<VideoView
android:id="#+id/videoView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
FragMovies.java:
public class FragMovies extends Fragment {
public FragMovies(){
//constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout._fragmovies, container, false);
WebView view = (WebView) rootView.findViewById(R.id.webView);
view.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
container.findViewById(R.id.webView).setVisibility(View.GONE);
container.findViewById(R.id.pBar1).setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
container.findViewById(R.id.pBar1).setVisibility(View.GONE);
container.findViewById(R.id.webView).setVisibility(View.VISIBLE);
}
});
view.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setAllowContentAccess(true);
view.getSettings().setAllowFileAccess(true);
view.getSettings().setLoadsImagesAutomatically(true);
view.getSettings().setAllowFileAccess(true);
view.getSettings().setBuiltInZoomControls(false);
view.getSettings().setDomStorageEnabled(true);
view.getSettings().setAppCacheEnabled(true);
view.getSettings().setDisplayZoomControls(false);
view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
view.getSettings().setSupportZoom(false);
view.setHorizontalScrollBarEnabled(false);
view.setVerticalScrollBarEnabled(false);
view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
view.loadUrl("https://www.bing.com/");
return rootView ;
}
}
_fragmovies.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mainLayout">
<ProgressBar
android:id="#+id/pBar1"
android:layout_width="93dp"
android:layout_height="match_parent"
android:layout_alignParentTop="false"
android:layout_centerHorizontal="true"
android:layout_marginStart="950px"
android:layout_marginLeft="950px" />
<WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/webView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
</LinearLayout>
Main_activity.java:
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
PagerAdapter pagerAdapter;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getViews();
//adapter setup
pagerAdapter = new com.example.telluridetainment.PagerAdapter(getSupportFragmentManager());
//attaching fragments to adapter
pagerAdapter.addFragment(new FragMovies(),"Movies");
viewPager.setOffscreenPageLimit(1);
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);
//setting icons
tabLayout.getTabAt(0).setIcon(R.drawable.ic_movie_white_24dp);
button = (Button) findViewById(R.id.button0);
button.setOnClickListener(new MyClass());
}
public class MyClass implements View.OnClickListener {
#Override
public void onClick(View v) {
videoPlay myfragment = new videoPlay();
//pass data
Bundle bundle = new Bundle();
bundle.putString("KEY","DATA");
myfragment.setArguments(bundle);
FragmentTransaction fragmentManager = getSupportFragmentManager().beginTransaction();
fragmentManager.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentManager.addToBackStack(null);
fragmentManager.replace(R.id.viewPager, myfragment).commit();
}
}
private void getViews() {
tabLayout = findViewById(R.id.mTabLayout);
viewPager = findViewById(R.id.viewPager);
}
}
activity_main.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="2000px"
android:layout_height="1200px"
tools:context=".MainActivity">
<Button
android:id="#+id/button0"
android:layout_width="200dp"
android:layout_height="152dp"
android:text="Button"
android:textColor="#B71C1C" />
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/appbarLayout"
tools:ignore="SpeakableTextPresentCheck">
</android.support.v4.view.ViewPager>
</RelativeLayout>
The path to the movie is correct. And the movie is there in the "external" SD card path. Clicking around on the new fragment (videoPlay) yields no video menu (play, remind, pause...) so its not there.
Any help would be great!

Control layout object in fragment - getting null object reference

I made a fragment_console.xml and ConsoleFragment.java
In MainActivity.java I create object console_fragment = new ConsoleFragment();
Then OnClickListener runs console_fragment.method();
But it gives error Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
on line
sendButton = v.findViewById(R.id.fragment_console_send_button);
ConsoleFragment.java
public class ConsoleFragment extends Fragment {
View v;
private boolean isVisible;
private Button sendButton;
private TextView consoleText;
private EditText commandText;
public ConsoleFragment() {
// 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
v = inflater.inflate(R.layout.fragment_console, container, false);
showConsole(v);
return v;
}
public void showConsole(View v){
sendButton = (Button) v.findViewById(R.id.fragment_console_send_button);
consoleText = (TextView) v.findViewById(R.id.fragment_console_log_text);
commandText = (EditText) v.findViewById(R.id.fragment_console_command_text);
isVisible = true;
sendButton.setVisibility(View.GONE);
consoleText.setVisibility(View.GONE);
commandText.setVisibility(View.GONE);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ConsoleFragment console_fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
console_fragment = new ConsoleFragment();
}
public void triggerConsole(View view) { //buton on click
console_fragment.showConsole(view);
}
}
fragment_console.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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="wrap_content"
tools:context=".activities.ConsoleFragment">
<TextView
android:id="#+id/fragment_console_log_text"
android:layout_width="match_parent"
android:layout_height="150dp"
android:text="TextView"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent">
<EditText
android:id="#+id/fragment_console_command_text"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="0.75"
android:layout_marginBottom="2dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="#string/console_command"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/fragment_console_send_button"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="0.25"
android:text="#string/console_send_button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
tools:context=".activities.MainActivity">
<include
android:id="#+id/include"
layout="#layout/activity_top_bar"
android:layout_width="match_parent"
android:layout_height="150dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fragment"
android:name="com.wordfall.wordfallcontroll.activities.ConsoleFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="#+id/include2"
app:layout_constraintStart_toStartOf="parent" />
</FrameLayout>
<include
android:id="#+id/include2"
layout="#layout/activity_bottom_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
How to get layout object (buttons, tv etc) to get control on it in fragment class?
public class XFragment extends Fragment {
View v;
private boolean isVisible;
private Button sendButton;
private TextView consoleText;
private EditText commandText;
public XFragment() {
// 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
v = inflater.inflate(R.layout.fragment_x, container, false);
showConsole(v);
return v;
}
public void showConsole(View v){
sendButton = v.findViewById(R.id.fragment_console_send_button);
consoleText = v.findViewById(R.id.fragment_console_log_text);
commandText = v.findViewById(R.id.fragment_console_command_text);
isVisible = true;
sendButton.setVisibility(View.GONE);
consoleText.setVisibility(View.GONE);
commandText.setVisibility(View.GONE);
}
}
In your activity_main.xml file you need to create a container for holding fragments like:
activity_main.xml
<LinearLayout
......
......
....
>
.........
........
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
In your MainActivity.java file inside onCreate method you can do:
MainActivity.java
#Override
protected void onCreate(...){
.....
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction().replace(R.id.container, new ConsoleFragment(), "ConsoleFragment").addToBackStack(null).commit();
}
What view you pass into triggerConsole method from outside fragment? The problem may be in this, you'll try to find controls in layout, which is not part of your fragment. View of your fragment is assigned to global variable v, but now you try to get it from method parameter named v. Try this code.
public void showConsole(){
sendButton = (Button) v.findViewById(R.id.fragment_console_send_button);
consoleText = (TextView) v.findViewById(R.id.fragment_console_log_text);
commandText = (EditText) v.findViewById(R.id.fragment_console_command_text);
isVisible = true;
sendButton.setVisibility(View.GONE);
consoleText.setVisibility(View.GONE);
commandText.setVisibility(View.GONE);
}
If you want pass different layouts into same fragment, do it via constructor, not via method parameter, and each time make new instance of fragment.

fragment doesn't show in framelayout in linearlayout

I use fragments to display multiple views in one activity. I have 2 framelayouts in one linearlayout. The onCreate and onCreateView of the fragment gets called but the view of the fragment is not displayed. Is what i'm trying to do not possible? Or is there a way to fix issue?
Layout of the activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".view.activity.StandardFlowActivity">
<FrameLayout
android:id="#+id/standardFlowDownloadContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<FrameLayout
android:id="#+id/standardFlowBaseContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
Layout of the fragment
<FrameLayout 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"
tools:context="com.example.sennevervaecke.crossexperience.view.fragment.WedstrijdFragment">
<ListView
android:id="#+id/wedstrijdListView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Fragment Class
public class WedstrijdFragment extends Fragment implements AdapterView.OnItemClickListener{
private ArrayList<Wedstrijd> wedstrijden;
private WedstrijdFragmentCom communication;
public WedstrijdFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.e("wedstrijdFragment", "onCreate is called");
super.onCreate(savedInstanceState);
wedstrijden = LocalDB.getWedstrijden();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.e("wedstrijdFragment", "onCreateView is called");
View view = inflater.inflate(R.layout.fragment_wedstrijd, container, false);
ListView listView = view.findViewById(R.id.wedstrijdListView);
WedstrijdAdapter adapter = new WedstrijdAdapter(getContext(), wedstrijden);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
communication = (WedstrijdFragmentCom) activity;
} catch (ClassCastException e){
e.printStackTrace();
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
communication.onWedstrijdItemClick(wedstrijden.get(i));
}
}
Code in the onCreate of the activity to add the fragment:
wedstrijdFragment = new WedstrijdFragment();
getSupportFragmentManager().beginTransaction().add(R.id.standardFlowBaseContainer, wedstrijdFragment, "wedstrijd").commit();
Thanks in advance!
Your first layout standardFlowDownloadContainer width and height is match_parent , so the standardFlowBaseContainer FrameLayout is out of the screen. you can change your standardFlowDownloadContainer's height to 20dp and run your project , you will see your Fragment content.

NPE on fragment recreation. Button is null after orientation change in fragment

I have read all the other topics related to this issue and none seem to be helping me solve the problem.
I am doing some background task in an asynctask that needs to persist on orientation change (configChanges). I have gotten the data to persist I believe by using fragments and setRetainInstance(true), but my buttons (Im assuming any views really) are being set to null on recreation of the fragment on orientation change. This is causing a null pointer error when I try to operate on the buttons reference after orientation has change (fragment has been recreated).
I have tried wrapping the button and calls on the button in a statement to check if the bundle is null. This stops the crash but does not allow for the button to be used again on recreation of the fragment.
The following class extends Fragment.
#Override
public void onCreate(Bundle savedInstanceState) {
if (DEBUG) Log.d(TAG, "onCreate()");
super.onCreate(savedInstanceState);
setRetainInstance(true);
currentActivity = super.getActivity();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
if (DEBUG) Log.d(TAG, "onActivityCreated(Bundle)");
super.onActivityCreated(savedInstanceState);
simpleForecastIntent = new Intent(currentActivity, SimpleForecastActivity.class);
Button fetchDataButton = (Button) currentActivity.findViewById(R.id.fetchDataButton);
if (savedInstanceState == null) {
fetchDataButton.setOnClickListener(fetchDataButtonListener);
fetchDataButton.setTransformationMethod(null);
}
locationManager = (LocationManager)
currentActivity.getSystemService(Context.LOCATION_SERVICE);
if (isTaskRunning) {
progressDialog = ProgressDialog.show(currentActivity, "Fetching data", "Please wait...");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (DEBUG) Log.d(TAG, "onCreateView(LayoutInflater, ViewGroup, Bundle)");
return inflater.inflate(R.layout.main_menu, container, false);
}
main_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".activities.MainActivity">
<include layout="#layout/toolbar" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<Button
android:id="#+id/fetchDataButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/locationField"
android:text="#string/fetch_weather_data"
android:layout_centerHorizontal="true" />
<EditText
android:id="#+id/locationField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/enter_location"
android:layout_alignEnd="#+id/fetchDataButton"
android:layout_alignLeft="#+id/fetchDataButton"
android:layout_alignRight="#+id/fetchDataButton"
android:layout_alignStart="#+id/fetchDataButton"
android:inputType="textPostalAddress" />
<ListView
android:id="#+id/previousLocationsList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/fetchDataButton"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</LinearLayout>
I have spent far too many hours on something so trivial and really need a bump in the correct direction. How can I get the button to not be null on recreation of fragment?
EDIT SOLVED:
I was using the disposed of activity's context to find the view of the button. Instead of the new activities view context.
#Override
public void onCreate(Bundle savedInstanceState) {
if (DEBUG) Log.d(TAG, "onCreate()");
super.onCreate(savedInstanceState);
setRetainInstance(true);
currentActivity = super.getActivity();
}
The problem is that you are referencing your button in onActivityCreated instead of onCreateView. On orientation change, the view gets torn down and then recreated. You should override onCreateView and maintain the reference to your button from there.
UPDATE:
I see how your code is working, but in my opinion it's following a bad design pattern. You are still instantiating your view references inside of onActivityCreated, instead of immediately after they are inflated in onCreateView.
I would switch it to something like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (DEBUG) Log.d(TAG, "onCreateView(LayoutInflater, ViewGroup, Bundle)");
View root = inflater.inflate(R.layout.main_menu, container, false);
Button fetchDataButton = (Button) root.findViewById(R.id.fetchDataButton);
...
return root;
}

Android: Cant replace fragment inside activity with another fragment?

I'm new to android development and having some issues with replacing a fragment with another fragment.
In my MainFragment.java, the first thing I do in onCreate is check for internet connectivity, and if there is not, I replace that fragment with the InternetCheckFragment. However, in InternetCheckFragment.java, when I try to inflate my check_internet.xml, the app closes, but there is no error.
activity_main.xml:
<fragment 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/main_browse_fragment"
android:name="com.ui.MainFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ui.MainActivity"
tools:deviceIds="tv"
tools:ignore="MergeRootFrame" />
MainActivity.java:
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
MainFragment.java:
public class MainFragment extends VerticalGridFragment
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (isConnectedToInternet() == true)
{
// DO stuff
}
else
{
showInternetError();
}
}
public void showInternetError()
{
getFragmentManager().beginTransaction().replace(R.id.show_internet_error , new InternetCheckFragment())
.commit();
}
....
}
InternetCheckFragment.java:
public class InternetCheckFragment extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
// Defines the xml file for the fragment
return inflater.inflate(R.layout.check_internet, parent, false);
}
}
check_internet.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/show_internet_error"
android:background="#color/black_transparent">
<Button android:id="#+id/btn_retry"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="RETRY"
android:layout_centerInParent="true"/>
</RelativeLayout>
However, I'm getting the error No view found for id.
I'm sure I'm not setting something correctly? Can someone point me in the right direction?
Thanks!
You are inflating a Fragment in a Fragment using the Fragment's FragmentManager.
This FragmentManager cannot handle this.
Try using the SupportFragmentManager with AppCompatActivity.getSupportFragmentManager() and the support Fragments from android.support.v4.app.Fragment
Ugh!..it was a stupid mistake, I replaced R.id.show_internet_error within getFragmentManager().beginTransaction().replace(R.id.show_internet_error , new InternetCheckFragment()).commit(); with R.id.main_browse_fragment and now it works.

Categories

Resources