Android Fragment crashing on orientation change - android

I'm trying to add a simple fragment and it works perfectly when I use it, until I switch rotations than it crashes.
Here is my code:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
//region Fragment
if(savedInstanceState==null){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment_Titlebar fragment = new Fragment_Titlebar();
fragmentTransaction.add(R.id.fragment, fragment);
fragmentTransaction.commit();
Fragment_Titlebar header = (Fragment_Titlebar) getFragmentManager().findFragmentById(R.id.fragment);
header.initFragment(R.string.SignUp, 0, true, true);}
//endregion
voornaam = (EditText)findViewById(R.id.first_name_text);
achternaam = (EditText)findViewById(R.id.last_name_text);
profile = (CircleImageView)findViewById(R.id.profile_image);
try {
//Getting the google account
Intent intent = getIntent();
if (intent.getExtras().get("User") instanceof GoogleSignInAccount) {
GoogleSignInAccount acct = (GoogleSignInAccount) intent.getExtras().get("User");
voornaam.setText(acct.getGivenName());
achternaam.setText(acct.getFamilyName());
if (acct.getPhotoUrl() != null) {
Picasso.with(this).load(acct.getPhotoUrl()).into(profile);
}
}
}
catch (NullPointerException e)
{
}
}}
And the Fragment:
private TextView headerText;
private ImageButton backButton;
private ImageButton homeButton;
private Toolbar background;
public Fragment_Titlebar(){}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_title_bar, container, false);
backButton = (ImageButton) view.findViewById(R.id.backButton);
backButton.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v) {
goBack(v);
}
});
homeButton = (ImageButton) view.findViewById(R.id.homeButton);
homeButton.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v) {
goHome(v);
}
}
);
headerText = (TextView) view.findViewById(R.id.headerText);
background = (Toolbar) view.findViewById(R.id.background);
return view;
}
finally the error message:
FATAL EXCEPTION: main
Process: rickvanfessem.carcoolandroid, PID: 18652
java.lang.RuntimeException: Unable to start activity ComponentInfo{rickvanfessem.carcoolandroid/rickvanfessem.carcoolandroid.AddUser}: android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class fragment
I already tried to do this setRetainInstance(true) but that didn't work.
Please Help
EDIT AFTER REQUEST FOR XML
XML of the Fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
xmlns:android="http://schemas.android.com/apk/res/android">
<Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/background"
android:background="#color/HeaderRed"
app:theme="#style/AppTheme"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/backButton"
style="#style/image_style"
android:layout_alignParentLeft="true"
android:src="#drawable/ic_arrow_back"
/>
<TextView
android:id="#+id/headerText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
style="#style/HeaderText"
tools:text="Test scherm"/>
<ImageButton
android:id="#+id/homeButton"
style="#style/image_style"
android:layout_alignParentRight="true"
android:src="#drawable/ic_home"
/>
</RelativeLayout>
</Toolbar>
</LinearLayout>

try this
Edit your Manifest
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
/>
and in MainActivity
add this Override Method
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation== Configuration.ORIENTATION_PORTRAIT)
{
}
else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
}
}

Related

Call to Fragment clears app view on startActivity()

