Toolbar text not showing when text is passed there - java

There was such problem: The text which I pass in SelectedActivity simply is not displayed. I have a DrawerLayout with fragments and on click on an element it goes to the SelectedActivity and loads the desired fragment. It works, but the SelectedActivity has a text of Toolbar. It's the one that doesn't show up. I'm new to programming and already completely confused. I would appreciate a solution! Here is my code:
SelectedActivity.java
public class SelectedActivity extends BaseActivity {
private static final String TAG = "SelectedActivity";
private static final String FRAGMENT_NAME = "fragment_name";
public MutableLiveData<String> toolBarTitle = new MutableLiveData<>();
TextView toolbarTitle;
public static void startActivityWithFragment(#NonNull Context context,
#NonNull Class<? extends Fragment> fragmentClass,
#Nullable Bundle bundle) {
context.startActivity(getStartIntent(context, fragmentClass, bundle));
}
private static Intent getStartIntent(#NonNull Context context,
#NonNull Class<? extends Fragment> fragmentClass,
#Nullable Bundle bundle) {
if (bundle == null) {
bundle = new Bundle();
}
bundle.putSerializable(FRAGMENT_NAME, fragmentClass);
Intent intent = new Intent(context, SelectedActivity.class);
intent.putExtras(bundle);
return intent;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selected);
Toolbar toolbar = findViewById(R.id.selected_activity_toolbar);
toolbarTitle = findViewById(R.id.selected_toolbar_title);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
Bundle extras = getIntent().getExtras();
if (extras == null) {
finish();
return;
}
Class<? extends Fragment> fragmentName = (Class<? extends Fragment>) extras.getSerializable(FRAGMENT_NAME);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container_selected_activity, fragmentName, extras)
.commit();
toolBarTitle.observe(this, s -> {
if (s == null) return;
toolbarTitle.setText(s);
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
public void setToolBarTitle(String toolBarTitle){
try {
toolbarTitle.setText(toolBarTitle);
} catch (Exception e) {
e.printStackTrace();
}
}
}
ProfileFragment.java
public class ProfileFragment extends BaseFragment {
private FragmentProfileBinding binding;
public ProfileViewModel profileViewModel;
public View root;
SelectedActivity activity = new SelectedActivity();
public TextView textView;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
profileViewModel = new ViewModelProvider(this).get(ProfileViewModel.class);
binding = FragmentProfileBinding.inflate(inflater, container, false);
textView = binding.textProfile;
profileViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
root = binding.getRoot();
binding.viewPager2.setAdapter(new ViewPagerAdapter(this));
binding.tabLayout.setTabIconTint(null);
new TabLayoutMediator(binding.tabLayout, binding.viewPager2,
(tab, position) -> {
if (position == 0) {
tab.setText(R.string.posts);
new PostsFragment();
} else {
tab.setText(R.string.saved);
new SavesFragment();
}
}).attach();
activity.setToolBarTitle(getString(R.string.menu_profile));
return root;
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
#Override
public void onResume() {
super.onResume();
}
}
activity_selected.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:elevation="0dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="#+id/selected_activity_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<TextView
android:id="#+id/selected_toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center"
android:maxLines="1"
android:elevation="#dimen/dimen_10"
android:textColor="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Selected Activity" />
</androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.appbar.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<FrameLayout
android:id="#+id/container_selected_activity"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Related

Widget layout from Activity still appear after fragment add transaction

I have a problem with fragments. I add fragments dynamically without removing old fragments so they can be recalled when I return. But when I applied the following snippet I found that some of the views that came from the activity did not disappear, such as the Button, TextView, and so on. The results I get are overlapping views
MainActivity.Java
public class MainActivity extends AppCompatActivity implements BlankFragment.OnFragmentInteractionListener {
private static final String TAG = "MainActivity";
private Unbinder unbinder;
private FragmentManager fragmentManager;
#BindView(R.id.dynamic_fragment_frame)
FrameLayout frameLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reading);
unbinder = ButterKnife.bind(this);
fragmentManager = this.getSupportFragmentManager();
}
public void openFragment(View view) {
BlankFragment fragment = BlankFragment.newInstance("Test 1");
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_right);
transaction.addToBackStack(null);
transaction.add(R.id.dynamic_fragment_frame, fragment, "BLACK_FRAGMENT");
transaction.commit();
}
#Override
protected void onDestroy() {
unbinder.unbind();
super.onDestroy();
}
#Override
public void onFragmentInteraction(String text) {
Log.d(TAG, "onFragmentInteraction: " + text);
onBackPressed();
}
}
activity_reading.xml
<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"
android:background="#00d9ff"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/dynamic_fragment_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="#+id/title_read_news"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ini Judul"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:layout_gravity="center"
android:paddingBottom="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="openFragment"
android:text="Open"
android:stateListAnimator="#null"/>
</RelativeLayout>
BlankFragment.java
public class BlankFragment extends Fragment {
private static final String ARG_TEXT = "TEXT";
private Unbinder unbinder;
private String mParam1;
private OnFragmentInteractionListener mListener;
#BindView(R.id.tv_blank_fragment)
TextView tvTitle;
#BindView(R.id.back_btn)
Button backBtn;
#BindView(R.id.next_btn)
Button nextBtn;
private FragmentManager fragmentManager;
public BlankFragment() {
// Required empty public constructor
}
public static BlankFragment newInstance(String param1) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_TEXT, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_TEXT);
}
fragmentManager = getFragmentManager();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_blank, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
unbinder = ButterKnife.bind(this, view);
tvTitle.setText(mParam1);
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String test = "test dari fragment";
sendBack(test);
}
});
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void sendBack(String sendback) {
if (mListener != null) {
mListener.onFragmentInteraction(sendback);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(String text);
}
}
fragment_blank.xml
<?xml version="1.0" encoding="utf-8"?>
<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:background="#cfcf1d"
tools:context=".BlankFragment">
<TextView
android:id="#+id/tv_blank_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
<Button
android:id="#+id/next_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/back_btn"
android:layout_alignParentStart="true"
android:text="Create new Fragment" />
<Button
android:id="#+id/back_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:text="back" />
</RelativeLayout>
Everything went smoothly but the result of my Mainactivity layout still appeared on fragment. Please help me
Result as shows as below:
here 1
here 2
In activity_reading, the fragment container view (dynamic_fragment_frame) is declared first, so the button and the text view will be displayed on top of it. If you move the fragment container to the bottom, the fragments will be displayed correctly, so the layout should look something like this:
<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"
android:background="#00d9ff"
tools:context=".MainActivity">
<TextView
android:id="#+id/title_read_news"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ini Judul"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:layout_gravity="center"
android:paddingBottom="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="openFragment"
android:text="Open"
android:stateListAnimator="#null"/>
<FrameLayout
android:id="#+id/dynamic_fragment_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
<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"
android:background="#00d9ff"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/dynamic_fragment_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="#+id/title_read_news"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ini Judul"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:layout_gravity="center"
android:paddingBottom="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="openFragment"
android:text="Open"
android:stateListAnimator="#null"/>
</RelativeLayout>
With the above layout, Imagine that the TextView and Button are over the FragmeLayout. So when you add a Fragment to the FrameLayout, the TextView and Button are still over the FragmeLayout. To hide these views, you should use TextView.setVisibility(View.GONE) and Button.setVisibility(View.GONE) when adding a Fragment

