I keep getting an IllegalArgumentException in my MainActivity code, please help me! The error is being shown on the line
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
I am trying to add in the QR code reader into the Main Activity, but when I did so, this error popped up
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private SharedPreferences appData;
private Button scan_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_scan);
scan_button = (Button) findViewById(R.id.btnScan);
final Activity activity = this;
scan_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*FloatingActionButton fab = 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 = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_transaction, R.id.nav_qrcode,
R.id.nav_login, R.id.nav_logout, R.id.nav_signup, R.id.nav_rewards, R.id.nav_scan)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
appData = getSharedPreferences("appData", this.MODE_PRIVATE);
SharedPreferences.Editor editor = appData.edit();
editor.putFloat("Point", 0);
//editor.putBoolean("SAVE_LOGIN_DATA", checkBox.isChecked());
editor.putString("ID", "");
editor.putString("PWD", "");
editor.apply();
//Navigation.findNavController(navigationView).navigate(R.id.nav_login);
}
#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 onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
public boolean onChangeMenuItem() {
NavigationView navigationView = findViewById(R.id.nav_view);
Menu menu = navigationView.getMenu();
MenuItem nav_dashboard = menu.findItem(R.id.nav_login);
nav_dashboard.setVisible(false);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(this, "You Cancelled the Scan", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
String scanResult = data.getStringExtra("SCAN_RESULT");
int pointsAdded = Integer.parseInt(scanResult);
}
}
else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
Related
I'm trying to make the "sign out" item take me back to the Login window. I did a lot of searching and watching videos but nothing worked for me.
Here's my built-in navigation drawer code.
The code I typed starts from line 46 to line 56, most codes are just built-in.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityHomepageBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.appBarHomepage.toolbar);
binding.appBarHomepage.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 = binding.drawerLayout;
NavigationView navigationView = binding.navView;
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id=menuItem.getItemId();
if (id == R.id.nav_Sign_out){
Intent intent = new Intent(Homepage.this, Login.class);
startActivity(intent);
}
return true;
}
});
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_dashboard, R.id.nav_profile, R.id.nav_orders, R.id.nav_recent_orders,
R.id.nav_pending_deliveries, R.id.nav_cancelled_orders, R.id.nav_settings)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_homepage);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.homepage, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_homepage);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
Login.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
textview = (TextView) findViewById(R.id.textViewSignUp);
textview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Login.this,Register.class);
startActivity(intent);
}
});
button = (Button) findViewById(R.id.btnLogin);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Login.this,Homepage.class);
startActivity(intent);
}
});
}
}
It doesn't have an error but it doesn't work.
Here's the activity_main_drawer.xml where I put the items.
<group
android:id="#+id/menu_top"
android:checkableBehavior="none">
<item
android:id="#+id/nav_dashboard"
android:icon="#drawable/ic_baseline_dashboard_24"
android:title="#string/dashboard">
</item>
<item
android:id="#+id/nav_profile"
android:icon="#drawable/ic_baseline_person_24"
android:title="#string/profile" >
</item>
</group>
<item
android:id="#+id/nav_orders"
android:title="#string/orders" >
<menu>
<item
android:id="#+id/nav_menu_orders"
android:title="#string/Orders"
android:icon="#drawable/ic_orders" />
<item
android:id="#+id/nav_recent_orders"
android:title="#string/recent_orders"
android:icon="#drawable/ic_recent" />
</menu>
</item>
<item
android:id="#+id/nav_deliveries"
android:title="#string/deliveries" >
<menu>
<item
android:id="#+id/nav_pending_deliveries"
android:title="#string/pending_deliveries"
android:icon="#drawable/ic_pending_deliveries"/>
<item
android:id="#+id/nav_recent_deliveries"
android:title="#string/recent_deliveries"
android:icon="#drawable/ic_recent" />
</menu>
</item>
<item
android:id="#+id/nav_cancelled_orders"
android:icon="#drawable/ic_baseline_cancel_24"
android:title="#string/cancelled_orders" >
</item>
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_baseline_settings_24"
android:title="#string/settings" >
</item>
<group
android:id="#+id/nav_menu_bottom"
android:checkableBehavior="none">
<item
android:id="#+id/nav_Sign_out"
android:icon="#drawable/ic_sign_out"
android:title="#string/sign_out">
</item>
</group>
Try this -
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
binding = ActivityHomepageBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.appBarHomepage.toolbar);
binding.appBarHomepage.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 = binding.drawerLayout;
NavigationView navigationView = binding.navView;
navigationView.setNavigationItemSelectedListener(this);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_dashboard, R.id.nav_profile, R.id.nav_orders, R.id.nav_recent_orders,
R.id.nav_pending_deliveries, R.id.nav_cancelled_orders, R.id.nav_settings)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_homepage);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.homepage, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_homepage);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int id=menuItem.getItemId();
if (id == R.id.nav_Sign_out){
Intent intent = new Intent(Homepage.this, Login.class);
startActivity(intent);
}
return true;
}
}
I'm new in android development, I used the navigation drawer activity template. I followed the tutorial by firebase to put in the code and made some change. My question is, I made a signin button in the navigation header, I would like to click the button then trigger the Google signin function. I put that code in a new java class, and how can I use MainActivity.java to make it work? many thanks.
NavHeadMainActivity.java
public class NavHeaderMainActivity extends AppCompatActivity {
private static final String TAG = "GoogleActivity";
private static final int RC_SIGN_IN = 9001;
private FirebaseAuth mAuth;
private GoogleSignInClient mGoogleSignInClient;
private NavHeaderMainBinding mBinding;
SignInButton signInButton = findViewById(R.id.sign_in_button);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
findViewById(R.id.sign_in_button).setOnClickListener(signInListener);
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
}
private Button.OnClickListener signInListener = new Button.OnClickListener(){
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
signIn();
break;
}
}
};
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
firebaseAuthWithGoogle(account.getIdToken());
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(String idToken) {
AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
// Snackbar.make(mBinding.mainLayout, "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
}
private void updateUI(FirebaseUser user) {
if (user != null) {
mBinding.eMail.setText(user.getEmail());
mBinding.userName.setText(user.getUid());
signInButton.setVisibility(View.GONE);
// mBinding.signOutAndDisconnect.setVisibility(View.VISIBLE);
} else {
mBinding.eMail.setText(null);
mBinding.userName.setText(null);
signInButton.setVisibility(View.VISIBLE);
// mBinding.signOutAndDisconnect.setVisibility(View.GONE);
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private Button signInBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = 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 = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
View headerView = navigationView.getHeaderView(0);
signInBtn = (Button) headerView.findViewById(R.id.sign_in_button);
signInBtn.setOnClickListener(signInBtnListener);
}
#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 onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
private Button.OnClickListener signInBtnListener =new Button.OnClickListener(){
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(MainActivity.this,NavHeaderMainActivity.class);
startActivity(intent);
}
};
}
My MainActivity uses onNavigationItemSelected(MenuItem item) that includes an activity. But somehow it won't open the other fragments that I have on the drawer. I can open the fragments if i delete navigationView.setNavigationItemSelectedListener(this). But then I can't open BookingActivity.
My MainActivity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
//region Properties
private AppBarConfiguration mAppBarConfiguration;
ImageButton settings_btn;
//endregion
#Override
protected void onStart() {
super.onStart();
ProductDatabase productDb = new ProductDatabase();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
settings_btn = findViewById(R.id.btn_settings);
settings_btn.setOnClickListener(v ->
startActivity(new Intent(MainActivity.this, SettingsActivity.class)));
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show());
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_login, R.id.nav_treatments, R.id.nav_product, R.id.nav_about, R.id.nav_contactUs)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
navigationView.setNavigationItemSelectedListener(this); // Fragments work if I remove this line, but not BookingActivity
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_booking) {
startActivity(new Intent(this, BookingActivity.class));
} else if (id == R.id.nav_home) {
} else if (id == R.id.nav_product) {
// What to write here to open ProductFragment?
} else if (id == R.id.nav_treatments) {
} else if (id == R.id.nav_about) {
} else if (id == R.id.nav_contactUs) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
please try this link How to go to fragment from activity
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_booking) {
startActivity(new Intent(this, BookingActivity.class));
} else if (id == R.id.nav_home) {
} else if (id == R.id.nav_product) {
// here you will set intent
} else if (id == R.id.nav_treatments) {
} else if (id == R.id.nav_about) {
} else if (id == R.id.nav_contactUs) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Hi i'm trying to put an event Item click in my Navigation View from drawer it works fine, but the problem is the other items in my drawer stop working, it seems that putting an item click event on my navigation view affect my NavigationController
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bundy_clock);
dBhelper = new DBhelper(this);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, R.id.nav_send)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if(id == R.id.nav_logout){
AlertDialog.Builder conDialog = new AlertDialog.Builder(BundyClock.this);
conDialog.setTitle("Confirm");
conDialog.setMessage("Are you sure you want to log out?");
conDialog.setCancelable(false);
conDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(BundyClock.this, MainActivity.class));
Toast.makeText(getApplicationContext(),"Successfully Logout",Toast.LENGTH_SHORT).show();
finish();
}
});
conDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog sdialog = conDialog.create();
sdialog.show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
}
You have to use NavigationUI.onNavDestinationSelected to handle this. Check below:
boolean handled = NavigationUI.onNavDestinationSelected(menuItem, navController);
if (!handled) {
if(id == R.id.nav_logout){
AlertDialog.Builder conDialog = new AlertDialog.Builder(BundyClock.this);
conDialog.setTitle("Confirm");
conDialog.setMessage("Are you sure you want to log out?");
conDialog.setCancelable(false);
conDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(BundyClock.this, MainActivity.class));
Toast.makeText(getApplicationContext(),"Successfully Logout",Toast.LENGTH_SHORT).show();
finish();
}
});
conDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog sdialog = conDialog.create();
sdialog.show();
}
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return handled;
I have been investigating for like 4 hours about this problem, but I didnt get any help.
On summary, I am trying to navigate between fragments in Android Studio, using Navigation View. I want to go from Home Fragment to Services Fragment.
The first Home Fragment always load, but when I click on Services item, the fragment Services load, but the data from Home always keeps on the fragment too.
This is my code:
HOME FRAGMENT CLASS
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
private PieChart pieChart;
private UserService userService;
private Calendar calendar;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
pieChart = root.findViewById(R.id.pieChart);
userService = UserRepository.getUserService();
getData();
return root;
}
private void getData(){
calendar = Calendar.getInstance();
int month = calendar.get(Calendar.MONTH)+1;
Log.i("INT MONTH", String.valueOf(month));
userService.getHoursPerService(String.valueOf(UserCache.empleado.getId_emp()),String.valueOf(month)).enqueue(new Callback<List<Servicio>>() {
#Override
public void onResponse(Call<List<Servicio>> call, Response<List<Servicio>> response) {
if(response.body().size() == 0){
pieChart.setNoDataText("Sin horas actuales.");
pieChart.setNoDataTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
pieChart.invalidate();
}else{
List<Servicio> list = response.body();
List<PieEntry> pieEntries = new ArrayList<>();
for(int cont=0;cont<list.size();cont++){
pieEntries.add(new PieEntry(list.get(cont).getTotalHoras(), list.get(cont).getLugarServicio()));
}
SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
String actual_month = sdf.format(calendar.getTime());
PieDataSet dataSet = new PieDataSet(pieEntries, getResources().getString(R.string.txt_hours_of)+" "+actual_month);
dataSet.setSliceSpace(3f);
dataSet.setSelectionShift(5f);
dataSet.setColors(ColorTemplate.MATERIAL_COLORS);
PieData data = new PieData(dataSet);
data.setValueTextSize(10f);
data.setValueTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
pieChart.getDescription().setEnabled(true);
pieChart.getDescription().setText(getResources().getString(R.string.txt_hours_of)+" "+actual_month+".");
pieChart.getDescription().setTextSize(12f);
pieChart.getDescription().setTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
pieChart.setExtraOffsets(5, 10, 5, 5);
pieChart.setDragDecelerationFrictionCoef(0.99f);
pieChart.setDrawHoleEnabled(true);
pieChart.setHoleColor(Color.WHITE);
pieChart.setTransparentCircleRadius(61f);
pieChart.animateY(2000, Easing.EaseInOutCubic);
pieChart.setEntryLabelColor(ContextCompat.getColor(getContext(),R.color.colorPrimaryDark));
pieChart.setData(data);
pieChart.invalidate();
}
}
#Override
public void onFailure(Call<List<Servicio>> call, Throwable t) {
}
});
}
}
SERVICES FRAGMENT CLASS
public class ServicesFragment extends Fragment {
private ServicesViewModel servicesViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
servicesViewModel = ViewModelProviders.of(this).get(ServicesViewModel.class);
View root = inflater.inflate(R.layout.fragment_myservices, container, false);
final TextView textView = root.findViewById(R.id.text_gallery);
servicesViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
MAIN ACTIVITY
public class MainActivityView extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private AppBarConfiguration mAppBarConfiguration;
private NavigationView navigationView;
private ActionBarDrawerToggle toggle;
private TextView userNameNav;
private TextView userEmailNav;
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_view);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*FloatingActionButton fab = 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();
}
});*/
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_myservices, R.id.nav_startservice)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
View headerView = navigationView.getHeaderView(0);
navigationView.setNavigationItemSelectedListener(this);
userNameNav = headerView.findViewById(R.id.userNameNav);
userEmailNav = headerView.findViewById(R.id.userEmailNav);
userNameNav.setText(UserCache.empleado.getNombre()+" "+UserCache.empleado.getApellidos());
userEmailNav.setText(UserCache.empleado.getEmail());
navigationView.bringToFront();
}
#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_activity_view, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public void onBackPressed() {
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}else{
AlertDialog.Builder alerta = new AlertDialog.Builder(this);
alerta.setTitle(getResources().getString(R.string.txt_dialog_exit_app));
alerta.setPositiveButton(getResources().getString(R.string.txt_yes_option), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
alerta.setNegativeButton(getResources().getString(R.string.txt_no_option), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alerta.show();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.nav_home:
getSupportFragmentManager().popBackStack(null,FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment,new HomeFragment()).commit();
case R.id.nav_myservices:
getSupportFragmentManager().popBackStack(null,FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new ServicesFragment()).commit();
//NavHostFragment.findNavController(new ServicesFragment());
break;
case R.id.nav_startservice:
getSupportFragmentManager().popBackStack(null,FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new StartServiceFragment()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
onNavigationItemSelected is where I do the navigation.
I tried everything, changing the ConstraintLayout to Relative, insert the fragments from xml into framelayout...
Also, I am using MVVM.
If more information is needed i can post here then.
PD: Sorry if I posting something wrong, this is my first time here.
SOLUTION: I forgot completly to break the first case onNavigationItemSelected.