I am new to Android development and have added an additional item to a Navigation menu which successfully opens an external browser window but clears the app screen (except for the navigation menu) when startActivity in onActivityCreated is performed.
I am not making any more progress despite working on this for several days so I am asking for help now. Perhaps this is a simple question for someone with more experience. I have spent a week looking at all the other answers in SO, YouTube and Google Developer Courses trying to solve this so I am asking for help now.
WebsiteFragment.java
public class WebsiteFragment extends Fragment {
View myFragment;
RecyclerView websiteList;
LinearLayoutManager layoutManager;
private static final String COMMON_TAG="CombinedLifeCycle";
private static final String ACTIVITY_NAME =WebsiteFragment.class.getSimpleName();
private static final String TAG=ACTIVITY_NAME;
public static WebsiteFragment newInstance() {
WebsiteFragment websiteFragment = new WebsiteFragment();
return websiteFragment;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_website, container, false);
Log.i(TAG,ACTIVITY_NAME+" onCreateView");
websiteList = (RecyclerView)view.findViewById(R.id.websiteList);
layoutManager = new LinearLayoutManager(getActivity());
websiteList.setHasFixedSize(true);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("https://english-alps.com"));
// App Window is cleared??
getActivity().startActivity(i);
Log.i(TAG,ACTIVITY_NAME+" onActivityCreated");
}
}
fragment_webiste.xml
<?xml version="1.0" encoding="utf-8"?>
<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=".WebsiteFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/websiteList"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
</FrameLayout>
Edit 21-08-2018
Added the following code to try and save Fragment state but it generates the error:
java.lang.NullPointerException: Attempt to read from field 'int androidx.fragment.app.Fragment.mIndex' on a null object referen.
I am having trouble with the parameters to getFragmentManager. How should the variables to getFragmentManager be initialized?
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState!=null){
Log.i(TAG,ACTIVITY_NAME+" calling onSaveInstanceState");
onSaveInstanceState(savedInstanceState);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getFragmentManager().putFragment(outState,TAG,myFragment);
Log.i(TAG,ACTIVITY_NAME+" onSaveInstanceState");
}
Edit#2 21-08-2018
Home.Java which adds WebsiteFragment to the Activity
public class Home extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()) {
case R.id.action_category:
selectedFragment = CategoryFragment.newInstance();
break;
case R.id.action_ranking:
selectedFragment = RankingFragment.newInstance();
break;
case R.id.action_website:
selectedFragment = WebsiteFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, selectedFragment);
transaction.addToBackStack(String.valueOf(R.id.frame_layout)); /* 21.08.2018 */
transaction.commit();
return true;
}
});
setDefaultKeyMode();
}
}
Edit #3 21-08-2018 activity_home.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="match_parent"
android:layout_height="match_parent"
tools:context=".Home">
<FrameLayout
android:id="#+id/frame_layout"
android:animateLayoutChanges="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/navigation"></FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/colorPrimary"
app:itemIconTint="#drawable/nav_item_color_state"
app:itemTextColor="#drawable/nav_item_color_state"
app:menu="#menu/bottom_menu"
/>
</RelativeLayout>

Android "No view found for id for fragment"