TabbedActivity randomly shows fragments but is most of the time blank

I created a TabbedActivity with some fragments, these fragments sometimes load and sometimes they dont, i've searched everywhere but couldn't find the issue.
Example gif
This is my main activity:
public class TwitterActivity extends AppCompatActivity implements MessagesFragment.OnFragmentInteractionListener, NotificationFragment.OnFragmentInteractionListener,
ProfileFragment.OnFragmentInteractionListener, TimeLineFragment.OnFragmentInteractionListener {
private static final String APP_TAG = "Twitter";
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(null);
setContentView(R.layout.activity_twitter);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
final TextView toolbarTitle = toolbar.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(3);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
if(position == 0){
toolbarTitle.setText(R.string.tab_timeline);
}else if(position == 1){
toolbarTitle.setText(R.string.tab_messages);
}else if(position == 2){
toolbarTitle.setText(R.string.tab_notifications);
}else if(position == 3){
toolbarTitle.setText(R.string.tab_profile);
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) { }
#Override
public void onTabReselected(TabLayout.Tab tab) { }
});
tabLayout.setupWithViewPager(mViewPager, false);
}
#Override
public void onFragmentInteraction(Uri uri) { }
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Log.d(APP_TAG, String.valueOf(position));
if(position == 0){
return TimeLineFragment.newInstance();
}else if(position == 1){
return MessagesFragment.newInstance();
}else if(position == 2){
return NotificationFragment.newInstance();
}else if(position == 3){
return ProfileFragment.newInstance();
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return getString(R.string.tab_timeline);
case 1:
return getString(R.string.tab_messages);
case 2:
return getString(R.string.tab_notifications);
case 3:
return getString(R.string.tab_profile);
default:
return getString(R.string.tab_timeline);
}
}
}
}
This is one of my fragments (They are all the same):
public class TimeLineFragment extends Fragment {
private OnFragmentInteractionListener mListener;
public TimeLineFragment() {
}
public static TimeLineFragment newInstance() {
TimeLineFragment fragment = new TimeLineFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_time_line, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
This is my main activity's layout file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".activities.TwitterActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#mipmap/ic_launcher"
/>
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="#string/tab_timeline"
android:textSize="18sp"
android:textStyle="bold" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:elevation="80dp"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="56dp"
app:tabGravity="fill"
app:tabIndicatorColor="#android:color/holo_orange_dark"
app:tabIndicatorHeight="0dp"
app:tabMode="fixed">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_above="#+id/tabs"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Please help me
EDIT: removed the useless TabItems.
You may have to use getChildFragmentManager() instead of getSupportFragmentManager() as parameter to create you adapter.

IllegalStatementException on fragment commit

I have the following simple code for testing fragments transactions as I'm relatively new to Android : At first , I just show the first fragment and everything goes fine , but when I want it to be changed after a button is clicked , I get the following error :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.onceuponatime, PID: 3161
java.lang.IllegalStateException: Activity has been destroyed
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1864)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:649)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:609)
at com.example.user.onceuponatime.activity.AuthentificationActivity.onFragmentSwapRequested(AuthentificationActivity.java:63)
at com.example.user.onceuponatime.fragment.SignInFragment$2.onClick(SignInFragment.java:95)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Activity :
public class AuthentificationActivity extends AppCompatActivity implements SignInFragment.SignInFragmentCallBack
,SignUpFragment.SignUpFragmentCallBack{
public static final String SIGNINFRAGMENT_TAG = "signinfragment";
public static final String SIGNUPFRAGMENT_TAG = "signupfragment";
public static final int SIGNIN_FRAGMENT_ID = 846464;
public static final int SIGNUP_FRAGMENT_ID = 125478;
public static final int LOST_PWD_FRAGMENT_ID = 85546;
private FragmentManager mFragmentManager;
private SignInFragment mSignInFragment;
private SignUpFragment mSignUpFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_authentification);
mSignInFragment = SignInFragment.getInstance();
mFragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.add(mSignInFragment,SIGNINFRAGMENT_TAG);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
#Override
public void onFragmentSwapRequested(int FragmentId) {
mFragmentManager = this.getSupportFragmentManager();
FragmentTransaction fgTransaction = mFragmentManager.beginTransaction();
switch(FragmentId) {
case SIGNUP_FRAGMENT_ID:
if(!isFinishing()) {
mSignUpFragment = (SignUpFragment) mFragmentManager.findFragmentByTag(SIGNUPFRAGMENT_TAG);
if (mSignUpFragment == null) {
mSignUpFragment = SignUpFragment.getInstance();
fgTransaction.replace(R.id.fragment_container, mSignUpFragment, SIGNUPFRAGMENT_TAG);
} else {
fgTransaction.show(mSignUpFragment);
}
fgTransaction.addToBackStack(null);
fgTransaction.commit();
}
break;
case LOST_PWD_FRAGMENT_ID:
break;
}
}
}
SignUpFragment :
public class SignUpFragment extends Fragment {
FragmentSignUpBinding signUpBinding;
private EditText mEmailEdit,mPasswordEdit;
private Button btnRegister,btnLogin;
private ProgressBar mProgressBar;
private CoordinatorLayout mCoordinatorLayout;
private FirebaseAuth mAuth;
private SignUpFragmentCallBack mCallBack;
public interface SignUpFragmentCallBack {
void onFragmentSwapRequested(int fragmentId);
}
public SignUpFragment() {
}
public static SignUpFragment getInstance() {
SignUpFragment fragment = new SignUpFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
signUpBinding = DataBindingUtil.setContentView(getActivity(),R.layout.fragment_sign_up);
mEmailEdit = signUpBinding.emailSignup;
mPasswordEdit = signUpBinding.passwordSignup;
btnLogin = signUpBinding.loginRedirectButton;
btnRegister = signUpBinding.registerButton;
mProgressBar = signUpBinding.progressBarSignup;
mCoordinatorLayout = signUpBinding.coordinatorSignup;
mCallBack = new AuthentificationActivity();
mAuth = FirebaseAuth.getInstance();
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mCallBack instanceof SignUpFragmentCallBack)
mCallBack.onFragmentSwapRequested(AuthentificationActivity.SIGNIN_FRAGMENT_ID);
}
});
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onRegisterClicked();
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_sign_up, container, false);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
private void onRegisterClicked() {
String email = mEmailEdit.getText().toString().trim();
final String pwd = mPasswordEdit.getText().toString().trim();
if(TextUtils.isEmpty(email)) {
Snackbar.make(mCoordinatorLayout,getString(R.string.no_email_entered),Snackbar.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(pwd)) {
Snackbar.make(mCoordinatorLayout,getString(R.string.no_password_entered),Snackbar.LENGTH_LONG).show();
return;
}
mProgressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email,pwd).addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
startActivity(new Intent(getActivity(), MainActivity.class));
getActivity().finish();
}
else {
mProgressBar.setVisibility(View.GONE);
Snackbar.make(mCoordinatorLayout,task.getException().toString(),Snackbar.LENGTH_LONG).show();
}
}
});
}
#Override
public void onDetach() {
super.onDetach();
}
}
I have read many posts about similar problems , some are saying wrap the transaction with a if(!isFinished()) , other are saying to override the onDestroy , none of them worked , and I believe the solution is way simpler .
EDIT :
Here are my SignInFragment and Authentification activity xml :
SignInFragment :
public class SignInFragment extends Fragment {
FragmentSignInBinding signInBinding;
private CoordinatorLayout mCoordinatorLayout;
private EditText mEmailEdit,mPasswordEdit;
private Button btnSignIn,btnSignUp,btnLostPwd;
private ProgressBar mProgressBar;
private FirebaseAuth mAuth;
private SignInFragmentCallBack mCallBack;
public interface SignInFragmentCallBack {
void onFragmentSwapRequested(int FragmentId);
}
public SignInFragment() {}
public static SignInFragment getInstance() {
return new SignInFragment();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mCallBack = (SignInFragmentCallBack) context;
} catch(ClassCastException e) {
throw new ClassCastException(context.toString() + " must implements SignInCallaback");
}
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
signInBinding = DataBindingUtil.setContentView(getActivity(),R.layout.fragment_sign_in);
mEmailEdit = signInBinding.emailSignin;
mPasswordEdit = signInBinding.passwordSignin;
mProgressBar = signInBinding.progressBarSignIn;
btnSignIn = signInBinding.signInButton;
btnSignUp = signInBinding.signUpButton;
btnLostPwd = signInBinding.passwordReset;
mCoordinatorLayout = signInBinding.coordinatorSignin;
mAuth = FirebaseAuth.getInstance();
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signInAction();
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mCallBack instanceof SignInFragmentCallBack)
mCallBack.onFragmentSwapRequested(AuthentificationActivity.SIGNUP_FRAGMENT_ID);
}
});
btnLostPwd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mCallBack instanceof SignInFragmentCallBack)
mCallBack.onFragmentSwapRequested(AuthentificationActivity.LOST_PWD_FRAGMENT_ID);
}
});
}
private void signInAction() {
String email = mEmailEdit.getText().toString().trim();
final String password = mPasswordEdit.getText().toString().trim();
if(TextUtils.isEmpty(email)) {
Snackbar.make(mCoordinatorLayout,getString(R.string.no_email_entered),Snackbar.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(password)) {
Snackbar.make(mCoordinatorLayout,getString(R.string.no_password_entered),Snackbar.LENGTH_LONG).show();
return;
}
mProgressBar.setVisibility(View.VISIBLE);
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
mProgressBar.setVisibility(View.GONE);
if(task.isSuccessful()) {
Snackbar.make(mCoordinatorLayout,getString(R.string.login_success),Snackbar.LENGTH_LONG).show();
startActivity(new Intent(getActivity(), MainActivity.class));
getActivity().finish();
}
else
{
Snackbar.make(mCoordinatorLayout,getString(R.string.login_failed),Snackbar.LENGTH_LONG).show();
}
}
});
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_sign_in,container,false);
}
#Override
public void onResume() {
super.onResume();
mProgressBar.setVisibility(View.GONE);
}
}
Authentification 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:id="#+id/activity_authentification"
android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="com.example.user.onceuponatime.activity.AuthentificationActivity">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/fragment_container">
</FrameLayout>
</LinearLayout>
EDIT2 : New stack trace :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.onceuponatime, PID: 8674
java.lang.IllegalArgumentException: No view found for id 0x7f0d007f (com.example.user.onceuponatime:id/fragment_container) for fragment SignUpFragment{2b0b994 #1 id=0x7f0d007f signupfragment}
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1293)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:757)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2355)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2146)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2098)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2008)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
SignInFragment xml :
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" >
<android.support.design.widget.CoordinatorLayout
android:id="#+id/coordinator_signin"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.user.onceuponatime.fragment.SignInFragment">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical"
android:background="#color/colorPrimaryDark"
android:padding="#dimen/activity_horizontal_margin"
>
<ImageView
android:layout_width="#dimen/logo_wh"
android:layout_height="#dimen/logo_wh"
android:src="#mipmap/ic_launcher"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="30dp"/>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/email_signin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/email_input"
android:textColor="#android:color/white"
android:maxLines="1"
android:inputType="textEmailAddress"
/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="1"
android:id="#+id/password_signin"
android:inputType="textPassword"
android:imeActionId="#+id/login"
android:imeOptions="actionUnspecified"
android:textColor="#android:color/white"
android:focusableInTouchMode="true"
android:hint="#string/password_input"
/>
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/sign_in_button"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="#color/colorAccent"
android:text="#string/short_signin"
android:textColor="#android:color/black"
android:textStyle="bold"
android:textAlignment="center"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/sign_up_button"
android:background="#null"
android:layout_marginTop="20dp"
android:textAllCaps="false"
android:textColor="#color/colorAccent"
android:text="#string/link_register"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/password_reset"
android:background="#null"
android:layout_marginTop="20dp"
android:textAllCaps="false"
android:text="#string/lost_password"
android:textColor="#android:color/white"
android:textSize="15dp"
/>
</LinearLayout>
<ProgressBar
android:id="#+id/progressBarSignIn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center|bottom"
android:layout_marginBottom="20dp"
android:visibility="gone" />
</android.support.design.widget.CoordinatorLayout>
</layout>
This would be the problem:
mCallBack = new AuthentificationActivity();
You cannot instantiate an Activity with new and have it work correctly. Furthermore, that new instance wouldn't be the current hosting instance anyway.
Instead, you want to cast the current hosting Activity instance to your interface. Since you're using support Fragments, you can use either getActivity() or getContext() to retrieve that instance, as both will return the same object with an Activity host. For example:
mCallBack = (SignUpFragmentCallBack) getContext();
This should be sufficient to at least test with your current setup. A cleaner implementation, however, might be to perform this cast in onAttach() with a try-catch for ClassCastException, where we can throw a more informative Exception if it should fail.
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mCallBack = (SignUpFragmentCallBack) context;
}
catch (ClassCastException e) {
throw new ClassCastException(context.toString() +
" must implement the SignUpFragmentCallBack interface");
}
}

