in an application , I wish I would pass a string fragment and display it in a toast.
The problem is with my code, the creation of the fragment I have a toast that appears, but empty ...
I do not understand where did my problem ( it's the first time I try to do that )
My code :
MainActivity :
public class MainActivity extends ActionBarActivity
implements NavigationDrawerCallbacks {
private NavigationDrawerFragment mNavigationDrawerFragment;
private Toolbar mToolbar;
private CharSequence mUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.fragment_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
Intent intent = new Intent(MainActivity.this, fragment_test.class);
intent.putExtra("message", "test");
objFragment = new fragment_test();
break;
case 1:
objFragment = new menu2_Fragment();
break;
case 2:
objFragment = new menu3_Fragment();
break;
case 3:
objFragment = new menu4_Fragment();
break;
case 4:
objFragment = new menu5_Fragment();
break;
case 5:
objFragment = new menu6_Fragment();
break;
case 6:
objFragment = new menu8_Fragment();
break;
case 7:
objFragment = new menu9_Fragment();
break;
case 8:
objFragment = new menu7_Fragment();
break;
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
#Override
public void onBackPressed() {
if (mNavigationDrawerFragment.isDrawerOpen())
mNavigationDrawerFragment.closeDrawer();
else
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
/*#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}*/}
Fragment_test :
public class fragment_test extends Fragment {
View rootview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rootview = inflater.inflate(R.layout.xml1, container, false);
Intent intent = getActivity().getIntent();
String message = intent.getStringExtra("message");
Toast toast = Toast.makeText(getActivity(), message, Toast.LENGTH_LONG);
toast.show();
return rootview;
}}
thx in advance
ps : sorry for my english french
Your code
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, objFragment).commit();
Replace with
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, objFragment).commit();
Bundle bundle = new Bundle();
bundle.putString(key, value);
objFragment.setArguments(bundle);
Write below code in your another activity
if (getArguments() != null)
{
m_searchText = getArguments().getString(Key);
}
Related
Below is the code for my adapter
DashboardAdapter.java
public class DashboardAdapter extends RecyclerView.Adapter<DashboardAdapter.DashviewHolder> {
ArrayList<DashModel> dashHolder;
private LayoutInflater layoutInflater;
public DashboardAdapter(ArrayList<DashModel> dashHolder) {
this.dashHolder = dashHolder;
}
#NonNull
#Override
public DashviewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.dash_layout, parent, false);
return new DashviewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull DashviewHolder holder, int position) {
holder.dashImg.setImageResource(dashHolder.get(position).getImage());
holder.header.setText(dashHolder.get(position).getHeader());
holder.desc.setText(dashHolder.get(position).getDesc());
}
#Override
public int getItemCount() {
return dashHolder.size();
}
class DashviewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView dashImg;
TextView header, desc;
public DashviewHolder(#NonNull View itemView) {
super(itemView);
dashImg = itemView.findViewById(R.id.dash_slide_img);
header = itemView.findViewById(R.id.dash_slide_txt1);
desc = itemView.findViewById(R.id.dash_slide_txt2);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final Fragment fm;
switch (getLayoutPosition()) {
case 0:
fm = new SavingsFragment();
break;
case 1:
fm = new TargetFragment();
break;
case 2:
fm = new InvestFragment();
break;
}
}
}
}
DashboardFragment.java
public class DashboardFragment extends Fragment {
private RecyclerView recyclerView;
ArrayList<DashModel> dashDataHolder;
private View view;
private DashboardAdapter dashboardAdapter;
private FragmentManager fm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_dashboard, container, false);
recyclerView = view.findViewById(R.id.dash_slider_layout);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
dashDataHolder = new ArrayList<>();
DashModel ob1 = new DashModel(R.drawable.ic_savings, R.string.first_slide_dash, R.string.first_slide_dash_amt);
dashDataHolder.add(ob1);
DashModel ob2 = new DashModel(R.drawable.ic_savings, R.string.second_slide_dash, R.string.second_slide_dash_amt);
dashDataHolder.add(ob2);
DashModel ob3 = new DashModel(R.drawable.ic_savings, R.string.third_slide_dash, R.string.third_slide_dash_amt);
dashDataHolder.add(ob3);
recyclerView.setAdapter(new DashboardAdapter(dashDataHolder));
//fm.getFragmentManager().beginTransaction().replace(R.id.fragment_container,getTargetFragment(),"New Fragment").commit();
return view;
}
}
Then the code for my main activity that has both drawer and bottom navigation
public class RetailerDashboard extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = RetailerDashboard.class.getSimpleName();
ChipNavigationBar chipNavigationBar;
DrawerLayout drawerLayout;
Toolbar toolbar;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retailer_dashboard);
/*--------------------HOOKS----------------------*/
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
toolbar = findViewById(R.id.toolbar);
chipNavigationBar = findViewById(R.id.bottom_bar);
/*--------------------BOTTOM MENU----------------------*/
chipNavigationBar.setItemSelected(R.id.menu_home, true);
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new DashboardFragment()).commit();
bottomMenu();
/*--------------------TOOLBAR----------------------*/
setSupportActionBar(toolbar);
/*--------------------NAVIGATION DRAWER MENU----------------------*/
navigationView.bringToFront();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,
drawerLayout,
toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
private void bottomMenu() {
chipNavigationBar.setOnItemSelectedListener(new ChipNavigationBar.OnItemSelectedListener() {
#Override
public void onItemSelected(int id) {
Fragment fragment = null;
switch (id) {
case R.id.menu_saving:
fragment = new SavingsFragment();
break;
case R.id.menu_home:
fragment = new DashboardFragment();
break;
case R.id.menu_target:
fragment = new TargetFragment();
break;
}
if (fragment != null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment).commit();
} else {
Log.e(TAG, "Error in creating fragment");
}
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_profile:
Intent accountIntent = new Intent(RetailerDashboard.this, Profile.class);
startActivity(accountIntent);
break;
case R.id.nav_account_balnce:
Intent balanceIntent = new Intent(RetailerDashboard.this, AccountBalance.class);
startActivity(balanceIntent);
break;
case R.id.nav_notifications:
Intent notifIntent = new Intent(RetailerDashboard.this, Notifications.class);
startActivity(notifIntent);
break;
case R.id.nav_settings:
Intent settingsIntent = new Intent(RetailerDashboard.this, Settings.class);
startActivity(settingsIntent);
break;
case R.id.nav_chat:
Intent chatIntent = new Intent(RetailerDashboard.this, Chat.class);
startActivity(chatIntent);
break;
case R.id.nav_faq:
Intent helpIntent = new Intent(RetailerDashboard.this, FAQ.class);
startActivity(helpIntent);
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
finishAffinity();
}
}
}
I'm trying to load all the fragments on the app start and they will never be reloaded even when the user navigates to different pages. Is it possible? The following is my MainActivity.java file.
Any help would be really appreciated.
public class MainActivity extends AppCompatActivity {
private WebView mywebView;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
//I added this if statement to keep the selected fragment when rotating the device
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()){
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_inbox:
selectedFragment = new InboxFragment();
break;
case R.id.nav_orders:
selectedFragment = new OrdersFragment();
break;
case R.id.nav_notifications:
selectedFragment = new NotificationsFragment();
break;
case R.id.nav_account:
selectedFragment = new MyaccountFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
}
EDIT:
This is one of my fragment: NotifcationFragment. Other fragments are almost similar to this one.
public class NotificationsFragment extends Fragment {
String ShowOrHideWebViewInitialUse = "show";
private WebView myWebView ;
private ProgressBar spinner;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_notifications,container,false);
myWebView = myView.findViewById(R.id.WebView3);
spinner = myView.findViewById(R.id.progressBar3);
myWebView.loadUrl("example.com/notifications");
myWebView.setWebViewClient(new CustomWebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return false;
}
}
);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
return myView;
}
// This allows for a splash screen
// (and hide elements once the page loads)
private class CustomWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView webview, String url, Bitmap favicon) {
// only make it invisible the FIRST time the app is run
if (ShowOrHideWebViewInitialUse.equals("show")) {
webview.setVisibility(myWebView.INVISIBLE);
}
}
#Override
public void onPageFinished(WebView view, String url) {
ShowOrHideWebViewInitialUse = "hide";
spinner.setVisibility(View.GONE);
view.setVisibility(myWebView.VISIBLE);
super.onPageFinished(view, url);
view.loadUrl("javascript:(function() { " +
"var foot = document.getElementsByClassName('footer-wrapper')[0].style.display='none'; " +
"var arrow = document.getElementsByClassName('scroll-to-top-wrapper')[0].style.display='none'; " +
"var head = document.getElementsByClassName('new-menu responsive')[0].style.display='none'; " +
"})()");
}
}
}
The way you have implemented when the user switch between the navigation bar tabs it always create new fragments. Then it should be refresh. If you don't want to refresh each time user navigate between tabs you need to change the code as follows:
Define Fragments creation at the top in the class
Eg :
private HomeFragment homeFragment = new HomeFragment(); (do for other fragments also)
Then in navigation view listener do as
> case R.id.nav_home:
> selectedFragment = homeFragment;
> break;
do for other fragments too
public class MainActivity extends AppCompatActivity {
private WebView mywebView;
private HomeFragment homeFragment = new HomeFragment();
private InboxFragment inboxFragment = new InboxFragment();
private OrdersFragment ordersFragment = new OrdersFragment();
private NotificationsFragment notificationsFragment = new NotificationsFragment();
private MyaccountFragment myAccountFragment = new MyaccountFragment();
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
//I added this if statement to keep the selected fragment when rotating the device
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()){
case R.id.nav_home:
selectedFragment = homeFragment;
break;
case R.id.nav_inbox:
selectedFragment = inboxFragment;
break;
case R.id.nav_orders:
selectedFragment = ordersFragment;
break;
case R.id.nav_notifications:
selectedFragment = notificationsFragment;
break;
case R.id.nav_account:
selectedFragment = myAccountFragment;
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
}
public class HomeFragment extends Fragment {
BottomNavigationView bottomNavigationView;
FragmentManager manager = getFragmentManager() ;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home,container,false);
}
#Override
public void onStart() {
super.onStart();
bottomNavigationView = bottomNavigationView.findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener=
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()){
case R.id.nav_home1 :
selectedFragment = new Home1Fragment();
break;
case R.id.nav_favourites :
selectedFragment = new FavouriteFragment();
break;
case R.id.nav_search:
selectedFragment = new SearchFragment();
break;
}
manager.beginTransaction().replace(R.id.fragment_container,selectedFragment).commit();
return true;
}
};
}
No error shown but the fragment isn't opening
add container framelayout to your parent fragment then on every click set fragment using this :
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.parent_fragment_container, new ParentFragment());
ft.commit();
your code will look like :
public class HomeFragment extends Fragment {
BottomNavigationView bottomNavigationView;
FragmentManager manager = getFragmentManager() ;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home,container,false);
}
private void setFragment(Fragment fragment){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.parent_fragment_container,fragment);
ft.commit();
}
#Override
public void onStart() {
super.onStart();
bottomNavigationView = bottomNavigationView.findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener=
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()){
case R.id.nav_home1 :
selectedFragment = new Home1Fragment();
setFragment(selectedFragment);
break;
case R.id.nav_favourites :
selectedFragment = new FavouriteFragment();
break;
case R.id.nav_search:
selectedFragment = new SearchFragment();
break;
}
manager.beginTransaction().replace(R.id.fragment_container,selectedFragment).commit();
return true;
}
};
}
I'm trying to get view from Fragment dynamically added to Activity.
MainActivity.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
myDrawerList.setOnItemClickListener(new DrawerItemClickListener());
handleIntent(getIntent());
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(
AdapterView<?> parent, View view, int position, long id
) {
// display view for selected nav drawer item
displayView(position);
}
}
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
String userToken = UserTokenStorageFactory.instance().getStorage().get();
switch (position) {
case 0:
fragment = new AllCategories();
break;
case 1:
fragment = new Subscription();
break;
case 2:
if( userToken != null && !userToken.equals( "" ) ){
Intent myIntent1 = new Intent(this, PrivateOffice.class);
this.startActivity(myIntent1);
break;
}
else {
Intent myIntent1 = new Intent(this, LogIn.class);
this.startActivity(myIntent1);
break;
}
case 3:
if( userToken != null && !userToken.equals( "" ) ){
Intent myIntent1 = new Intent(this, Create_action.class);
this.startActivity(myIntent1);
break;
}
else {
Intent myIntent1 = new Intent(this, LogIn.class);
this.startActivity(myIntent1);
break;
}
case 4:
AlertDialog dialog = onCreateDialog(DIALOG_CHOOSE_CATEGORY);
dialog.show();
break;
default:
break;
}
if (fragment != null) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fTrans = fragmentManager.beginTransaction();
fTrans.replace(R.id.content_frame, fragment);
fTrans.commit();
// update selected item and title, then close the drawer
myDrawerList.setItemChecked(position, true);
myDrawerList.setSelection(position);
setTitle(viewsNames[position]);
myDrawerLayout.closeDrawer(mDrawer);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
I need to get view (LinearLayout listv) from layout of AllCategories.java. I tried using getView() with findViewById, but it returns NullPointerException. What shall I do?
I m using drawer list for my android application.
Got a issue.
When I click randomly (very fast) then I get forcestop and java.lang.IllegalStateException: Content view not yet created showing in Log.
I m using fragments
I m also getting the following Runtime error
at android.support.v4.app.ListFragment.ensureList(ListFragment.java:32
Here is a part of my code in selecting from drawer list and
Fragment home = new Home();
Fragment feeds = new Feeds_ListView();
.....
private void selectItem(int position)
{
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
switch (position)
{
case 0:
setTitle(title[position]);
ft.replace(R.id.content_frame, feeds);
break;
case 1:
setTitle(title[position]);
ft.replace(R.id.content_frame, NewPostFragment);
break;
case 2:
setTitle(title[position]);
ft.replace(R.id.content_frame, SearchDetailsFragment);
break;
case 3:
setTitle(title[position]);
ft.replace(R.id.content_frame, feeds1);
break;
case 4:
setTitle(title[position]);
ft.replace(R.id.content_frame, UserDetailsFragment);
break;
case 5:
setTitle(title[position]);
ft.replace(R.id.content_frame, FBActivity);
break;
}
ft.commit();
mDrawerList.setItemChecked(position, true);
setTitle(title[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
Here is the part of Feeds_ListView();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
context=container.getContext();
rootView = inflater.inflate(R.layout.feeds_listview_layout, container, false);
list = (ListView) rootView.findViewById(android.R.id.list);
mRelativeLayout=rootView.findViewById(R.id.mRelativeLayout);
saveProgress =(ProgressBar) rootView.findViewById(R.id.loadpost);
saveProgress.setVisibility(View.INVISIBLE);
userAdapter = new CustomListAdapter(getActivity(), R.layout.feeds_listview_item,userArray);
mRelativeLayout.setVisibility(View.GONE);
list.setItemsCanFocus(false);
list.setAdapter(userAdapter);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
SharedPreferences settings =getActivity().getSharedPreferences("newdatabase",0);
String user_id=settings.getString("user_id", "--");
if(user_id.equals("--") || user_id.equals(""))
{ FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, FBActivity);
ft.commit();
}else{
new Onscrollasync().execute();
((PullToRefresh_Master) getListView()).setOnRefreshListener(new OnRefreshListener()
{
#Override
public void onRefresh()
{
new Onscrollasync().execute();
}
});
}
}
The problem is with the code in the Fragment Home that you wrote in the onCreateView. Move the code in your onCreateView() to either onActivityCreated() or onViewCreated(). There are several similar question on StackOverlfow like here.
Try this instead of inflating a container,try to inflate your view without the container ie
rootView = inflater.inflate(R.layout.feeds_listview_layout,null);
Let me know if this works.