i have fragment for display the NavigationDrawer. In that i have the first section the header with some information. This information change and with EventBus i control this event, but how can update this fragment?
The implementation below work only if i rotate the device.
extract from MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity);
mNavigationNavDrawerFragment = (Nav_DrawerFragment) getFragmentManager().findFragmentById(R.id.fragment_drawer);
mNavigationNavDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
inizialized(mServices);
}
....
....
EventBus.getDefault().postSticky(new PersonDetails(mNomeCognome, mEmail));
//HERE HOW CAN REFRESH OR RECREATE THIS mNavigationNavDrawerFragment?
}
Extract from Nav_DrawerFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mDrawerList.setLayoutManager(layoutManager);
mDrawerList.setHasFixedSize(true);
final List<NavigationItem> navigationItems = getMenu();
//HERE I SET THE UPDATE DATA
Nav_adapter adapter = new Nav_adapter(navigationItems,mNomeCognome,mEmail);
adapter.setNavigationDrawerCallbacks(this);
mDrawerList.setAdapter(adapter);
selectItem(mCurrentSelectedPosition,items);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().registerSticky(this);
}
public void onEventMainThread(PersonDetails event){
mNomeCognome = event.mNomeCognome;
mEmail = event.mEmail;
}
public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) return;
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) return;
getActivity().invalidateOptionsMenu();
}
};
I can see you're using a RecyclerView with the adapter
Nav_adapter adapter = new Nav_adapter(navigationItems,mNomeCognome,mEmail);
and then you're updating the values that were used to create the adapter on the event
mNomeCognome = event.mNomeCognome;
mEmail = event.mEmail;
the problem is that you didn't pass those values to the adapter.
So you'll have to create a way to pass those updated values to the existing adapter, something like this:
// first define your adapter as a field:
Nav_adapter adapter;
// then on your event
public void onEventMainThread(PersonDetails event){
mNomeCognome = event.mNomeCognome;
mEmail = event.mEmail;
adapter.setNewValues(mNomeCognome, mEmail);
}
then inside this setNewValues you update the adapter values and don't forget to call one of the notifyItemChanged or notifyItemRangeChanged method on the adapter so that the new value can be updated on the screen.
Related
Error msg :
( - Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference)
The app crashes while accessing this RecyclerView :
if (!type.equals("Admin"))
{
userNameTextView.setText(Prevalent.currentOnlineUser.getName());
Picasso.get().load(Prevalent.currentOnlineUser.getImage()).placeholder(R.drawable.profile).into(profileImageView);
}
recyclerView = (RecyclerView) findViewById(R.id.recycler_menu);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
}
and this is the RecyclerView :
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_menu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"/>
The Java Class :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
recyclerView = (RecyclerView) findViewById(R.id.recycler_menu) ;
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null)
{
type = getIntent().getExtras().get("Admin").toString();
}
ProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
Paper.init(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Home");
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
if (!type.equals("Admin"))
{
Intent intent = new Intent(HomeActivity.this, CartActivity.class);
startActivity(intent);
}
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
TextView userNameTextView = headerView.findViewById(R.id.user_profile_name);
CircleImageView profileImageView = headerView.findViewById(R.id.user_profile_image);
if (!type.equals("Admin"))
{
userNameTextView.setText(Prevalent.currentOnlineUser.getName());
Picasso.get().load(Prevalent.currentOnlineUser.getImage()).placeholder(R.drawable.profile).into(profileImageView);
}
recyclerView = (RecyclerView) findViewById(R.id.recycler_menu);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
}
#Override
protected void onStart()
{
super.onStart();
FirebaseRecyclerOptions<Products> options =
new FirebaseRecyclerOptions.Builder<Products>()
.setQuery(ProductsRef, Products.class)
.build();
FirebaseRecyclerAdapter<Products, ProductViewHolder> adapter =
new FirebaseRecyclerAdapter<Products, ProductViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ProductViewHolder holder, int position, #NonNull final Products model)
{
holder.txtProductName.setText(model.getPname());
holder.txtProductDescription.setText(model.getDescription());
holder.txtProductPrice.setText("Price = " + model.getPrice() + "$");
Picasso.get().load(model.getImage()).into(holder.imageView);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
if (type.equals("Admin"))
{
Intent intent = new Intent(HomeActivity.this, AdminMaintainProductsActivity.class);
intent.putExtra("pid", model.getPid());
startActivity(intent);
}
else
{
Intent intent = new Intent(HomeActivity.this, ProductDetailsActivity.class);
intent.putExtra("pid", model.getPid());
startActivity(intent);
}
}
});
}
#NonNull
#Override
public ProductViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_items_layout, parent, false);
ProductViewHolder holder = new ProductViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
I can see that your code has no problem. So I think you are putting the wrong layout in setContentView()
OR if this is not the case, just make sure that there is really a RecyclerView with the specified id in your layout.
If you are sure, just invalidate cache & restart and build again
I am making an online food ordering app.My app was running good but when i add cart code it is showing abnormal behaviour like the cart button takes me to first screen i started.following is the cart.java code
public class Cart extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference requests;
TextView txtTotalPrice;
FButton btnPlace;
List<Order> cart=new ArrayList<>();
CartAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
//Firebase
database = FirebaseDatabase.getInstance();
requests = database.getReference("Requests");
//Init
recyclerView = (RecyclerView) findViewById(R.id.listCart);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
txtTotalPrice = (TextView) findViewById(R.id.total);
btnPlace =(FButton)findViewById(R.id.btnPlaceOrder);
btnPlace.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
showAlertDialog();
}
});
loadlistfood();
}
private void showAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Cart.this);
alertDialog.setTitle("One more step!");
alertDialog.setMessage("Enter your Address: ");
final EditText edtAddress = new EditText(Cart.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
);
edtAddress.setLayoutParams(lp);
alertDialog.setView(edtAddress);//add edt text to alert box
alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Request request = new Request(
Common.currentUser.getPhone(),
Common.currentUser.getName(),
edtAddress.getText().toString(),
txtTotalPrice.getText().toString(),
cart
);
//submit to firebase
//we will use system.currntMill to key
requests.child(String.valueOf(System.currentTimeMillis()))
.setValue(request);
//Delete cart
new Database(getBaseContext()).cleanCart();
Toast.makeText(Cart.this, "Thank you,Order placed", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
private void loadlistfood() {
cart=new Database(this).getCarts();
adapter=new CartAdapter(cart,this);
recyclerView.setAdapter(adapter);
//calculate price
int total=0;
for(Order order:cart)
total+=(Integer.parseInt(order.getPrice()))*(Integer.parseInt(order.getQuantity()));
Locale locale=new Locale("en","US");
NumberFormat fmt=NumberFormat.getCurrencyInstance(locale);
txtTotalPrice.setText(fmt.format(total));
}
Rest i had put a intent in where cart button is put and else i have cartAdapter class and request.java.If you need them i will edit the question.Please help me.
Here is code that take me to cart.java.
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
FirebaseDatabase database;
DatabaseReference category;
TextView txtFullName;
RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;
FirebaseRecyclerAdapter<Category,MenuViewHolder> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Menu");
setSupportActionBar(toolbar);
//init firebase
database = FirebaseDatabase.getInstance();
category = database.getReference("Category");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cartIntent = new Intent(getApplicationContext(),Cart.class);
startActivity(cartIntent);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//set name for user
View headerView = navigationView.getHeaderView(0);
txtFullName = (TextView)headerView.findViewById(R.id.txtFullName);
txtFullName.setText(Common.currentUser.getName());
//Load menu
recycler_menu=(RecyclerView)findViewById(R.id.recycler_meu);
recycler_menu.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycler_menu.setLayoutManager(layoutManager);
loadMenu();
}
private void loadMenu() {
adapter=new FirebaseRecyclerAdapter<Category, MenuViewHolder>(Category.class,R.layout.menu_item,MenuViewHolder.class,category) {
#Override
protected void populateViewHolder(MenuViewHolder viewHolder, Category model, int position) {
viewHolder.txtMenuName.setText(model.getName());
Picasso.with(getBaseContext()).load(model.getImage())
.into(viewHolder.imageView);
final Category clickItem = model;
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
//Get category id and send to new Activity
Intent foodList=new Intent(Home.this,FoodList.class);
foodList.putExtra("CategoryId",adapter.getRef(position).getKey());
startActivity(foodList);
}
});
}
};
recycler_menu.setAdapter(adapter);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_menu) {
// Handle the camera action
} else if (id == R.id.nav_cart) {
// Intent cartIntent = new Intent(Home.this,Cart.class);startActivity(cartIntent);
} else if (id == R.id.nav_orders) {
} else if (id == R.id.log_out) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Thank you in advance
This is kind of hard to explain so I took screenshots of my problem.
So this is my MainActivity.java
I open the navigation drawer and click on Milestones which will bring me to Milestones.java
Here I am at Milestones.java fragment...
working fine for now...
Just how I want it to look.
But when we leave Milestones and go anywhere else and come back it will be messed up. So I will go to Kick Counter.
Here I am in my KickCounter.java fragment
Open navigation drawer and going back to Milestones...
So right now I have fragment Months0Through6 open with Milestones fragment. Some times Months0Through6 and Month12Plus fragments does not show up right away after coming back some times it does. What is always messed up at this point is the Months6Through12 fragment will never display again unless you restart the app. Also swapping between the three fragments is laggy after coming back but never on first view.
Here it is. Where did it go?
youtube video: https://www.youtube.com/watch?v=6yMYcluvqbs
Get Source Here: https://github.com/delaroy/RecyclerViewFragment
I got my code from this youtube video which is almost exactly identical but his MainActivity (which I made into my Milestones fragment) is an activity whereas I used a fragment so I was thinking that might have something to do with my problem.
Milestones.java
public class Milestones extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Milestones() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Milestones.
*/
// TODO: Rename and change types and number of parameters
public static Milestones newInstance(String param1, String param2) {
Milestones fragment = new Milestones();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_milestones, container, false);
Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
ViewPager viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
//dont know if this will work
PagerAdapter pagerAdapter = new PagerAdapter(getFragmentManager(), getContext());
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout) rootView.findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
for(int i = 0; i < tabLayout.getTabCount(); i++){
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
// Inflate the layout for this fragment
return rootView;
}
// not boiler plate
#Override
public void onResume() {
super.onResume();
}
// probably just adding extra menu dont need it
/*#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
*/
//not boilerplate
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == R.id.action_settings){
return true;
}
return super.onOptionsItemSelected(item);
}
//not boilerplate
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[]{"0-6 Months", "6-12 Months", "12+ Months"};
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Months0Through6();
case 1:
return new Months6Through12();
case 2:
return new Months12Plus();
}
return null;
}
#Override
public CharSequence getPageTitle(int position){
return tabTitles[position];
}
public View getTabView(int position){
View tab = LayoutInflater.from(getContext()).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
// TODO: Rename method, update argument and hook method into UI event
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;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
MilestonesAdapter.java
public class MilestonesAdapter extends RecyclerView.Adapter<MilestonesAdapter.MyViewHolder> {
private String[] mDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView mTextView;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_text);
}
}
public MilestonesAdapter(String[] myDataset){
mDataset = myDataset;
}
#Override
public MilestonesAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
holder.mTextView.setText(mDataset[position]);
}
#Override
public int getItemCount() { return mDataset.length; }
Just posting Months0Through6.java because the other two are exactly the same just different strings.
public class Months0Through6 extends android.support.v4.app.Fragment {
public Months0Through6() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
MilestonesAdapter adapter = new MilestonesAdapter(new String[]{"Month 0 stuff", "Example Two", "Example Three", "Example Four", "Example Five" , "Example Six" , "Example Seven"});
rv.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
return rootView;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity
implements KickCounter.OnFragmentInteractionListener, MommyMetrics.OnFragmentInteractionListener, Milestones.OnFragmentInteractionListener, NavigationView.OnNavigationItemSelectedListener {
Intent shareIntent;
String sharetext = "Hey check out mommy-info here at http://www.mommy-info.com";
private WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Connects to www.mommy-info.com
myWebView = (WebView)findViewById(R.id.webView_ID);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.mommy-info.com");
myWebView.setWebViewClient(new WebViewClient());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
//back button in navigation drawer logic
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
//back button in webView logic
else if(myWebView.canGoBack()){
myWebView.goBack();
}
else if(getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
else{
super.onBackPressed();
}
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.kick_counter_ID) {
KickCounter kickCounter = new KickCounter();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.full_screen_ID, kickCounter).addToBackStack(null).commit();
} else if (id == R.id.nav_mommy_metrics) {
MommyMetrics mommyMetrics = new MommyMetrics();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.full_screen_ID, mommyMetrics).addToBackStack(null).commit();
} else if (id == R.id.nav_milestones) {
Milestones milestones = new Milestones();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.full_screen_ID, milestones).addToBackStack(null).commit();
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "my app");
shareIntent.putExtra(Intent.EXTRA_TEXT, sharetext);
startActivity(Intent.createChooser(shareIntent, "share via"));
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
In Fragments you need to use getChildFragmentManager(), You are using same Fragment manager in the fragments as in Activity. Hope this will help
I'm trying to integrate azure's app service with my app. In particular, I'm trying to store data on the database hosted by Azure. I can insert data fine, but whenever I try to retrieve it, my app freezes.
MainActivity- starts the activity and initializes the azure connection and table.
public class MainActivity extends ActionBarActivity {
/**
* TODO: view data, put data in ordered lists, rate data, scheduler
* **/
Toolbar toolbar;
ViewPager pager;
ViewPageAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"New","Trending","Famous"};
int Numboftabs =3;
MobileServiceClient client;
MobileServiceTable<Post> postTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
//manually set action bar color since not happening before
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPageAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.colorAccent);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
postPrompt();
}
});
//initialize azure
try {
client = new MobileServiceClient("https://firechat.azurewebsites.net", this);
postTable = client.getTable(Post.class);
} catch (MalformedURLException e) {
e.printStackTrace();
}
//testing
//Post post = new Post("haha, so funny :p");
//postTable.insert(post);
}
private String makePost(String input){
Post post = new Post(input);
postTable.insert(post);
return post.text;
}
}
return post.text;
}
}
Tab1- a fragment that populates a list with data retrieved from the server. I believe my error is here when I try to query azure for the data.
public class Tab1 extends Fragment {
MainActivity mainActivity;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
return v;
}
#Override
public void onStart() {
super.onStart();
try {
//get data from azure
mainActivity = (MainActivity) getActivity();
List<Post> postList= mainActivity.postTable.execute().get();
//List<Post> postList = new ArrayList<Post>();
//set lists
ListView newListView = (ListView) mainActivity.findViewById(R.id.newListView);
NewAdapter newAdapter = new NewAdapter(mainActivity, postList);
newListView.setAdapter(newAdapter);
}catch(Exception e){
}
}
}
I found out I was having the error because you must retrieve data from Azure using an async task. I left an example of one down below.
private void retrievePosts(){
AsyncTask<Void,Void,Void> task = new AsyncTask<Void,Void,Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
postList= mainActivity.postTable.execute().get();
Log.e("TAG",postList.get(0).text);
newAdapter.updateList(postList);
} catch (final Exception e) {
}
return null;
}
};
runAsyncTask(task);
}
I have an action bar but have only been to display the title of application or/and the title of the current fragment activity into it. I would want to display logo in it, and any attempts to add a logo have been unsuccessful.
Below is the code:
public class MainActivity extends ActionBarActivity {
private String[] mOptionMenu;
private DrawerLayout mDrawerLayout;
private RelativeLayout mDrawerRelativeLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mTitleSection;
private CharSequence mTitleApp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView button=(ImageView)findViewById(R.id.logobutton);
mOptionMenu = new String[] { "Opción 1", "Opción 2", "Opción 3" };
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerRelativeLayout = (RelativeLayout)
findViewById(R.id.left_drawer);
mDrawerList = (ListView) findViewById(R.id.list_view_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
mOptionMenu));
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FirstFragment();
break;
case 1:
fragment = new SecondFragment();
break;
case 2:
fragment = new ThirdFragment();
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mTitleSection = mOptionMenu[position];
getSupportActionBar().setTitle(mTitleSection);
mDrawerLayout.closeDrawer(mDrawerRelativeLayout);
}
});
mDrawerList.setItemChecked(0, true);
mTitleSection = getTitle();
mTitleApp = getTitle();
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitleSection);
getSupportActionBar().setLogo(R.drawable.logo);
ActivityCompat.invalidateOptionsMenu(MainActivity.this);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mTitleSection);
ActivityCompat.invalidateOptionsMenu(MainActivity.this);
getSupportActionBar().setLogo(R.drawable.logo);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_activity_actions, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show();
;
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
I tried adding this line in the code, but no image is being displayed:
getSupportActionBar().setLogo(R.drawable.logo);
I also have a similar concern, in that I want the logo to be clickable and to direct user to the MainActivity
You have to enable Logo feature on you ActionBar by calling getSupportActionBar().setDisplayUseLogoEnabled(true).
Try this in your OnCreate in this order:
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setLogo(R.drawable.ic_logo);
In your manifest, you can set android:logo="#drawable/logo" on your <application> node, and/or android:icon="#drawable/icon" for each <activity> node.
In your mainfest file, add under <application>:
android:icon="#drawable/logo"