How to give functionality to navigation menu selection? - java

web dev trying (and struggling) to have a go at android application development here. I'm trying to implement a side navigation into a login system so make my UI look nicer and generally give my app a nicer feel. The problem that I am having is;
Currently on the MainActivity (dashboard/ homescreen) of the application, I have a button which basically logs out the user from the login system which I am using with the following code.
Button logoutBtn = findViewById(R.id.btnLogout);
logoutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
session.logoutUser();
Intent i = new Intent(MainActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
});
The UI:
The above code works as expected, by logging out the user and re-directing them to the login/ register page. Now I've start to try and implement a side navigation I've found (https://antonioleiva.com/materialize-app/) and am struggling to work out how I can give the functionality of the above button to the navigation menu item as shown below;
The side navigation example I am using has the following code which basically presents a notification to show which side navigation menu item has being selected;
private void setupDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
Snackbar.make(content, menuItem.getTitle() + " pressed", Snackbar.LENGTH_LONG).show();
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
}
This presents the following;
If anyone could give me any points, hints, or help on how I can give the menu option the functionality of the logout button it would be thoroughly appreciated as once I know how to set on click listeners/ run parts of code for menu selections I can proceed to load different activities and proceed building my application.
Thanks in advance SO.
The full code for the homescreen (MainActivity.java) is below;
package com.antonioleiva.materializeyourapp;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
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.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
RecyclerViewAdapter.OnItemClickListener {
private SessionHandler session;
private static List<ViewModel> items = new ArrayList<>();
private DrawerLayout drawerLayout;
private View content;
private RecyclerView recyclerView;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new SessionHandler(getApplicationContext());
User user = session.getUserDetails();
TextView dashboardText = findViewById(R.id.dashboardText);
dashboardText.setText("Welcome to gluca, " + user.getFullName() + "!");
initRecyclerView();
initFab();
initToolbar();
setupDrawerLayout();
Button logoutBtn = findViewById(R.id.btnLogout);
logoutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
session.logoutUser();
Intent i = new Intent(MainActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
});
content = findViewById(R.id.content);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
setRecyclerAdapter(recyclerView);
}
}
#Override
public void onEnterAnimationComplete() {
super.onEnterAnimationComplete();
setRecyclerAdapter(recyclerView);
recyclerView.scheduleLayoutAnimation();
}
private void initRecyclerView() {
recyclerView = (RecyclerView) findViewById(R.id.recycler);
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
}
private void setRecyclerAdapter(RecyclerView recyclerView) {
RecyclerViewAdapter adapter = new RecyclerViewAdapter(items);
adapter.setOnItemClickListener(this);
recyclerView.setAdapter(adapter);
}
private void initFab() {
findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(content, "FAB Clicked", Snackbar.LENGTH_SHORT).show();
}
});
}
private void initToolbar() {
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_black_24dp);
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
private void setupDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
Snackbar.make(content, menuItem.getTitle() + " pressed", Snackbar.LENGTH_LONG).show();
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(View view, ViewModel viewModel) {
DetailActivity.navigate(this, view.findViewById(R.id.image), viewModel);
}
}

What if you pass logout actions to a new function , let say logout() and you put inside session.logoutUser();
Intent i = new Intent(MainActivity.this, LoginActivity.class);
startActivity(i);
finish();
Then, inside onOptionsItemSelected function you add a case check case (menuItem.getTitle =="Logout") {lougout();}
Of course it's just an idea but you can elaborate it

