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>
Related
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
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);
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 }
...
}
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>
I got some error in my logcat and my application doesn't run in my smartphone...
I changed some codes in my manifest and MainActivity (named as HomaActivity )
THIS IS MY MANIFEST:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ir.homa">
<permission
android:name="android.permission.INTERNET">
</permission>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="24" />
<application
android:name=".AppController"
android:allowBackup="true"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".HomaActivity"
android:label="#string/app_name"
android:launchMode="singleTop" >
<intent-filter >
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".LoginActivity"
android:label="#string/app_name"
android:launchMode="singleTop"
android:windowSoftInputMode="adjustPan" >
<category android:name="android.intent.category.DEFAULT" />
</activity>
<activity
android:name=".RegisterActivity"
android:label="#string/app_name"
android:launchMode="singleTop"
android:windowSoftInputMode="adjustPan" >
<category android:name="android.intent.category.DEFAULT" />
</activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
THIS IS HomaActivity.Java :
package ir.homa;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
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.Menu;
import android.view.MenuItem;
import android.view.View;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class HomaActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homa);
Toolbar 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) {
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);
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
*/
#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.homa, 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.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public GoogleApiClient client;
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
GoogleApiClient client = null;
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Homa Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://ir.homa/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Homa Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://ir.homa/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
THESE ARE ERRORS IN MY LOGCAT:
07-02 20:26:44.441 26501-26501/ir.homa E/AndroidRuntime: FATAL EXCEPTION: main
Process: ir.homa, PID: 26501
java.lang.RuntimeException: Unable to start activity ComponentInfo{ir.homa/ir.homa.HomaActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.common.api.GoogleApiClient.connect()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.common.api.GoogleApiClient.connect()' on a null object reference
at ir.homa.HomaActivity.onStart(HomaActivity.java:127)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1234)
at android.app.Activity.performStart(Activity.java:6258)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2621)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
This is your problem, you're calling a method on a null variable:
GoogleApiClient client = null;
client.connect();
you need to initialize the client first. something like this
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */,
this /* OnConnectionFailedListener */)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.build();
Check this link.
In onStart(), you have:
GoogleApiClient client = null;
client.connect();
client is null. Hence, you cannot call connect() on it without getting a NullPointerException.