Okay. I am stuck and having a headache... I am not sure how to access the other layout's view, since inflating does not work.
Here are my codes.
WriteRouteActivity.java
public class WriteRouteActivity extends AppCompatActivity {
private Toolbar tb;
private TextView txt_toolbar_title;
private Button btnSearchPlaces;
private LinearLayout parentLayout, placesCoverLayout;
private View popupView;
private ImageView imgShowPlaces;
private boolean isKeyBoardVisible;
private int keyboardHeight;
private EditText edtSearchPlaces;
private PopupWindow popupWindow;
//popupView
private TabLayout tabLayout;
private FrameLayout frameLayout;
//prework
private int minusVal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write_route);
initView();
}
private void initView() {
//for activity and native back button
tb = (Toolbar) findViewById(R.id.nav_toolbar);
setSupportActionBar(tb);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
txt_toolbar_title = (TextView) findViewById(R.id.txt_toolbar);
parentLayout = (LinearLayout) findViewById(R.id.layout_parent);
placesCoverLayout = (LinearLayout) findViewById(R.id.footer_for_places);
imgShowPlaces = (ImageView) findViewById(R.id.img_show_places);
edtSearchPlaces =(EditText) findViewById(R.id.edt_search_place);
btnSearchPlaces = (Button) findViewById(R.id.btn_search_place);
popupView = getLayoutInflater().inflate(R.layout.places_popup, null);
tabLayout = (TabLayout) popupView.findViewById(R.id.tab_layout);
frameLayout = (FrameLayout) popupView.findViewById(R.id.frame_layout);
doWorkForLayotus();
}
private void doWorkForLayotus(){
final float popUpheight = getResources().getDimension(R.dimen.keyboard_height);
changeKeyboardHeight((int) popUpheight);
enablePopUpView();
setTabLayout();
checkKeyboardHeight(parentLayout);
enableFooterView();
}
public void setCurrentTabFragment(int position) throws IllegalAccessException, InstantiationException {
String tag="";
Fragment fr = null;
Class frClass = null;
FragmentManager frManager = getSupportFragmentManager();
switch (position) {
case 0:
tag = "first";
//hide
if(frManager.findFragmentByTag("second")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("second")).commit();
}
if(frManager.findFragmentByTag("third")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("third")).commit();
}
if(frManager.findFragmentByTag("fourth")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("fourth")).commit();
}
//show
if(frManager.findFragmentByTag("first")!=null){
frManager.beginTransaction().show(frManager.findFragmentByTag("first")).commit();
}else{ //add
try {
frManager.beginTransaction().add(frameLayout.getId(), ((Fragment) Fragment_zasin.class.newInstance()), tag).commit();
}catch(Exception e){
Log.e("why", e.getMessage().toString());
}
}
break;
case 1:
tag = "second";
//hide
if(frManager.findFragmentByTag("first")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("first")).commit();
}
if(frManager.findFragmentByTag("third")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("third")).commit();
}
if(frManager.findFragmentByTag("fourth")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("fourth")).commit();
}
//show
if(frManager.findFragmentByTag("second")!=null){
frManager.beginTransaction().show(frManager.findFragmentByTag("second")).commit();
}else{ //add
frManager.beginTransaction().add(frameLayout.getId(), ((Fragment) Fragment_zasin.class.newInstance()), tag).commit();
}
break;
case 2:
tag = "third";
//hide
if(frManager.findFragmentByTag("first")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("first")).commit();
}
if(frManager.findFragmentByTag("second")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("second")).commit();
}
if(frManager.findFragmentByTag("fourth")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("fourth")).commit();
}
//show
if(frManager.findFragmentByTag("third")!=null){
frManager.beginTransaction().show(frManager.findFragmentByTag("third")).commit();
}else{ //add
frManager.beginTransaction().add(frameLayout.getId(), ((Fragment) Fragment_zasin.class.newInstance()), tag).commit();
}
break;
case 3:
tag = "fourth";
//hide
if(frManager.findFragmentByTag("first")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("first")).commit();
}
if(frManager.findFragmentByTag("second")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("second")).commit();
}
if(frManager.findFramentByTag("third")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("third")).commit();
}
//show
if(frManager.findFragmentByTag("fourth")!=null){
frManager.beginTransaction().show(frManager.findFragmentByTag("fourth")).commit();
}else{ //add
frManager.beginTransaction().add(R.id.frame_layout, ((Fragment) Fragment_zasin.class.newInstance()), tag).commit();
}
break;
}
//frManager.beginTransaction().replace(R.id.frame_container, fr, tag).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
}
private void setTabLayout(){
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
try {
setCurrentTabFragment(tab.getPosition());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void enablePopUpView() {
// Creating a pop window for emoticons keyboard
popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT,
(int) keyboardHeight, false);
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
placesCoverLayout.setVisibility(LinearLayout.GONE);
}
});
}
int previousHeightDiffrence = 0;
private void checkKeyboardHeight(final View parentLayout) {
parentLayout.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
Rect r = new Rect();
parentLayout.getWindowVisibleDisplayFrame(r);
int screenHeight = parentLayout.getRootView()
.getHeight();
minusVal=screenHeight-r.bottom;
int heightDifference = screenHeight - (r.bottom+(minusVal));
if (previousHeightDiffrence - heightDifference > 50) {
popupWindow.dismiss();
}
previousHeightDiffrence = heightDifference;
if (heightDifference > 100) {
isKeyBoardVisible = true;
changeKeyboardHeight(heightDifference);
} else {
isKeyBoardVisible = false;
}
}
});
}
private void changeKeyboardHeight(int height) {
if (height > 100) {
keyboardHeight = height;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, keyboardHeight);
placesCoverLayout.setLayoutParams(params);
}
}
private void enableFooterView() {
edtSearchPlaces.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (popupWindow.isShowing()) {
popupWindow.dismiss();
}
}
});
btnSearchPlaces.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideSoftKeyboard(WriteRouteActivity.this);
if(!popupWindow.isShowing()){
popupWindow.setHeight((int) (keyboardHeight));
if (isKeyBoardVisible) {
placesCoverLayout.setVisibility(LinearLayout.GONE);
} else {
placesCoverLayout.setVisibility(LinearLayout.VISIBLE);
}
popupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
popupWindow.showAtLocation(parentLayout, Gravity.BOTTOM, 0, 0);
try {
setCurrentTabFragment(0);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
} else {
//popupWindow.dismiss();
}
}
});
}
#Override
protected void onDestroy() {
popupWindow.dismiss();
super.onDestroy();
}
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(), 0);
}
#Override
public void onBackPressed() {
if(popupWindow.isShowing()){
popupWindow.dismiss();
}else {
super.onBackPressed();
}
}
}
activity_write_wroute.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/nav_toolbar" />
<fragment
android:id="#+id/google_map"
class="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<include
android:id="#+id/footer_layout"
layout="#layout/footer_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/footer_for_places"
android:layout_width="match_parent"
android:layout_height="#dimen/keyboard_height"
android:background="#android:color/transparent"
android:orientation="vertical"
android:visibility="gone" />
</LinearLayout>
Fragment_Zasin
public class Fragment_zasin extends Fragment {
public Fragment_zasin newInstance() {
Fragment_zasin fr = new Fragment_zasin();
return fr;
}
public Fragment_zasin() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_zasin, container, false);
return rootView;
}
}
places_popup.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/linear_layout_top"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="fill_parent"
android:layout_height="?attr/actionBarSize"
android:background="#ffffff"
app:tabGravity="fill"
app:tabIndicatorColor="#color/colorPrimary"
app:tabIndicatorHeight="4dp"
app:tabMode="fixed"
app:tabSelectedTextColor="#color/colorPrimary">
<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/tab_pin_selector"
android:text="11">
</android.support.design.widget.TabItem>
<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/tab_mainroute_selector"
android:text="22" />
<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/tab_talk_selector"
android:text="33" />
<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/tab_my_selector"
android:text="44" />
</android.support.design.widget.TabLayout>
<FrameLayout
android:id="#+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1" />
</LinearLayout>
LOGCAT Message
FATAL EXCEPTION: main Process: suacuration.itgotravel, PID: 20131
java.lang.IllegalArgumentException: No view found for id 0x7f100173 for fragment Fragment_zasin{d4ac39c #0 id=0x7f100173 first}
Can somebody help this?
This error occurs because the fragment manager could not find the view on which it has to inflate the fragment.
The fragment transaction is linked to the activity so this error occurs as the frame layout is not a part of that main activity's xml.so it cant find where to add the fragment.fragment has to be added inside the activity.
what you have to do is provide the id of a view in your main activity.
for e.g your main view
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mainView"//like this
android:orientation="vertical">
<include layout="#layout/nav_toolbar" />
<fragment
android:id="#+id/google_map"
class="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<include
android:id="#+id/footer_layout"
layout="#layout/footer_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/footer_for_places"
android:layout_width="match_parent"
android:layout_height="#dimen/keyboard_height"
android:background="#android:color/transparent"
android:orientation="vertical"
android:visibility="gone" />
</LinearLayout>
The view where you are trying to inflate the fragemnt must be inside activity.
Now when you try
frManager.beginTransaction().add(R.id.mainView, ((Fragment) Fragment_zasin.class.newInstance()), tag).commit();
the fragment will be loaded on this view of your activity.
Problem is you are trying to show a Fragment on a View which is not defined in your layout which you have defined in your onCreate() while setContentView(layoutId)
In your case you are inflating fragments in WriteRouteActivity where layout defined is activity_write_route and fragments are added on FrameLayout which is defined in places_popup.xml so define your framelayout in a view layout of Activity.
Small Description :
--------code------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
-------layout define for activity-------
setContentView(R.layout.activity_write_route);
}
now where you are adding fragment on a FrameLayout(view)
frManager.beginTransaction().add(R.id.frame_layout, ((Fragment) Fragment_zasin.class.newInstance()), tag).commit();
here R.id.frame_layout should be define in your layout activity_write_route.
Okay i found an answer.
The problem was that fragment cannot be a child of a 'Dialog'.
Since i used popup dialog, it was unable to put fragments inside the dialog.
i solved by inflating views rather than using fragments in tablayout.
There could be other errors but what is this?
tb = (Toolbar) findViewById(R.id.nav_toolbar);
This is not a toolbar:
<include layout="#layout/nav_toolbar" />
Can we see inside this nav_toolbar layout?
Also, where is this: "R.layout.fragment_zasin". It's complaining about a Fragment so it would be worthwhile seeing if this is ok.
Anyway, as a general troubleshooting strategy, try commenting out all those lines in the initView() method and just add them in one at a time until it fails. Or maybe if you scroll down in the error logs further it will give you a hyperlink to the line that's causing it to fail.
Why do you have "frameLayout.getId()" on one line but "R.id.frame_layout" on another? Try to use the latter for all of the lines and see if that's it.
I was extending the wrong type of activity, extended AppCompact solved issue.
Got this error when starting new fragment from fragment, using ChildFragmentManager, and giving id of container from activity, in transaction replace method.
It happens that FragmentManager has access to activity containers, but ChildFragmentManager has access to fragment containers.
The solution was to use FragmentManager class instead of ChildFragmentManager.
You got this error because your view found for id 0x7f100173 into fragment Fragment_zasin so only solution is that:
1) check all id present to that particular layout.
2) if all id is present to that particular layout and still you facing same issue do one thing change name of id don't refactor change name and access this changed id name in your fragment or activity.