Below is the sample code for directly logout from menu
NOTE : No need of open new Activity or fragment for logout.
Here is Code:
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
fragment = new HomeFragment();
title.setText(pref.getString(Constants.REGIS_FIRST_NAME, "")+" "+pref.getString(Constants.REGIS_LAST_NAME, ""));
}
if (id == R.id.nav_profile) {
fragment = new ProfileFragment();
title.setText("My Profile ");
}
if (id == R.id.nav_past) {
fragment = new PastFragment();
title.setText("Past Ceremony ");
}
else if (id == R.id.nav_logout) {
callLogout(); //logout here
}
Here is the Dialog code :
private void callLogout() {
final Dialog dialog1;
dialog1 = new Dialog(MainActivity.this);
dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog1.setCancelable(false);
dialog1.setContentView(R.layout.logout_dilaog);
final TextView logoutTxt, yes, no;
yes = dialog1.findViewById(R.id.yes);
no = dialog1.findViewById(R.id.no);
logoutTxt = dialog1.findViewById(R.id.logoutTxt);
Log.e("NAME", "" + pref.getString("USER_NAME_LOGIN", ""));
logoutTxt.setText("Are you sure to logout ?");
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor = pref.edit();
editor.clear();
editor.apply();
// utils.showtoast("Logout");
finish();
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog1.dismiss();
}
});
dialog1.show();
}
logout_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_marginTop="10dp"
android:gravity="center_horizontal"
android:textSize="16dp"
android:fontFamily="#font/lato_semibold"
android:id="#+id/logoutTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black" />
<LinearLayout
android:gravity="right"
android:layout_marginTop="15dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/yes"
android:layout_marginRight="15dp"
android:layout_width="90dp"
android:layout_height="30dp"
android:text="YES"
android:fontFamily="#font/lato_regular"
android:gravity="center"
android:textColor="#color/white"
android:textSize="14dp"
android:background="#drawable/ripple_btn"
/>
<TextView
android:layout_marginRight="15dp"
android:id="#+id/no"
android:layout_width="90dp"
android:layout_height="30dp"
android:text="NO"
android:fontFamily="#font/lato_regular"
android:gravity="center"
android:textColor="#color/white"
android:textSize="14dp"
android:background="#drawable/ripple_btn"
/>
</LinearLayout>

Related

'Attempt to invoke virtual method 'android.webkit.WebSettings android.webkit.WebView.getSettings()' on a null object reference' on activity open

I want to open a atctivity, that includes a browser, when i press the button 5 times.
Here is my MainActivity.java:
package de.gamingwave.browser;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
private static int druecken = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setDruecken(getDruecken() + 1);
System.out.println(getDruecken());
if (druecken == 5){
Intent activity2Intent = new Intent(getApplicationContext(), browser.class);
startActivity(activity2Intent);
}
}
});
}
public static int getDruecken() {
return druecken;
}
public static void setDruecken(int druecken) {
MainActivity.druecken = druecken;
}
}
Here is the browser.java:
package de.gamingwave.browser;
import android.annotation.SuppressLint;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
public class browser extends AppCompatActivity {
// Declare View object references
EditText etUrl;
Button btnGo;
WebView webView;
ProgressBar progressBar;
ProgressDialog progressDialog;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
// Instantiate View objects
etUrl = findViewById(R.id.etUrl);
btnGo = findViewById(R.id.btnGo);
webView = findViewById(R.id.webview);
progressBar = findViewById(R.id.progressBar);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Please Wait...");
// Create a WebSettings object
// Set Zoom Controls
webView.getSettings().setBuiltInZoomControls(true);
// JavaScript is by default turned off in WebView. To enable JavaScript we can call
// setJavaScriptEnabled() method on webSettings object and pass true as parameter.
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setAllowFileAccess(true);
/*
Now, when the user clicks a link from a web page in your WebView, the
default behavior for Android is to launch an application that handles
URLs. Typically, system's default web browser opens and loads the
destination URL. However, you can override this behavior for your
WebView, so that links open within your WebView and hence within the app.
You can then allow the user to navigate backward and forward through their web page history
that's maintained by your WebView. To accomplish this, we need to create a subclass of
WebViewClient and override it's shouldOverrideUrlLoading() method. Let's do that.
*/
webView.setWebViewClient(new MyWebViewClient());
if (!checkConnection()) {
showDialog();
}
// Attach OnClickListener with the Button
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Get the text from EditText
String url = etUrl.getText().toString().trim();
// If entered url doesn't start "http://" or "https://" we need to append it
// before the url.
if (!url.startsWith("http://") || !url.startsWith("https://")) {
url = "https://" + url;
}
// To load the webView with the url we need to call loadUrl() method
// of the WebView class, passing url as parameter.
webView.loadUrl(url);
}
});
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
setTitle("Loading...");
progressBar.setProgress(newProgress);
progressDialog.show();
if (newProgress == 100) {
setTitle(webView.getTitle());
progressDialog.dismiss();
}
super.onProgressChanged(view, newProgress);
}
});
webView.setDownloadListener(new MyDownLoadListener());
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// When you return false you're telling Android not to override; let WebView
// load the page
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
webView.setVisibility(View.GONE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
webView.setVisibility(View.VISIBLE);
}
}
/* Run the application. (pause)
Let's specify a url in the EditText field and press the ENTER button to launch the website.
But before that please make sure that you are connected to the internet.
The site looks good in WebView.
As you can see, the url loads properly in WebView but if we click the Back button,
the app gets closed even though we’ve navigated through a few pages within the WebView itself.
Let's see how we can handle navigation in WebView with Back Button.
To go through the browsing history on pressing the Back button we need to override
onBackPressed() method as follows.
*/
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to Exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
// The WebView maintains a browsing history just like a normal browser.
// If there is no history then it will result in the default behavior of the Back button i.e.
// closing the app.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navPrev:
onBackPressed();
break;
case R.id.navNext:
if (webView.canGoForward()) {
webView.goForward();
}
break;
case R.id.navReload:
checkConnection();
}
return super.onOptionsItemSelected(item);
}
private boolean checkConnection() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
return true;
}
}
} else {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
return true;
}
}
}
return false;
}
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Connect to WIFI or Exit")
.setCancelable(false)
.setPositiveButton("Connect to WIFI", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
})
.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public class MyDownLoadListener implements DownloadListener {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
if (url != null) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
}
}
}
Here is the activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:text="Senden"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="#+id/button"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" app:backgroundTint="#1BB500"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="Name"
android:ems="10"
android:id="#+id/editTextTextPersonName" tools:layout_editor_absoluteY="127dp"
tools:layout_editor_absoluteX="105dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
And here is the activity_browser.java:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".browser"
android:padding="10dp">
<!-- Lets design the layout -->
<!-- Create a horizontal LinearLayout to display the EditText and the ENTER Button. -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/etUrl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="9"
android:ems="10"
android:maxLines="1"
android:hint="Enter Url"
android:inputType="textPersonName"
android:minHeight="52dp"
android:drawableLeft="#drawable/ic_baseline_search_24"/>
<Button
android:id="#+id/btnGo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#0070c7"
android:textColor="#android:color/white"
android:layout_weight="1"
android:text="Go" />
</LinearLayout>
<!-- Add a RelativeLayout to contain a ProgressBar and a WebView
that fills the rest of the screen. -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone"/>
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/webview"
android:visibility="gone"/>
</RelativeLayout>
</LinearLayout>
What's wrong with this code?
Thank's for helping.
The button should open a new browser activity.