OnListItemClick event is not working when I use checkbox in list_item.xml

My code is working fine, but when I use checkbox in my list_item.xml, the OnListItemClick and the startActivity(intent) don't work. I want to use checkbox to select multiple apps, and do some action using button like some toast or something.
My MainActivity.java:
public class MainActivity extends ListActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private AppAdapter listadapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
packageManager = getPackageManager();
new LoadApplications().execute();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ApplicationInfo app = applist.get(position);
try{
Intent intent = packageManager.getLaunchIntentForPackage(app.packageName);
if(intent != null) {
startActivity(intent);
}
} catch(ActivityNotFoundException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
} catch(Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> appList = new ArrayList<ApplicationInfo>();
for(ApplicationInfo info : list) {
try{
if(packageManager.getLaunchIntentForPackage(info.packageName) != null) {
appList.add(info);
}
} catch(Exception e) {
e.printStackTrace();
}
}
return appList;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadapter = new AppAdapter(MainActivity.this, R.layout.list_item, applist);
return null;
}
}
Adapter.java
public class AppAdapter extends ArrayAdapter<ApplicationInfo>{
private List<ApplicationInfo> appList = null;
private Context context;
private PackageManager packageManager;
public AppAdapter(Context context, int resource,
List<ApplicationInfo> objects) {
super(context, resource, objects);
this.context = context;
this.appList = objects;
packageManager = context.getPackageManager();
}
#Override
public int getCount() {
return ((null != appList) ? appList.size() : 0);
}
#Override
public ApplicationInfo getItem(int position) {
return ((null != appList) ? appList.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(null == view) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.list_item, null);
}
ApplicationInfo data = appList.get(position);
if(null != data) {
TextView appName = (TextView) view.findViewById(R.id.app_name);
TextView packageName = (TextView) view.findViewById(R.id.app_package);
ImageView iconView = (ImageView) view.findViewById(R.id.app_icon);
appName.setText(data.loadLabel(packageManager));
packageName.setText(data.packageName);
iconView.setImageDrawable(data.loadIcon(packageManager));
}
return view;
}
}
list_item.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="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="#+id/app_icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="3dp"
android:scaleType="centerCrop"
android:contentDescription="#null" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center|center_vertical"
android:orientation="vertical"
android:paddingLeft="5dp"
android:layout_weight="1">
<TextView
android:id="#+id/app_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textStyle="bold" />
<TextView
android:id="#+id/app_package"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<CheckBox
android:id="#+id/checkBox"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_gravity="right"
android:gravity="end|right" />
</LinearLayout>
</LinearLayout>
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:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>

