How to pass string variable between fragments in navigation drawer activity template - java

tell me how to pass a string variable between two fragments of the navigation drawer activity template in Android Studio 4.0.1, preferably with examples of program code
I tried to do it using intent, but I don't understand where to specify it
Мой код MainActivity.java:
package com.example.myt;
import android.os.Bundle;
import android.view.View;
import android.view.Menu;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#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);
}
#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();
}
}

Communication between fragments should happen through the parent activity.
You can read more about it on the documentation (including code samples):
https://developer.android.com/guide/fragments/communicate

Related

Main Activity does not have a NavController

During one of the launches of the application, log issued such a stack of errors:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nikitafront.schooldiary, PID: 29751
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nikitafront.schooldiary/com.nikitafront.schooldiary.MainActivity}: java.lang.IllegalStateException: Activity com.nikitafront.schooldiary.MainActivity#4801345 does not have a NavController set on 2131296534
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3754)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3912)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2319)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:239)
at android.app.ActivityThread.main(ActivityThread.java:8205)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016)
Caused by: java.lang.IllegalStateException: Activity com.nikitafront.schooldiary.MainActivity#4801345 does not have a NavController set on 2131296534
at androidx.navigation.Navigation.findNavController(Navigation.java:61)
at com.nikitafront.schooldiary.MainActivity.onCreate(MainActivity.java:53)
at android.app.Activity.performCreate(Activity.java:8119)
at android.app.Activity.performCreate(Activity.java:8103)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1359)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3727)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3912) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2319) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:239) 
at android.app.ActivityThread.main(ActivityThread.java:8205) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016) 
Before this I was only experimenting with app themes, but after I returned everything to its original state nothing has changed
P.S. I tried solve the problem by clearing the cache and restart IDE, but this way doesn`t worked too.
MainActivity.java code
package com.nikitafront.schooldiary;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Spinner;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.nikitafront.schooldiary.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
private CheckBox checkBoxAuto;
private Spinner dropDownList;
private LinearLayout byHandLesson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_write, R.id.nav_do, R.id.nav_account)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(binding.navView, navController);
checkBoxAuto = (CheckBox) findViewById(R.id.checkBoxAuto);
dropDownList = (Spinner) findViewById(R.id.dropDownListLesson);
byHandLesson = (LinearLayout) findViewById(R.id.byHandLesson);
}
#Override
protected void onStart() {
super.onStart();
checkBoxAuto.setOnClickListener(this::selectFillLesson);
int currentNightMode = getApplicationContext().getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && currentNightMode == Configuration.UI_MODE_NIGHT_YES) {
getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.my_black));
}
}
public void selectFillLesson(View view) {
if (checkBoxAuto.isChecked()) {
byHandLesson.setAlpha((float) 0.7);
} else {
byHandLesson.setAlpha((float) 1);
}
dropDownList.setEnabled(!(checkBoxAuto.isChecked()));
}
public void selectCheckBox(View view) {
checkBoxAuto.setChecked(!checkBoxAuto.isChecked());
selectFillLesson(checkBoxAuto);
}
public void addHomework(View view) {
}
}
main_activity.xml code
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
<androidx.fragment.app.FragmentContainerView
android:id="#+id/nav_host_fragment_activity_main"
android:name="androidx.navigation.fragment.NavHostFragment"
class="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="#id/nav_view"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
Manifest.xml code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nikitafront.schooldiary">
<application
android:allowBackup="true"
android:icon="#drawable/homework_icon"
android:label="#string/app_name"
android:roundIcon="#drawable/homework_icon"
android:supportsRtl="true"
android:theme="#style/Theme.SchoolDiary">
<activity
android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
As it was described in the reference:
When creating the NavHostFragment using FragmentContainerView or if
manually adding the NavHostFragment to your activity via a
FragmentTransaction, attempting to retrieve the NavController in
onCreate() of an Activity via Navigation.findNavController(Activity,
#IdRes int) will fail. You should retrieve the NavController directly
from the NavHostFragment instead.
Looks like you should use
NavHostFragment navHostFragment =
(NavHostFragment) supportFragmentManager.findFragmentById(R.id.nav_host_fragment);
NavController navController = navHostFragment.getNavController();
instead of
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
Navigating to a destination is done using a NavController, an
object that manages app navigation within a NavHost. Each
NavHost has its own corresponding NavController.
Write your code like below:
Kotlin
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.nav_view)
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment_activity_main) as NavHostFragment
bottomNavigationView.setupWithNavController(navHostFragment.navController)
Java
BottomNavigationView bottomNavigationView = findViewById<BottomNavigationView>(R.id.nav_view);
NavHostFragment navHostFragment = (NavHostFragment) supportFragmentManager.findFragmentById(R.id.nav_host_fragment_activity_main);
bottomNavigationView.setupWithNavController(navHostFragment.navController);

MenuItem on Navigation Drawer does not respond

i am new to java programming, now i am working on a simple app that has an webview integrated that open a particular website.
My style is navigation drawer for the app. When i press an item from the drawer menu it doesn't work at all. I am trying to open a URL using the webview but nothing happens.
I have tried many things i found on here but i cant get any results
package com.virsoft.alfagreece;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import com.virsoft.alfagreece.ui.home.HomeFragment;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private WebView myWebView;
private AppBarConfiguration mAppBarConfiguration;
#Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent Email = new Intent(Intent.ACTION_SEND);
Email.setType("text/email");
Email.putExtra(Intent.EXTRA_EMAIL,
new String[]{"sales#test.com"});
Email.putExtra(Intent.EXTRA_SUBJECT,
"testApp"); // Email 's Subject
Email.putExtra(Intent.EXTRA_TEXT, "Hi test," + ""); //Email 's Greeting text
startActivity(Intent.createChooser(Email, "Send message"));
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
myWebView =(WebView) findViewById(R.id.webView);
WebSettings webSettings=myWebView.getSettings();
myWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowContentAccess(true);
webSettings.setAppCacheEnabled(true);
webSettings.setCacheMode(webSettings.LOAD_CACHE_ELSE_NETWORK);
webSettings.setDomStorageEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("https://www.test.com");
// 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)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
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.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 onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_home) {
myWebView.loadUrl("https://youtube.com");
Toast.makeText(MainActivity.this,"testing", Toast.LENGTH_LONG).show();
return true;
}
else if (id == R.id.nav_gallery) {
myWebView.loadUrl("https://yahoo.com");
return true;
}
return true;
}
#Override
public void onBackPressed() {
if(myWebView.canGoBack()) {
myWebView.goBack();
} else {
super.onBackPressed();
}
}
}
After setting up a small sample and doing some debugging, it seems to me that a NavigationView can be controlled either by setting up navigation with NavController or by setting a NavigationView.OnNavigationItemSelectedListener. You can't have both of them.
So if you want to keep on using Navigation components (which should by all means be possible), the question is how to get notified of clicks on NavigationView items?
NavController will navigate to some destination, nothing more. But using the safeargs plugin, one can pass along argument values to the destination Fragment.
If you use always the same destination (Fragment) but with different URLs, you could associate each NavigationView item with a specific action in the navigation graph which in turn belongs to one specific URL.
In my sample app, NavController replaced an already visible HomeFragment with a new instance of HomeFragment and the new URL was passed in correctly.
MainActivity onCreate() (note that you can remove everything related to NavigationView.OnNavigationItemSelectedListener from MainActivity):
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
Basic declaration of arguments in navigation graph:
<fragment
android:id="#+id/nav_home"
android:name="com.example.navdrawerissue.HomeFragment"
android:label="fragment_home"
tools:layout="#layout/fragment_home">
<argument
android:name="webUrl"
app:argType="string"
android:defaultValue="https://developer.android.com"/>
</fragment>
Declaration of global action in navigation graph (below fragment, not nested!)
<action android:id="#+id/nav_other" app:destination="#+id/nav_home">
<argument
android:name="webUrl"
app:argType="string"
android:defaultValue="https://youtube.com" />
</action>
NavigationView menu
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/nav_home"
android:icon="#drawable/ic_launcher_background"
android:title="nav_home"/>
<item android:id="#+id/nav_plusone"
android:title="plus one"/>
<item android:id="#+id/nav_other"
android:title="other"/>
</menu>

How to navigate to activity on navigation drawer item click

This is my main activity i want to navigate to an activity on my navigation drawer item click. I have checked the old way of achieving this i.e using switch statement and using onNavigationItemSelected method.
I know this is a question frequently asked, but after reading the many questions and solutions on stack overflow I am confused. I am confused with regards to Fragments and what is required to start an activity from clicking an item in the navigation drawer.
MainActivity.java
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
}
#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();
}
}
mobile_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation 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/mobile_navigation"
app:startDestination="#+id/nav_home">
<fragment
android:id="#+id/nav_home"
android:name="com.vdosol.navigationdrawer.ui.home.HomeFragment"
android:label="#string/menu_home"
tools:layout="#layout/fragment_home" />
<fragment
android:id="#+id/nav_gallery"
android:name="com.vdosol.navigationdrawer.ui.gallery.GalleryFragment"
android:label="#string/menu_gallery"
tools:layout="#layout/fragment_gallery" />
<fragment
android:id="#+id/nav_slideshow"
android:name="com.vdosol.navigationdrawer.ui.slideshow.SlideshowFragment"
android:label="#string/menu_slideshow"
tools:layout="#layout/fragment_slideshow" />
<fragment
android:id="#+id/nav_tools"
android:name="com.vdosol.navigationdrawer.ui.tools.ToolsFragment"
android:label="#string/menu_tools"
tools:layout="#layout/fragment_tools" />
<fragment
android:id="#+id/nav_share"
android:name="com.vdosol.navigationdrawer.ui.share.ShareFragment"
android:label="#string/menu_share"
tools:layout="#layout/fragment_share" />
<fragment
android:id="#+id/nav_send"
android:name="com.vdosol.navigationdrawer.ui.send.SendFragment"
android:label="#string/menu_send"
tools:layout="#layout/fragment_send" />
</navigation>
you can do the following to navigate:
MenuItem logOutItem = navigationView.getMenu().findItem(R.id.nav_logout);
logOutItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
//do your stuff
return true;
}
});
your AppBarConfiguration and Nav Controller should not contain above id ie "nav_logout" (in my case):
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_plan, R.id.navigation_history, R.id.navigation_about, R.id.navigation_feedback, R.id.navigation_notifications)
.setDrawerLayout(drawer)
.build();
your menu should only contain in your menu file....no need to add it to you AppBarConfiguration and your NavController....
hope this helps....happy coding
Implement the listener in your Activity:
public class HomeActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener
setNavigationItemSelectedListener in onCreate of Activity
NavigationView mNavigationView = (NavigationView) findViewById(R.id.account_navigation_view);
if (mNavigationView != null) {
mNavigationView.setNavigationItemSelectedListener(this);
}
Override the method
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_account) {//DO your stuff }
...
}

MainActivity cannot run after splashcreen

This is my code:
package pi.com.pariwisata;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_maps) {
Intent peta = new Intent(this, MapsActivity.class);
startActivity(peta);
} else if (id == R.id.nav_list) {
Intent list = new Intent(this, ListActivity.class);
startActivity(list);
} else if (id == R.id.nav_about) {
Intent tentang = new Intent(this, TentangActivity.class);
startActivity(tentang);
} else if (id == R.id.nav_exit) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Keluar Dari Aplikasi?")
.setCancelable(false)//tidak bisa tekan tombol back
//jika pilih yess
.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
//jika pilih no
.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
and I have an error in setSupportActionBar(toolbar);
can you help me?
Try setting your Activity's parent theme to Theme.AppCompat.Light.NoActionBar
The important part is "NoActionBar"
Then you can use your custom ToolBar at your layout.
Set windowNoTitle and 'windowActionBar` in base theme of styles.xml and apply this theme to your application in AndroidManifest.xml
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
</style>