How to implement sign out function in the new navigation drawer in android studio?

I would like to implement the sign out method in my project. i watch all youtube tutorial but seems like the navigation drawer is the update version. and i'm clueless on how to implement those sign out coding into my coding.
the newest version of the navigation drawer already built in with the ui package folder. So i'm not quite sure on how to implement those tutorial code because most of the tutorial code have this code.
below is the tutorial code and i don't know on how to implement the sign out method into my home.java code. thank you
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
getSupportActionBar().setTitle("Home");
getSupportFragmentManager().beginTransaction().replace(R.id.container,new HomeFragment()).commit();
} else if (id == R.id.nav_profile) {
getSupportActionBar().setTitle("Profile");
getSupportFragmentManager().beginTransaction().replace(R.id.container,new ProfileFragment()).commit();
} else if (id == R.id.nav_settings) {
getSupportActionBar().setTitle("Settings");
getSupportFragmentManager().beginTransaction().replace(R.id.container,new SettingsFragment()).commit();
}
else if (id == R.id.nav_signout) {
FirebaseAuth.getInstance().signOut();
Intent loginActivity = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(loginActivity);
finish();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
this is my home.java code
package com.example.guru;
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 com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
import android.widget.TextView;
public class Home extends AppCompatActivity {
FirebaseAuth firebaseAuth;
FirebaseUser currentUser;
DatabaseReference databaseReference;
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//ini
firebaseAuth = FirebaseAuth.getInstance();
currentUser = firebaseAuth.getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference("Customer");
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_profile, R.id.nav_orders,R.id.nav_logout)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
updateNavHeader();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
public void updateNavHeader() {
NavigationView navigationView = findViewById(R.id.nav_view);
View headerView= navigationView.getHeaderView(0);
TextView navName= headerView.findViewById(R.id.txtName);
TextView navEmail=headerView.findViewById(R.id.txtEmail);
navName.setText(currentUser.getDisplayName());
navEmail.setText(currentUser.getEmail());
}
}
LogoutFragment
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.example.guru.R;
public class LogoutFragment extends Fragment {
private LogoutViewModel logoutViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
logoutViewModel =
ViewModelProviders.of(this).get(LogoutViewModel.class);
View root = inflater.inflate(R.layout.fragment_logout, container, false);
final TextView textView = root.findViewById(R.id.text_logout);
logoutViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
and this is my LogoutViewModel
package com.example.guru.ui.Logout;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class LogoutViewModel extends ViewModel {
private MutableLiveData<String> mText;
public LogoutViewModel() {
mText = new MutableLiveData<>();
mText.setValue("logout");
}
public LiveData<String> getText() {
return mText;
}
}
Feels like there should be a built in solution but so far I have solved it like this.
I simply add a click listener on that menu option, in my case my logout button:
In Java -->
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.getMenu().findItem(R.id.logout).setOnMenuItemClickListener(menuItem -> {
logout();
return true;
});
In Kotlin -->
navView.getMenu().findItem(R.id.nav_logout).setOnMenuItemClickListener({ menuItem ->
logoutDialog()
true
})
I found two solution to handle it.
1. If you have register your fragment in navigation graph than
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller, #NonNull NavDestination destination, #Nullable Bundle arguments) {
if (destination.getId() == R.id.logout){
logout();
}
}
});
2. If you don't have register fragment in navigation graph and you just want to handle click event on drawer menu.
mNavigationView.getMenu().findItem(R.id.nav_logout).setOnMenuItemClickListener(menuItem -> {
AppUtils.showLongToast("this works", getApplicationContext());
return true;
});
my navigation menu code
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_menu_share"
android:title="#string/menu_share" />
<item
android:id="#+id/logout"
android:icon="#drawable/logout"
android:title="Logout" />
<item
android:id="#+id/login"
android:icon="#drawable/logout"
android:title="Login" />
</menu>
code inside onResume method , this will hide either sign out or sign in button depending upon auth state of user
#Override
protected void onResume() {
super.onResume();
if (auth.getCurrentUser() == null) {
navigationView.getMenu().findItem(R.id.logout).setVisible(false);
navigationView.getMenu().findItem(R.id.login).setVisible(true);
// perform action when user is not logged in
} else {
navigationView.getMenu().findItem(R.id.logout).setVisible(true);
navigationView.getMenu().findItem(R.id.login).setVisible(false);
// perform action when user is already logged in
}
}
Handle navigation view item clicks here.
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logout) {
auth.signOut();
onResume();
} else if (id == R.id.login) {
//handle event login button pressed
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Hope this will help you
I solve it with the help of constraint layout

Swipe to refresh webview fragment doesnt load url

I have a webview fragment in my MainActivity. I am trying to add Swipetoview inside it. But when I load the fragment it doesn't load the url.
My fragment:
// Inflate the layout for this fragment
View vDriver=inflater.inflate(R.layout.fragment_drivers, container, false);
mWebView = vDriver.findViewById(R.id.drivers_webview);
mWebView.loadUrl("https://ahmetbarpa-grand-prix.firebaseapp.com/drivers.html");
// Enable Javascript
//WebSettings webSettings = mWebView.getSettings();
//webSettings.setJavaScriptEnabled(true);
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());
swipeLayout = vDriver.findViewById(R.id.fragment_drivers);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mWebView.reload();
new Handler().postDelayed(new Runnable() {
#Override public void run() {
swipeLayout.setRefreshing(false);
}
}, 5000);
}
});
return vDriver;
My fragment layout:
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_drivers"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Drivers">
<WebView
android:id="#+id/drivers_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v4.widget.SwipeRefreshLayout>
I tried different things and this is the last code I tried. What am I doing wrong?
Thanks for your time in advance.
EDIT: MainActivity
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
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.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, HomeFragment.OnFragmentNavListener,Drivers.OnDriverNavigationListener {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private GoogleApiClient mGoogleApiClient;
private static final int RC_SIGN_IN = 0 ;
private SignInButton btn_signin;
private TextView nameText;
private TextView emailText;
private ImageView imgProfilePic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
HomeFragment fragment = new HomeFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
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);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View navHeader1 = navigationView.getHeaderView(0);
btn_signin = navHeader1.findViewById(R.id.signin_btn);
View navHeader3 = navigationView.getHeaderView(0);
nameText = navHeader3.findViewById(R.id.name);
View navHeader4 = navigationView.getHeaderView(0);
emailText = navHeader4.findViewById(R.id.email);
View navHeader5 = navigationView.getHeaderView(0);
imgProfilePic = navHeader5.findViewById(R.id.imgProfilePic);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null){
btn_signin.setVisibility(View.GONE);
if(user.getDisplayName() != null) {
nameText.setText(user.getDisplayName());
nameText.setVisibility(View.VISIBLE);
}
emailText.setText(user.getEmail());
emailText.setVisibility(View.VISIBLE);
imgProfilePic.setVisibility(View.VISIBLE);
Picasso.get().load(user.getPhotoUrl())
.into(imgProfilePic);
NavigationView navigationView2 = findViewById(R.id.nav_view);
Menu menu = navigationView2.getMenu();
MenuItem target = menu.findItem(R.id.nav_send);
target.setVisible(false);
MenuItem target2 = menu.findItem(R.id.nav_send2);
target2.setVisible(true);
}
else {
nameText.setVisibility(View.GONE);
emailText.setVisibility(View.GONE);
btn_signin.setVisibility(View.VISIBLE);
NavigationView navigationView2 = findViewById(R.id.nav_view);
Menu menu = navigationView2.getMenu();
MenuItem target = menu.findItem(R.id.nav_send);
target.setVisible(true);
MenuItem target2 = menu.findItem(R.id.nav_send2);
target2.setVisible(false);
imgProfilePic.setVisibility(View.GONE);
}
}
};
btn_signin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
signIn();
}
});
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
private void signIn () {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// deneme
}
}
}
#Override
public void onStop() {
super.onStop();
if(mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
#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 onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(final 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) {
signIn();
} else if (id == R.id.nav_send2) {
FirebaseAuth.getInstance().signOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
Toast.makeText(getApplicationContext(), "Çıkış yaptınız.", Toast.LENGTH_SHORT).show();
}
});
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentNav(int position) {
Fragment navFragment = null;
switch (position) {
case 0:
navFragment = new HomeFragment();
break;
case 1:
navFragment = new Drivers();
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, navFragment)
.addToBackStack(null)
.commit();
}
#Override
public void onDriverNavigation(int asd) {
}
}
HomeFragment.java
package com.ahmetbarpa.grandprix;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class HomeFragment extends Fragment {
private OnFragmentNavListener mListener;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v1 =inflater.inflate(R.layout.fragment_home, container, false);
Button profile= v1.findViewById(R.id.button1);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
onButtonSelected(1);
}
});
Button education= v1.findViewById(R.id.button2);
education.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Takımlar ve arabalar",Toast.LENGTH_SHORT).show();
}
});
Button health= v1.findViewById(R.id.button3);
health.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Pistler",Toast.LENGTH_SHORT).show();
}
});
Button goals= v1.findViewById(R.id.button4);
goals.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Sıralama",Toast.LENGTH_SHORT).show();
}
});
Button finance= v1.findViewById(R.id.button5);
finance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Grand Prix Tarihi",Toast.LENGTH_SHORT).show();
}
});
Button comfort= v1.findViewById(R.id.button6);
comfort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"GP kart oyunu",Toast.LENGTH_SHORT).show();
}
});
return v1;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonSelected(int position) {
if (mListener != null) {
mListener.onFragmentNav(position);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentNavListener) {
mListener = (OnFragmentNavListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentNav");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentNavListener {
void onFragmentNav(int position);
}
}
Instead of reload()
mWebView.loadUrl("https://ahmetbarpa-grand-prix.firebaseapp.com/drivers.html");
Try it..
If this is not the way you want, the second method is:
make a new class as:
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
then, Instead of this:
mWebView.setWebViewClient(new WebViewClient());
write this:
mWebView.setWebViewClient(new MyBrowser());
Hopefully your problem will be solved

Using Nav Drawer Settings in different Activity

So I am creating an app that I want the user to be able to decide if they want to use WiFi or 4G to fetch the data after logging in (I will make another question about implementing the decision later, unless anyone wants to add that here too). So currently I have a MainActivity.java that will be handling the logging in (which I have yet to implement) and I have a NavDrawerActivity.java for the Navigation Drawer. Now obviously once I do the "log in" it goes to the Nav Drawer. However, I want the user to be able to choose whether or not to use Wifi or Data before logging in as well as being able to choose once they log in. So I guess this is a two part question, how would you implement this as well as, is it a good idea to put that in the login screen? Or should I just default it to always use wifi unless they change it and if I detect WiFi isn't enabled, have them enable it?
MainActivity.java code
package com.example.jamessingleton.chffrapi;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText emailText;
TextView responseView;
ProgressBar progressBar;
static final String API_KEY = "USE_YOUR_OWN_API_KEY";
static final String API_URL = "https://api.fullcontact.com/v2/person.json?";
static final String ClientId= "";
static final String ClientSecret = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseView = (TextView) findViewById(R.id.responseView);
emailText = (EditText) findViewById(R.id.emailText);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
final Context context = this;
Button queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new RetrieveFeedTask().execute();
Intent intent = new Intent(context, NavDrawerActivity.class);
startActivity(intent);
}
});
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected String doInBackground(Void... urls) {
String email = emailText.getText().toString();
// Do some validation here
try {
URL url = new URL(API_URL + "email=" + email + "&apiKey=" + API_KEY);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
// TODO: check this.exception
// TODO: do something with the feed
// try {
// JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
// String requestID = object.getString("requestId");
// int likelihood = object.getInt("likelihood");
// JSONArray photos = object.getJSONArray("photos");
// .
// .
// .
// .
// } catch (JSONException e) {
// e.printStackTrace();
// }
}
}
}
NavDrawerActivity.java code
package com.example.jamessingleton.chffrapi;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
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.Menu;
import android.view.MenuItem;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class NavDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
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();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
});
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();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nav_drawer, 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();
FragmentManager fragmentSettingsManager = getFragmentManager();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
fragmentSettingsManager.beginTransaction().replace(R.id.content_frame, new SettingsFragment()).commit();
setTitle(R.string.action_settings);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.GONE);
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new FirstFragment()).commit();
setTitle(R.string.speed_graph);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.VISIBLE);
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new SecondFragment()).commit();
setTitle(R.string.drive_player);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.VISIBLE);
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction().replace(R.id.content_frame, new ThirdFragment()).commit();
setTitle(R.string.google_maps);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.VISIBLE);
} else if (id == R.id.nav_share) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Go Check Out All Driving Data in the Play Store!");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Let me know if there is anything else you guys need and thank you guys for all the help :)
Here is the WifivsDataDialog code
package com.example.jamessingleton.chffrapi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
/**
* Created by James Singleton on 8/9/2016.
*/
public class WifivsDataDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_box)
.setPositiveButton(R.string.WiFi, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.Cell_Data, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
It's not entirely clear what you would like to achieve.
Is it mandatory to fetch the data? What if the user has both Wi-Fi and mobile network disabled on the device? What if they choose to use Wi-Fi, but have only mobile network enabled on the device?
I would create a Dialog at the start of the app that explains this stuff and let the user choose if they would like to allow fetching data on mobile network, or Wi-Fi only, with a "Do not show this dialog again" CheckBox.
If the user chooses with the CheckBox checked, then that will be the default behaviour on further launches (and can be changed in the Preferences/Settings).
You could show the Dialog from the onCreate() of your login Activity.
For example:
connection_dialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Would you like to allow fetching data on mobile network?"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yes"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No, allow Wi-Fi only"/>
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:text="OK"/>
</LinearLayout>
ConnectionDialogFragment.java:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ConnectionDialogFragment extends DialogFragment {
public ConnectionDialogFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.connection_dialog, container, false);
// set up your View here
return view;
}
}
And in your Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
// ...
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(prefs.getBoolean("show_dialog", true)) {
showDialog();
}
}
private void showDialog() {
ConnectionDialogFragment dialog = new ConnectionDialogFragment();
dialog.show(getSupportFragmentManager(), "connection_dialog");
}
Check out the developer's guide on Dialogs.
When the user has chosen whether they want to use Wi-Fi only, or allow mobile network also, you could check the available connection with something like this:
// this method will return either
// ConnectivityManager.TYPE_MOBILE
// or
// ConnectivityManager.TYPE_WIFI
// or -1 (if no connection is available)
private int checkAvailableConnectionType() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
int type = activeNetwork.getType();
if(activeNetwork.isConnected() && (type == ConnectivityManager.TYPE_MOBILE ||
type == ConnectivityManager.TYPE_WIFI)) {
return type;
}
return -1;
}
And do your stuff according to the user's choice and the currently active connection (advise the user to turn on Wi-Fi, for example).