How to go one Fragment to another when I will click on TextView Id?

How to go one Fragment to another when I will click on TextView Id?
Error shows:
java.lang.ClassCastException: com.example.tripigator.Overview cannot be cast to android.app.Activity.
and error comes from these lines :
TextView overview = (TextView) findViewById(R.id.txt_overview);
overview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProjectOverview.this, Overview.class);
startActivity(intent);
}
});
So please anybody help me how to move from one fragment to another by clicking text item.
ProjectOverview class :
public class ProjectOverview extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project_overview);
initialingpaging();
TextView overview = (TextView) findViewById(R.id.txt_overview);
overview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProjectOverview.this, Overview.class);
startActivity(intent);
}
});
}
private void initialingpaging() {
// TODO Auto-generated method stub
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Overview.class.getName()));
fragments.add(Fragment.instantiate(this, Highlight.class.getName()));
mPageAdapter = new PageAdapter(this.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
pager.setAdapter(mPageAdapter);
}
}
Two Fragment Classes:
public class Overview extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState)
{
if(container == null)
{
return null;
}
return (LinearLayout) inflater.inflate(R.layout.overview,container,false);
}
}
public class Highlight extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
if(container == null)
{
return null;
}
return (LinearLayout) inflater.inflate(R.layout.highlight,container,false);
}
}
Layout Interface:
<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" >
<LinearLayout
android:id="#+id/project_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="65dp"
android:gravity="center" >
<TextView
android:id="#+id/txt_overview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:layout_marginLeft="12dp"
android:text="Overview" />
<TextView
android:id="#+id/txt_highlite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:layout_marginLeft="12dp"
android:text="Highlight" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
You can't initiate the fragment using Intent.Try this it helps.
Fragment fragment = null;
FragmentManager frgManager;
FragmentTransaction ft;
fragment = new Overview();
ft = frgManager.beginTransaction();
ft.replace(R.id.frame_content, fragment);
ft.addToBackStack(null);
ft.commitAllowingStateLoss();
If you use View-Pager
your_ViewPager.setCurrentItem(position)
you should not use intent in fragment to move another fragment
and check this for whole example http://examples.javacodegeeks.com/android/core/app/fragment/android-fragments-example/
use this.
((yourfragmentActivity) getActivity()).setCurrentItem(1,//desired activity 0=first 1= second and so on
true);
insted
Intent intent = new Intent(ProjectOverview.this, Overview.class);
startActivity(intent);

Categories

Resources