Difference between fragment_main.xml and activity_main.xml - java

I'm following along with the tutorial here
https://developer.android.com/training/basics/firstapp/building-ui.html
and I'm confused as to why they say to edit fragment_main.xml instead of activity_main.xml. In the MainActivy.java file, the onCreate() method has a line that says
setContentView(R.layout.activity_main);
Why does it complain when I try to change it to
setContentView(R.layout.fragment_main);
Any pointers would be appreciated.

The activity is a container of fragments, a fragment is like an UI layer which can be added, modified or deleted in execution time. also in the activity layout you can have added "static" fragments.
There can be a lot of causes for your error if you swap the layouts, maybe your activity code tries to reference some views that are not in the fragment layout or viceversa, maybe the activity layout has references to fragments, etc... You can name your layouts as you want, but you need to set the layout that matches with your code in your activities/fragments

you have to use
setContentView(R.layout.activity_main);
in your program where as setContentView(R.layout.fragment_main); is used when you use Different Fragments in One Activity
and you getting error because there is no xml file present named fragment_main.xml in res folder.

its just name fragment_main or activity_main if you wish you can give your GF :D name also,
i.e when you add a layout file to res/layout path an entry will be maid in R.java
say you create main.xml in res/layout, and when you clean your project an entry R.layout.main
will be added to R.java its just the name whatever you give to file.
may be you getting error because that file not there or might be that file don't hold layout in it.

Both are optional. But, It's always better using one layout to avoid confusion into your code. Which in this case I will suggest using activity_main.xml and delete the fragment_activity.xml following the below procedure:
1.Creat project normally.
2.Copy fragment_main.xml to activity_main.xml (content). Then delete fragment_main.xml
3.In MainActivity.java delete the following content :
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
and
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
Hope this help

Related

Error inflating class fragment. What can I do here?

I was coding this program the other day, hoping that the fragment was doing okay, but it isn't. My project is a Relative Layout app where the GPS map will show up on the screen first thing the activity pops up, and then the choices to view some of the Javanese culture of Indonesia (in the form of Grid - Card View combination), will be available for selection.
Here, in this line, I have a class fragment inflation error, according to Logcat :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_java_island); // Erroring line
KerisCard = (CardView) findViewById(R.id.KerisCard);
TradClothesCard = (CardView) findViewById(R.id.TradClothesCard);
TradHouseCard = (CardView) findViewById(R.id.TradHouseCard);
TariMerakCard = (CardView) findViewById(R.id.TariMerakCard);
SupportMapFragment javaMapFragment = (SupportMapFragment) getSupportFragmentManager().
findFragmentById(R.id.java_island_map);
javaMapFragment.getMapAsync(this); . . . }
In retrospect, I'm not very familiar to the concept of fragments as the classes I've been attending aren't going too detailed on the usage of fragments. Also, I have to note without the declaring the object references ((CardView) declarations on the onCreate() function), this error would not show up, and the app will be executable as normal.
Instead of making support fragment reference create fragment reference directly and call method from fragment.
SampleFragment fragment=new SampleFragment()
Fragment .someMethod
Here is a confusion
Do you want to open fragment in activity ?
Because you are trying to find fragment from id ,so have you created in xml if not then there is problem.

My custom SurfaceView is null after findViewById() [duplicate]