onCreateView() and onActivityCreated() in MyAddFragment class invokes a lot more than required by working with dynamic fragment

I am new at android app development.I have a problem with my app.I am doing a simple 'Todo List App'. When I deploy my app to android phone.First time it works well.When I change orientation of device, onCreateView() and onActivityCreated() in MyAddFragment works multiple.And 'Add Button' doesn't work after changing orientation.****Please help me how to get rid of the problem.
The following my activity and fragment classes and xml files.
public class MainActivity extends Activity implements Communicator{
FragmentManager man;
private ArrayAdapter<String> todoArrayAdapter;
private ArrayList<String> todoItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
man = getFragmentManager();
MyAddFragment f1 = new MyAddFragment();
MyListFragment f2 = new MyListFragment();
FragmentTransaction transaction = man.beginTransaction();
transaction.add(R.id.frameLayout1, f1, "Add");
transaction.add(R.id.frameLayout2, f2,"List");
Log.i("a", "onCreate - ADDED FRAGMENT");
if (savedInstanceState == null) {
todoItems = new ArrayList<String>();
}else {
todoItems = savedInstanceState.getStringArrayList("veri");
}
todoArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,todoItems);
f2.setListAdapter(todoArrayAdapter);
transaction.commit();
}
public void respond(String data) {
MyListFragment fb = (MyListFragment) man.findFragmentById(R.id.frameLayout2);
todoItems.add(data);
todoArrayAdapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putStringArrayList("veri", todoItems);
}
}
public class MyAddFragment extends Fragment{
Button btnAdd;
EditText txtEdit;
Communicator comm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_add, container,false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
btnAdd = (Button) getActivity().findViewById(R.id.btnAdd);
txtEdit = (EditText) getActivity().findViewById(R.id.txtEdit);
comm = (Communicator) getActivity();
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String newRecord = txtEdit.getText().toString();
comm.respond(newRecord);
txtEdit.setText("");
}
});
}
}
public class MyListFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container,false);
return view;
}
}
public interface Communicator {
public void respond(String data);
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/RelativeLayout1"
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.ceng389hw1.MainActivity" >
<FrameLayout
android:id="#+id/frameLayout1"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:background="#ab3e0f" >
</FrameLayout>
<FrameLayout
android:id="#+id/frameLayout2"
android:layout_width="fill_parent"
android:layout_height="20dp"
android:layout_alignParentBottom="true"
android:layout_below="#+id/frameLayout1"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:background="#ab3eab"
>
</FrameLayout>
</RelativeLayout>
fragment_add.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ab3e0f">
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="#string/btnStringAdd" />
<EditText
android:id="#+id/txtEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/btnAdd"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/btnAdd"
android:ems="10"
android:inputType="text" />
</RelativeLayout>
fragment_list.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:orientation="vertical"
android:background="#ab5810" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
You should change two files in your Application.
First step, you should add following code in androidmanifest file.
android:configChanges="orientation|screenSize"
After you add the code to Androidmanifest, Your androidmanifes file must be like below.
<activity
android:name="com.example.ceng389hw1.MainActivity"
android:configChanges="orientation|screenSize"
android:label="#string/app_name" >
Secon Step, You must be override onConfigurationChanged function like below.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText( this, "landscape", Toast.LENGTH_SHORT ).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
For more detail -> http://developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange
In your main activity check is fragment already added in activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
...
if(getFragmentManager().getFragment("Add")==null) {
//initialize fragment, create transaction and commit
}
...
}
You can add configChanges parametre inside manifest.xml it will provide you to ignore reinilizating after config changes you can do it simply like that
<activity
android:name="com.youractivity"
android:configChanges="orientation" />
I hope it will help you :)