MainActivity is not public

I am getting a weird error in AndroidManifest.xml file saying "MainActivity is not public. Validate Resource reference inside Android XML files." Do not know how to solve the error. Can anyone help me here?
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pixalstudio.javaclasses" >
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".What_is_java"
android:label="#string/title_activity_what_is_java" >
</activity>
</application>
</manifest>
MainActivity.java
package com.pixalstudio.javaclasses;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener {
private Toolbar toolbar;
ListView mDrawerList;
DrawerLayout mDrawerLayout;
ActionBarDrawerToggle mDrawerToggle;
String[] mDrawerListItems;
String[] mDrawerListItems2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectivityManager cManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cManager.getActiveNetworkInfo();
if (nInfo != null && nInfo.isConnected()) {
Toast.makeText(this, "Newtwrok Available", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Network Not Available", Toast.LENGTH_LONG).show();
}
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
LayoutInflater inflater = getLayoutInflater();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mDrawerList = (ListView) findViewById(R.id.drawerList);
mDrawerListItems = getResources().getStringArray(R.array.drawer_list);
ViewGroup header_news = (ViewGroup) inflater.inflate(R.layout.nav_header, mDrawerList, false);
mDrawerList.addHeaderView(header_news, null, false);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mDrawerListItems));
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 1) {
Intent i = new Intent(MainActivity.this, What_is_java.class);
startActivity(i);
}
mDrawerLayout.closeDrawer(mDrawerList);
}
});
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
toolbar,
R.string.drawer_open,
R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
syncState();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
syncState();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle.syncState();
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 2) {
Intent i = new Intent(this, What_is_java.class);
startActivity(i);
}
mDrawerLayout.closeDrawer(mDrawerList);
}
}
activity_main.xml
<LinearLayout 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:orientation="vertical">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar">
</include>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<ListView
android:id="#+id/drawerList"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#CE93D8">
</ListView>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
Change class MainActivity [...] to public class MainActivity [...] in MainActivity.java

Categories

Resources