First of all: yes, I read all the other threads on this topic. And not only those from this site... (you see, I'm a little frustrated)
Most of them come with the advice to use android:id instead of just id in the XML file. I did.
From others, I learned, that View.findViewById works different than Activity.findViewById. I handled that, too.
In my location_layout.xml, I use:
<FrameLayout .... >
<some.package.MyCustomView ... />
<LinearLayout ... >
<TextView ...
android:id="#+id/txtLat" />
...
</LinearLayout>
</FrameLayout>
In my Activity I do:
...
setContentView( R.layout.location_layout );
and in my custom view class:
...
TextView tv = (TextView) findViewById( R.id.txtLat );
which returns null. Doing this, my Activity works fine. So maybe it's because of the Activity.findViewById and View.findViewById differences. So I stored the context passed to the customs view constructor locally and tried:
...
TextView tv = (TextView) ((Activity) context).findViewById( R.id.txtLat );
which also returned null.
Then, I changed my custom view to extend ViewGroup instead View and changed the location_layout.xml to let the TextView be a direct child of my custom view, so that the View.findViewById should work as supposed. Suprise: it didn't solve anything.
So what the heck am I doing wrong?
I'll appreciate any comments.
which returns null
Possibly because you are calling it too early. Wait until onFinishInflate(). Here is a sample project demonstrating a custom View accessing its contents.
Possibly, you are calling findViewById before calling setContentView?
If that's the case, try calling findViewById AFTER calling setContentView
Make sure you don't have multiple versions of your layout for different screen densities. I ran into this problem once when adding a new id to an existing layout but forgot to update the hdpi version. If you forget to update all versions of the layout file it will work for some screen densities but not others.
FindViewById can be null if you call the wrong super constructor in a custom view. The ID tag is part of attrs, so if you ignore attrs, you delete the ID.
This would be wrong
public CameraSurfaceView(Context context, AttributeSet attrs) {
super(context);
}
This is correct
public CameraSurfaceView(Context context, AttributeSet attrs) {
super(context,attrs);
}
Alongside the classic causes, mentioned elsewhere:
Make sure you've called setContentView() before findViewById()
Make sure that the id you want is in the view or layout you've given to setContentView()
Make sure that the id isn't accidentally duplicated in different layouts
There is one I have found for custom views in standard layouts, which goes against the documentation:
In theory you can create a custom view and add it to a layout (see here). However, I have found that in such situations, sometimes the id attribute works for all the views in the layout except the custom ones. The solution I use is:
Replace each custom view with a FrameLayout with the same layout properties as you would like the custom view to have. Give it an appropriate id, say frame_for_custom_view.
In onCreate:
setContentView(R.layout.my_layout);
FrameView fv = findViewById(R.id.frame_for_custom_layout);
MyCustomView cv = new MyCustomView(context);
fv.addView(cv);
which puts the custom view in the frame.
In my case, I had 2 activites in my project, main.xml and main2.xml. From the beginning, main2 was a copy of main, and everything worked well, until I added new TextView to main2, so the R.id.textview1 became available for the rest of app. Then I tried to fetch it by standard calling:
TextView tv = (TextView) findViewById( R.id.textview1 );
and it was always null. It turned out, that in onCreate constructor I was instantiating not main2, but the other one. I had:
setContentView(R.layout.main);
instead of
setContentView(R.layout.main2);
I noticed this after I arrived here, on the site.
#Override
protected void onStart() {
// use findViewById() here instead of in onCreate()
}
A answer for those using ExpandableListView and run into this question based on it's title.
I had this error attempting to work with TextViews in my child and group views as part of an ExpandableListView implementation.
You can use something like the following in your implementations of the getChildView() and getGroupView() methods.
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.child_layout, null);
}
I found this here.
FWIW, I don't see that anyone solved this in quite the same way as I needed to. No complaints at compile time, but I was getting a null view at runtime, and calling things in the proper order. That is,
findViewById()
after
setContentView().
The problem turned out that my view is defined in content_main.xml, but in my activity_main.xml, I lacked this one statement:
<include layout="#layout/content_main" />
When I added that to activity_main.xml, no more NullPointer.
I'm pretty new to Android/Eclipse, by mistake I added the UI stuff to activity_main.xml instead of fragment_main.xml. Took me some hours to figure that out...
I had this same problem. I was using a third-party library that allows you to override their adapter for a GridView and to specify your own layout for each GridView cell.
I finally realized what was happening. Eclipse was still using the library's layout xml file for each cell in the GridView, even though it gave no indication of this. In my custom adapter, it indicated that it was using the xml resource from my own project even though at runtime, it wasn't.
So what I did was to make sure my custom xml layouts and ids were different from those still sitting in the library, cleaned the project and then it started reading the correct custom layouts that were in my project.
In short, be careful if you're overriding a third-party library's adapter and specifying your own layout xml for the adapter to use. If your layout inside your project has the same file name as that in the library, you might encounter a really difficult-to-find bug!
In my particular case, I was trying to add a footer to a ListView. The following call in onCreate() was returning null.
TextView footerView = (TextView) placesListView.findViewById(R.id.footer);
Changing this to inflate the footer view instead of finding it by ID solved this issue.
View footerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_view, null, false);
Just wanted to throw my specific case in here. Might help someone down the line.
I was using the directive in my Android UI XML like this:
Parent view:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:tag="home_phone"
android:background="#color/colorPrimary">
...
<include
layout="#layout/retry_button"
android:visibility="gone" />
Child view (retry_button):
<com.foo.RetryButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/retry"
android:layout_gravity="center"
android:orientation="vertical"
android:layout_width="100dp"
android:layout_height="140dp">
.findViewById(R.id.retry) would always return null. But, if I moved the ID from the child view into the include tag, it started working.
Fixed parent:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:tag="home_phone"
android:background="#color/colorPrimary">
...
<include
layout="#layout/retry_button"
android:id="#+id/retry"
android:visibility="gone" />
Fixed child:
<com.foo.RetryButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_gravity="center"
android:orientation="vertical"
android:layout_width="100dp"
android:layout_height="140dp">
In my case, I was using ExpandableListView and I had set android:transcriptMode="normal". This was causing few children in expandable group to disappear and I used to get NULL exception when ever I used scroll the list.
For me I had two xml layouts for the same activity - one in portrait mode and one in landscape. Of course I had changed the id of an object in the landscape xml but had forgotten to make the same change in the portrait version. Make sure if you change one you do the same to the other xml or you will not get an error until you run/debug it and it can't find the id you didn't change. Oh dumb mistakes, why must you punish me so?
Set the activity content from a layout resource.
ie.,setContentView(R.layout.basicXml);
In addition of the above solutions you make sure the
tools:context=".TakeMultipleImages"
in the layout is same value in the mainfest.xml file :
android:name=".TakeMultipleImages" for the same activity element.
it is occur when use copy and paste to create new activity
I have the same problem, but I think its worth sharing with you guys.
If you have to findViewById in custom layout, for example:
public class MiniPlayerControllBar extends LinearLayout {
//code
}
you cannot get the view in constructor.
You should call findViewById after view has inflated.
Their is a method you can override onFinishInflate
My case is none like above, no solutions worked. I assume my view was too deep into layout hierarchy. I moved it one level up and it was not null anymore.
INFLATE THE LAYOUT !! (which contains the id)
In my case findViewById() returned null, because the layout in which the element was written, was not inflated...
Eg.
fragment_layout.xml
<ListView
android:id="#+id/listview">
findViewById(R.id.listview) returned null, because I had not done
inflater.inflate(R.layout.fragment_layout, ..., ...);
before it.
Hope this answer helps some of y'all.
In my case I had inflated the layout but the child views were returning null. Originally I had this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
footerView = ((LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listview_footer, null, false);
pbSpinner = (ProgressBar) findViewById(R.id.pbListviewFooter);
tvText = (TextView) findViewById(R.id.tvListviewFooter);
...
}
However, when I changed it to the following it worked:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
footerView = ((LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listview_footer, null, false);
pbSpinner = (ProgressBar) footerView.findViewById(R.id.pbListviewFooter);
tvText = (TextView) footerView.findViewById(R.id.tvListviewFooter);
...
}
The key was to specifically reference the already inflated layout in order to get the child views. That is, to add footerView:
footerView.findViewById...
It crashed for me because one of fields in my activity id was matching with id in an other activity. I fixed it by giving a unique id.
In my loginActivity.xml password field id was "password". In my registration activity I just fixed it by giving id r_password, then it returned not null object:
password = (EditText)findViewById(R.id.r_password);
In my experience, it seems that this can also happen when your code is called after OnDestroyView (when the fragment is on the back stack.) If you are updating the UI on input from a BroadCastReceiver, you ought to check if this is the case.
findViewById also can return null if you're inside a Fragment. As described here: findViewById in Fragment
You should call getView() to return the top level View inside a Fragment. Then you can find the layout items (buttons, textviews, etc)
In my case, findViewById returned null when I moved the call from a parent object into an adapter object instantiated by the parent. After trying tricks listed here without success, I moved the findViewById back into the parent object and passed the result as a parameter during instantiation of the adapter object.
For example, I did this in parent object:
Spinner hdSpinner = (Spinner)view.findViewById(R.id.accountsSpinner);
Then I passed the hdSpinner as a parameter during creation of the adapter object:
mTransactionAdapter = new TransactionAdapter(getActivity(),
R.layout.transactions_list_item, null, from, to, 0, hdSpinner);
I was facing a similar problem when I was trying to do a custom view for a ListView.
I solved it simply by doing this:
public View getView(int i, View view, ViewGroup viewGroup) {
// Gets the inflater
LayoutInflater inflater = LayoutInflater.from(this.contexto);
// Inflates the layout
ConstraintLayout cl2 = (ConstraintLayout)
inflater.inflate(R.layout.custom_list_view, viewGroup, false);
//Insted of calling just findViewById, I call de cl2.findViewById method. cl2 is the layout I have just inflated.
TextView tv1 = (TextView)cl2.findViewById(cl2);
Ways to debug and find the issue:
Comment out all findViewById in your activity.
Comment out everything except onCreate and setContentView
Run the project and see if any layout is set
In my case, I was using activity_main.xml in both my app module and also my library module. So when I performed the above steps, instead of the layout which I designed in the library, the layout inside app module was inflated.
So I changed the activity_main.xml file name to activity_main_lib.xml.
So make sure you do not have any duplicate layout names in your whole project.
The issue for me was that I had two layouts with the same file name activity_main.xml. (The layouts were in different libraries but in the same app) The issue was solved by renaming one of them to a unique name.
For me it returned null because the given control was (programmatically) hidden. When I put a condition to call findViewByID(id) only when the control is visible, it started working again.
For me it was only null when using Evaluate Expression or the Debug Watch View of the IDE.

Android studio Can't find button ID in java file

I've started working on a menu for my app and I'm trying to start an activity from a fragment. My fragment code looks like this;
public class Studies extends Fragment {
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Studies");
}
public void goToAttract(View v) {
Intent intent = new Intent(getActivity(), informaticainfo.class);
startActivity(intent);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.studies, container, false);
}}
I've got this working in a different project so I do not think that is the problem, my XML button to go to the next activity looks like this;
<Button
android:id="#+id/I"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="40dp"
android:background="#drawable/buttonshape"
android:onClick="goToAttract" <---- is this wrong?
android:paddingLeft="130sp"
android:paddingRight="130sp"
android:text="#string/informatica"
android:textColor="#ffffff" />
I've declared the new activity in the Manifest, but the XML file keeps giving this error at the line specified above;
Cannot resolve symbol 'goToAttract' less
Inspection info: Checks if the method specified in onClick XML attribute is declared in related activity.
Does the method I'm using above not work with fragments? Why can it not find the function I have working in another project?
Check this link [How exactly does the android:onClick XML attribute differ from setOnClickListener?
According to this that with the XML above, Android will look for the onClick method only in the current Activity. This is important to remember if you are using fragments, since even if you add the XML above using a fragment, Android will not look for the onClick method in the .java file of the fragment used to add the XML.
Declaring and assigning value to onClickin XML does not work in fragment, use OnClickListener programmatically instead of using onClick in XML.

How to get information from my Android Fragment to MyActivity.java

I'm trying to learn to create an Android fragment to implement an amount insert box which I can reuse throughout my application. So I create a simple xml file which has some EditText boxes. I then created the associated java file called AmountFragment.java:
public class AmountFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.amount_fragment, container, false);
return view;
}
}
I then use this fragment in another xml file:
<fragment
android:name="com.example.android.ui.widget.AmountFragment"
android:id="#+id/transaction_amount"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
This works fine so far. It shows the fragment fine and I can insert numbers in it. I now want to be able to get the inserted text in the mainActivity. So I read this page on Fragments from the Android docs, but I'm totally lost. The code they show makes no sense at all to me. I need to define an interface, but I have no clue what I have to do with it. I tried simply copy-pasting it over, but I get an InflateException. Since I don't even know what's going on I have no clue where to look for a solution.
So my question: can anybody give me some pointers on how to interface this fragment with the Activity in which I use it?
Try the following code.
In MainActivity.java add
public void getMessage(Object obj) {
Log.d("My App", "Look at my object " + obj.toString();
}
That will get objects from your AmountFragment, then in your AmountFragment write:
String anyObject = "Yay something";
((MainActivity)getActivity()).getMessage(anyObject);
What's happening here is that getActivity() will get the instance of the Activity which contains the fragment, then you cast it to your activity, MainActivity, and call the receiver method you wrote for it.

Android: Best way to retain listview content in fragment in tabbed app?

Firstly, this is my first question on StackOverflow so please forgive any formatting issues etc.
I'm writing an Android tablet application which allows users to populate a ListView with content pulled from a web service. At the minute there is one activity which contains a ViewPager which contains 6 fragments on different pages.
The issue is that the data which is downloaded and added to the ListView disappears when the user changes to another tab/back again and the Fragment's OnCreateView method is called (which initialises the ListView back to empty)
What's the best way of keeping the content of the listview besides storing it in a database/sharedprefs. The data in the listview needs to be destroyed when the user logs out/restarts the application, so I'm hoping to not persist it in any way.
the OnCreateView of the ListView container fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_certificate_list, container, false);
return rootView;
}
And here's the code which populates the ListView when the user hits the download button:
ListView lv = (ListView) callerActivity.findViewById(R.id.listView1);
lv.setAdapter(new CertListAdapter(callerActivity.getBaseContext(), activeCerts));
if (activeCerts.size() > 0) {
((TextView) callerActivity.findViewById(R.id.certStatusLabel)).setVisibility(View.GONE);
} else {
((TextView) callerActivity.findViewById(R.id.certStatusLabel)).setText(callerActivity.getString(R.string.certsDontExist));
}
the activeCerts variable is an arraylist of certificate objects which are obtained from the web service.
EDIT
Found a solution for this, to simply check if the "activeCerts" variable is null in the onCreateView method and populate the ListView again if it's not null. When the user logs out I'll just set activeCerts to null.
Cheers
"Correct" way:
use Fragment.onSaveInstanceState(Bundle) and Fragment.onActivityCreated(Bundle) to save and restore your items
Cheap way:
set android:configChanges="orientation|keyboardHidden|screenSize" on your activity hosting the fragment
You can also setRetainInstance(true); in the onCreate() of your Fragment
Read more about all this here.

Categories