Get edittext value from fragment

I am using fragments,I have an edittext in fragment and I want to get value in main activity.
This is my fragment layout
<?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:orientation="vertical"
android:background="#878787" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="dfgdfgdf"
android:textSize="20dp"
android:layout_centerInParent="true"
android:id="#+id/user_name"/>
<EditText
android:id="#+id/message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:text="Gönder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="getFromUser"
android:layout_marginTop="40dp"
/>
</RelativeLayout>
I am loading fragment with this function:
public void startChat(JsonObject user) {
FrameLayout layout = (FrameLayout)findViewById(R.id.container);
layout.setVisibility(View.VISIBLE);
Bundle bundle = new Bundle();
bundle.putString("name", user.get("name").getAsString());
sendTo=user.get("username").getAsString();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ConversationFragment conv = new ConversationFragment();
conv.setArguments(bundle);
fragmentTransaction.add(R.id.container, conv);
fragmentTransaction.commit();
viewPager.setVisibility(View.GONE);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayHomeAsUpEnabled(true);
}
And this is my fragment class
public class ConversationFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String name = getArguments().getString("name");
View rootView = inflater.inflate(R.layout.fragment_conversation, container, false);
TextView username=(TextView)rootView.findViewById(R.id.user_name);
username.setText(name);
return rootView;
}
}
As you can see when press the button main activity runs "getFromUser" function.I want to get edittext value in this function.How can I do this ?
It's always the same procedure for these things. You can't access a fragment's views just like that. You need a callback method.
Add this code to ConversationFragment:
private OnGetFromUserClickListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnGetFromUserClickListener ) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnGetFromUserClickListener");
}
}
public void getFromUser(View v) {
if (mListener != null) {
EditText edit = (EditText)findViewById(R.id.message);
mListener.getFromUser(edit.getText().toString());
}
}
public interface OnGetFromUserClickListener {
void getFromUser(String message);
}
Make your MainActivity implement this interface. Replace getFromUser() inside MainActivity with:
public void getFromUser(String message) {
sendMessage(message);
}
Done.
Edit:
Actually, using the XML-onClick attribute is currently bugged (see onClick inside fragment called on Activity): It links to the activity instead of the fragment. You have to set the click listener programmatically to make sure the code won't break at some point in the future. So give the button an ID inside the XML (e.g. get_from_user) and add this code to onCreateView inside ConversationFragment:
v.findViewById(R.id.get_from_user).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.get_from_user) {
getFromUser(v);
}
}
});
Using this code vastly decouples the activity and the fragment from each other.
I resolved this problem.
public void getFromUser(View view) {
ConversationFragment fragment1 = (ConversationFragment)getSupportFragmentManager().findFragmentById(R.id.container);
View frag=fragment1.getView();
EditText editText1 =(EditText) frag.findViewById(R.id.message);
String message=editText1.getText().toString();
sendMessage(message);
}
Now I can get edittext value from fragment.

