Error inflating class fragment. What can I do here? - java

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.

Related

Why does the change in position of the setContentView change the behavior of the the app?

When I place "setContentView" above the "NumbersClickListners" line the app works as expected.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NumbersClickListners numbersClickListners = new NumbersClickListners();
TextView numbers = (TextView) findViewById(R.id.numbers);
numbers.setOnClickListener(numbersClickListners);
}
But as soon as the "setContentView" is placed below the three lines starting with "NumbersClickListners" the app crashes. The code looks like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
NumbersClickListners numbersClickListners = new NumbersClickListners();
TextView numbers = (TextView) findViewById(R.id.numbers);
numbers.setOnClickListener(numbersClickListners);
setContentView(R.layout.activity_main);
}
I'm pretty much unsure of the reason for this behavior. Can anybody help me with that please?
Let's look at the life of layout.
First of all, you have to create it by declaring XML file, where you do your design in a user-friendly way and name the elements according to your needs.
Now your layout is just a file, that Android doesn't really care about for performance reasons.
Next thing you wanna do is use your layout. To do that your file needs to be converted to internal structure of objects known as ViewGroup and Views.
This process is called inflating. That's the point where the system can find the views for you by calling findViewById().
So in the second snippet you ask activity to find you a button, which is not inflated. That leads to throwing exception.
Generally speaking, first thing you want to do in the onCreate is to call setContentView().

In android Studio, I want when i click on button , next activity/fragment should come from right side

In android Studio, I want when i click on button , next activity/fragment should come from right side and present activity sholud gone left.I implimented its working on Activity but not on adapters is showing error.
holder.questions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(DoctorsProfile.this,Questions.class);
i.putExtra("DOCTOR_ID",doctor_id);
startActivity(i);
overridePendingTransition( R.anim.slide_in_right_up, R.anim.slide_out_right_up);
}
});
overridePendingTransition is working on Activity but not working on Adapters of Recyclerview and Listview, Please tell any other option. I want when i click on recyclerview item next Activity should navigate or come from right side by using overridePendingTransition.
Fragment fragment = Fragment.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.fragment_slide_left_enter,
R.anim.fragment_slide_left_exit, R.anim.fragment_slide_right_enter,
R.anim.fragment_slide_right_exit);
Utils.addFragmentToActivity(fragmentTransaction, Fragment, R.id
.content_frame);
This tip features how to change Android’s default animation when switching between Activities.
The code to change the animation between two Activities is very simple: just call the overridePendingTransition() from the current Activity, after starting a new Intent. This method is available from Android version 2.0 (API level 5), and it takes two parameters, that are used to define the enter and exit animations of your current Activity.
Here’s an example:
//Calls a new Activity
startActivity(new Intent(this, NewActivity.class));
//Set the transition -> method available from Android 2.0 and beyond
overridePendingTransition(R.anim.slide_in_right_up, R.anim.slide_out_right_up);
These two parameters are resource IDs for animations defined with XML files (one for each animation). These files have to be placed inside the app’s res/anim folder. Examples of these files can be found at the Android API demo, inside the anim folder.
for example code visit http://www.christianpeeters.com/android-tutorials/tutorial-activity-slide-animation/#more-483
Change like this code you must be passing activity as context in adapter
holder.questions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(DoctorsProfile.this,Questions.class);
i.putExtra("DOCTOR_ID",doctor_id);
Activity activity = (Activity) context;
activity.startActivity(i);
activity.overridePendingTransition(R.anim.slide_in_right_up, R.anim.slide_out_right_up);
}
});
Note : Context is the Base Object of Activity
Update :
I have checked the accepted answer but hope you understand that it will be called everytime when your activity get launched and thats not supposed to be best practice. I am suggesting better approach if you want to follow the accepted answer .
Alternative :
Pass one parameter in bundle to new activity to make sure that transition coming from that specific adapter so double transation should not happen when you are coming rom any other activity also.
There is a easy way to do this. just put overridePendingTransition on your OnCreate method of next Activity/Fragment.So that when next Activity will come it will come according to your choice.Need not add overridePendingTransition on adapters.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ask_question);
overridePendingTransition( R.anim.slide_in_right_up, R.anim.slide_out_right_up);
}

Material Design ToolBar with ListActivity

I am replacing the ActionBar and integrating the Material Design ToolBar within my app. One of my activity's extends ListActivity.
In the onCreate() method, whenever I try to add the ToolBar, the setSupportActionBar() method is producing an error saying it cannot be resolved.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_route_recipients);
// Attaching the toolbar layout to the toolbar object
toolbar = (Toolbar) findViewById(R.id.tool_bar);
// Setting toolbar as the ActionBar with setSupportActionBar() call
setSupportActionBar(toolbar);
// get the default list view associated with this activity
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); // we can now check and uncheck multiple friends
// get the array of LatLng points passed in from the map intent
markerPoints = getIntent().getParcelableArrayListExtra("markerPoints");
}
What is the best solution to this problem?
You wrote that your activity extends ListActivity but sadly ListActivity doesn't implement setSupportActionBar. You have to base your activity on AppCompatActivity.
You'll say "but hey, but I really need ListActivity as I've ListView in my Activity" -- consider using RecyclerView as well. I'd say that ListView is a dead end now -- one should port code to RecyclerViews
And as a help, two sample projects showing all new features of Material Design
https://github.com/antoniolg/MaterializeYourApp
https://github.com/chrisbanes/cheesesquare

Issues with code in dynamically created fragments

I'm building an app with multiple pages to it, each of the main pages is displayed in a fragment in the main activity. Whenever the user wants to change page, the fragment within the activity is changed.
I want to write the code for each fragment within its own java file, as opposed to writing the code for all of the fragments within the main activity.
I've tried putting each bit of code within the fragment's onCreate and onCreateView methods (including trying onStart, onPause and whole other load of ones) but I've noticed that when the fragment is created the code just isn't running.
I've seen other questions on here with similar issues but none of the answers offered me an actual solution.
My question is this, how can I write the code for each fragment within that fragment's java file and actually get it to run? I understand this would be much easier if my fragments were created statically in the activity but these are not, they are created at runtime.
For reference, each fragment is displayed in the activity like so:
fragmentManager.beginTransaction().replace(R.id.container, HomeFragment.newInstance(position)).commit();
Try this,
From main activity you can call a static method defined in your fragment class as:
AuthFragment.NewInstance(LoginActivity.this, constantsObj);
This only line will go in your fragment calling activity.
Now in your fragment, inside the static method, find and create the fragment as,
public static void NewInstance(LoginActivity activityContext, Constants constantsObj) {
clsConstantsObj = constantsObj;
urlToCatch = clsConstantsObj.toString();
urlToCatch = urlToCatch.replace("/params", "");
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
activityContextInFragment = activityContext;
fragmentManager = activityContext.getSupportFragmentManager();
AuthFragment findAuthFragment = (AuthFragment) fragmentManager
.findFragmentByTag("authFragment");
if (findAuthFragment == null) {
AuthFragment authFragment = new AuthFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.mainviewRegionwise, authFragment, "authFragment");
fragmentTransaction.commit();
}
}
Notice the "R.id.mainviewRegionwise", which is the id of your main container which could be a FrameLayout or any other container.

Difference between fragment_main.xml and activity_main.xml

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

Categories