dialog fragment: response when entered value

I need help with knowing how to get dialogfragment act when entered a value then pressed okay button or cancel button.
Below are classes ActivityA.java, BasicDialogFragment.java, fragment_basic_dialog.xml and activity_a.xml.
That's all the code you need for this question. Thanks in advance.
ActivityA
package internal.android.com.helloworld;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ActivityA extends ActionBarActivity implements BasicDialogFragment.OnNameEnteredListener {
private Button dialogKnapp = null;
private TextView textA = null;
private TextView textA2 = null;
private EditText editA2 = null;
private Button buttonAB = null;
private Button buttonAC = null;
private Button buttonAD = null;
private Button buttonCancel = null;
private Button buttonOK = null;
private EditText dialog_fornavn = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
dialogKnapp = (Button) findViewById(R.id.dialog_knapp);
buttonCancel = (Button) findViewById(R.id.buttonCancel);
buttonOK = (Button) findViewById(R.id.buttonOK);
dialog_fornavn = (EditText) findViewById(R.id.dialog_fornavn);
textA = (TextView) findViewById(R.id.textA);
textA2 = (TextView) findViewById(R.id.textA2);
editA2 = (EditText) findViewById(R.id.editA2);
buttonAB = (Button) findViewById(R.id.buttonAB);
buttonAC = (Button) findViewById(R.id.buttonAC);
buttonAD = (Button) findViewById(R.id.buttonAD);
Intent intent = getIntent();
String navn = intent.getStringExtra("navnet");
textA2.setText(navn);
buttonAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAB();
}
});
buttonAC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAC();
}
});
buttonAD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAD();
}
});
dialogKnapp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startDialog();
}
});
}
private void startAB() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startAC() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityC.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startAD() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityD.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startDialog() {
BasicDialogFragment bdf = new BasicDialogFragment();
bdf.show(getFragmentManager(), "basic");
}
public void OnFragmentInteractionListener(String nameEntered){
visTekst();
}
private void visTekst() {
if(buttonOK.isPressed()){
textA2.setText(dialog_fornavn.getText());
Toast melding = Toast.makeText(getApplicationContext(),
dialog_fornavn.getText(), Toast.LENGTH_SHORT);
melding.show();
} else if(buttonCancel.isPressed()){
startAB();
}
}
#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) {
// 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.
Toast toast = Toast.makeText(getApplicationContext(), "Activity A",
Toast.LENGTH_SHORT);
switch (item.getItemId()) {
case R.id.menu_item_1:
toast.setText("Activity A");
toast.show();
return true;
case R.id.menu_item_2:
toast.setText("Activity B");
toast.show();
startAB();
return true;
case R.id.menu_item_3:
toast.setText("Activity C");
toast.show();
startAC();
return true;
case R.id.menu_item_4:
toast.setText("Activity D");
toast.show();
startAD();
return true;
case R.id.action_settings:
toast.setText("Settings");
toast.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
BasicDialogFragment.java
import android.app.Activity;
import android.app.DialogFragment;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link BasicDialogFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link BasicDialogFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class BasicDialogFragment extends DialogFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnNameEnteredListener {
public void OnFragmentInteractionListener(String nameEntered);
}
private OnNameEnteredListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment BasicDialogFragment.
*/
// TODO: Rename and change types and number of parameters
public static BasicDialogFragment newInstance(String param1, String param2) {
BasicDialogFragment fragment = new BasicDialogFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public BasicDialogFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_basic_dialog, container, false);
this.getDialog().setTitle("First Name");
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.OnFragmentInteractionListener("uri");
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnNameEnteredListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
fragment_basic_dialog.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" tools:context="no.hit.kvisli.heiverden.BasicDialogFragment"
android:layout_width="match_parent" android:layout_height="match_parent"
android:padding="10dp" android:orientation="vertical" >
<EditText
android:id="#+id/dialog_fornavn"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:textSize="24dp" android:textColor="#android:color/holo_red_dark"
android:hint="Skriv fornavn her" android:inputType="textPersonName" />
<LinearLayout
android:layout_width="match_parent" android:layout_height="wrap_content"
android:padding="10dp" android:orientation="horizontal" >
<Button
android:id="#+id/buttonCancel" android:text="Cancel"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
<Button
android:id="#+id/buttonOK" android:text="OK"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
activity_a.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<LinearLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/farge_A"
tools:context=".ActivityA">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity A"
android:id="#+id/textA"
style="#style/Overskrift"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textA2"
style="#style/Overskrift"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editA2"
style="#style/EditTekst"
android:hint="Skriv noe her"
android:layout_marginLeft="120dp"
android:layout_marginTop="50dp"/>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_marginTop="150dp"
android:layout_marginLeft="50dp"
tools:context=".ActivityA">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dialog"
android:id="#+id/dialog_knapp"
android:background="#color/dialog_knapp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to B"
android:id="#+id/buttonAB"
android:background="#color/farge_B"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to C"
android:id="#+id/buttonAC"
android:background="#color/farge_C"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to D"
android:id="#+id/buttonAD"
android:background="#color/farge_D"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
If I am reading it correctly and your BasicDialogFragment code is like this
then all you need to do is add
public void OnNameEntered(String nameEntered){
//Do Something Here
}
to your ActivityA.java
EDIT
modify the following functions as follows:
private void visTekst(String nameEntered) {
if(buttonOK.isPressed()){
textA2.setText(nameEntered);
Toast melding = Toast.makeText(getApplicationContext(),
dialog_fornavn.getText(), Toast.LENGTH_SHORT);
melding.show();
} else if(buttonCancel.isPressed()){
startAB();
}
}
and call it as
public void OnFragmentInteractionListener(String nameEntered){
visTekst(nameEntered);
}
You need to setup your listeners as it is mentioned in the code that you have used
in your BasicDialogFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_basic_dialog, container, false);
this.getDialog().setTitle("First Name");
buttonCancel = (Button) findViewById(R.id.buttonCancel);
buttonOK = (Button) findViewById(R.id.buttonOK);
buttonCancel.setOnClickListner(new View.OnClickListener(View v){
onButtonPressed(/*Your custom URI*/Uri uri);
});
buttonOK .setOnClickListner(new View.OnClickListener(View v){
onButtonPressed(/*Your custom URI*/Uri uri);
});
return v;
}
For this issue, there are two ways, one is direct cast to hosted Activity to get activity instance. Another is using one interface that defined in DialogFragment but implemented by hosted Activity.
For detail please follow my previous post Call activity from DialogFragment.
//Here is the answer. Took a while but got it to the end, thanks for your help.
//ActivityA
import android.app.FragmentManager;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ActivityA extends ActionBarActivity implements BasicDialogFragment.Communicator {
private Button dialogKnapp = null;
private TextView textA = null;
private TextView textA2 = null;
private EditText editA2 = null;
private Button buttonAB = null;
private Button buttonAC = null;
private Button buttonAD = null;
private EditText dialog_fornavn = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
dialogKnapp = (Button) findViewById(R.id.dialog_knapp);
dialog_fornavn = (EditText) findViewById(R.id.dialog_fornavn);
textA = (TextView) findViewById(R.id.textA);
textA2 = (TextView) findViewById(R.id.textA2);
editA2 = (EditText) findViewById(R.id.editA2);
buttonAB = (Button) findViewById(R.id.buttonAB);
buttonAC = (Button) findViewById(R.id.buttonAC);
buttonAD = (Button) findViewById(R.id.buttonAD);
Intent intent = getIntent();
String navn = intent.getStringExtra("navnet");
textA2.setText(navn);
buttonAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAB();
}
});
buttonAC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAC();
}
});
buttonAD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAD();
}
});
dialogKnapp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startDialog();
}
});
}
private void startAB() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startAC() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityC.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startAD() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityD.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
public void startDialog(){
FragmentManager manager = getFragmentManager();
BasicDialogFragment basicDialogFragment = new BasicDialogFragment();
basicDialogFragment.show(manager,"BasicDialogFragment");
}
#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) {
// 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.
Toast toast = Toast.makeText(getApplicationContext(), "Activity A",
Toast.LENGTH_SHORT);
switch (item.getItemId()) {
case R.id.menu_item_1:
toast.setText("Activity A");
toast.show();
return true;
case R.id.menu_item_2:
toast.setText("Activity B");
toast.show();
startAB();
return true;
case R.id.menu_item_3:
toast.setText("Activity C");
toast.show();
startAC();
return true;
case R.id.menu_item_4:
toast.setText("Activity D");
toast.show();
startAD();
return true;
case R.id.action_settings:
toast.setText("Settings");
toast.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onDialogMessage(Editable message) {
textA2.setText(message);
}
}
//BasicDialogFragment
`import android.app.Activity;
import android.app.DialogFragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class BasicDialogFragment extends DialogFragment implements View.OnClickListener{
private Button buttonCancel = null;
private Button buttonOK = null;
private EditText dialog_fornavn = null;
Communicator communicator;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
communicator= (Communicator) activity;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_basic_dialog, null);
buttonCancel = (Button) v.findViewById(R.id.buttonCancel);
buttonOK = (Button) v.findViewById(R.id.buttonOK);
dialog_fornavn = (EditText) v.findViewById(R.id.dialog_fornavn);
buttonCancel.setOnClickListener(this);
buttonOK.setOnClickListener(this);
setCancelable(true);
return v;
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.buttonOK){
communicator.onDialogMessage(dialog_fornavn.getText());
dismiss();
}
else{
dismiss();
}
}
interface Communicator{
public void onDialogMessage(Editable message);
}
}`
//Thats it, nothing chaged in xml files. Not sure if its good coding but worked for me.

Categories

Resources