Accessing Views inside fragment

I'm having troubles accessing the Views that within my Fragment. In the example below, I can't access the 2nd button that is within the Fragment (e.g., findViewById appears to return NULL and the app crashes when I try b2.setText("test") ), but when I directly add it in the activity_main.xml, it does work.
Here is the code:
MainActivity.java
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button fragmentButton = (Button)findViewById(R.id.iMainButton);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.iMainInnerLLContainer, new TestFragment());
ft.commit();
final Button b2 = (Button)findViewById(R.id.iTestFragmentInnerButton);
if(b2 == null) { Log.d("MainActivity.java:", "b2 is null"); }
else { Log.d("MainActivity.java:", "b2 is NOT null"); }
fragmentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// do stuff here
}
});
}
}
activity_main.xml
<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:id="#+id/iMainRootLinearLayoutContainer"
android:orientation="vertical"
>
<Button
android:id="#+id/iMainButton"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="Add fragment..."
/>
<LinearLayout
android:id="#+id/iMainInnerLLContainer"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
>
<!-- Fragment goes here, can reference button if it is added here manually -->
</LinearLayout>
</LinearLayout>
TestFragment.java
public class TestFragment extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.ltestfragment, container, false);
}
}
ltestfragment.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:orientation="vertical"
android:id="#+id/iTestFragmentOuterLinearLayout"
>
<Button
android:id="#+id/iTestFragmentInnerButton"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="This is my test fragment button."
/>
</LinearLayout>
I think I'm missing something very basic here and I would appreciate some insight on what that might be.
Thank you in advance!
I think you need to set up a textchangelistener in your fragment.
public class FragmentA extends Fragment {
TextChangeListener listener;
public interface TextChangeListener {
public void onTextChange(CharSequence newText);
}
public void setTextChangeListener(TextChangeListener listener) {
this.listener = listener;
}
Then, in your activity, set up the listener :
public class ActivityAB extends FragmentActivity {
FragmentA fragmentA;
FragmentB fragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ab);
FragmentManager manager = getSupportFragmentManager();
fragmentA = (FragmentA) manager.findFragmentById(R.id.fragmentA);
fragmentB = (FragmentB) manager.findFragmentById(R.id.fragmentB);
fragmentA.setTextChangeListener(new TextChangeListener() {
#Override
public void onTextChange(CharSequence newText) {
fragmentB.updateTextValue(newText);
}
});
}
}
Implement an interface to listen to the events of a fragment from its activity.
Code in Fragment:-
public class TestFragment extends Fragment
{
public interface OnClickListener
{
public void onButtonClicked(<data type><data>);
}
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
listener.onButtonClicked(<<pass some values here>>);
}
});
}
Code in Main:-
MainActivity extends FragmentActivity implements TestFragment.OnClickListener,
{
#Override
public void onButtonClicked(<<receive the pased data here>>) {
//do some stuff here with the received data after the button is clicked
}
}

Categories

Resources