I have tried making an app for my website with a webview and progressbar, the visibility of the webview remains hidden till the page loads. Now I have tried adding google admob banner ad at the botton and it isn't showing up, I am using a relativelayout and the ad shows in preview of xml, but not in app.
The activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:visibility="gone" />
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:background="#000000"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-3467064285652442/5673227109">
</com.google.android.gms.ads.AdView>
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
app:layout_constraintStart_toStartOf="#+id/activity_main_webview"
app:layout_constraintTop_toTopOf="#+id/activity_main_webview" />
</RelativeLayout>
The MainActivity.java:
package com.dhruv.spadebee;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ProgressBar;
import android.util.Log;
import android.view.MenuItem;
import android.view.Window;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.PopupMenu;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import android.view.View;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.onesignal.OSNotificationAction;
import com.onesignal.OSNotificationOpenResult;
import com.onesignal.OneSignal;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
String ShowOrHideWebViewInitialUse = "show";
private WebView mWebView;
private ProgressBar spinner;
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setVisibility(View.VISIBLE);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.custom_toolbar);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#080808")));
final ImageView img = (ImageView) findViewById(R.id.toolbar_top);
img.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(MainActivity.this, img);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.one:
mWebView.loadUrl("https://spadebee.com/");
break;
case R.id.two:
mWebView.loadUrl("https://spadebee.com/category/general/");
break;
case R.id.three:
mWebView.loadUrl("https://spadebee.com/category/programming/");
break;
case R.id.four:
mWebView.loadUrl("https://spadebee.com/category/gaming/");
break;
case R.id.five:
mWebView.loadUrl("https://spadebee.com/category/android/");
break;
case R.id.six:
mWebView.loadUrl("https://spadebee.com/about");
break;
}
return true;
}
});
popup.show();//showing popup menu
}
});//closing the setOnClickListener method
OneSignal.startInit(this)
.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
.unsubscribeWhenNotificationsAreDisabled(true)
.setNotificationOpenedHandler(new ExampleNotificationOpenedHandler())
.init();
mWebView = (WebView) findViewById(R.id.activity_main_webview);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Stop local links and redirects from opening in browser instead of WebView
spinner = (ProgressBar)findViewById(R.id.progressBar1);
mWebView.setWebViewClient(new MyAppWebViewClient() {
#Override
public void onPageStarted(WebView webview, String url, Bitmap favicon) {
if (ShowOrHideWebViewInitialUse.equals("show")) {
webview.setVisibility(webview.INVISIBLE);
}
}
#Override
public void onPageFinished(WebView view, String url)
{
mWebView.loadUrl("javascript:(function() { " +
"var head = document.getElementsByClassName('custom-header')[0].style.display='none'; " +
"})()");
mWebView.loadUrl("javascript:(function() { " +
"var head = document.getElementsByClassName('main-navigation')[0].style.display='none'; " +
"})()");
spinner.setVisibility(View.GONE);
mWebView.setVisibility(WebView.VISIBLE);
super.onPageFinished(view, url);
}
});
mWebView.loadUrl("https://spadebee.com/");
}
#Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
// This fires when a notification is opened by tapping on it.
#Override
public void notificationOpened(OSNotificationOpenResult result) {
Log.i("OSNotificationPayload", "result.notification.payload.toJSONObject().toString(): " + result.notification.payload.toJSONObject().toString());
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
String appURL = result.notification.payload.launchURL;
Log.i("appURL", appURL);
mWebView.loadUrl("https://spadebee.com");
mWebView.setWebViewClient(new MyAppWebViewClient());
}
}
public class jparser {
public void main(String[] args) throws IOException {
Validate.isTrue(args.length == 1, "usage: supply url to fetch");
String url = args[0];
Document doc = Jsoup.connect(url).get();
Elements links = doc.select("a[href].more-link");
Elements media = doc.select("img");
Elements summary = doc.select("div.entry-summary");
}
}
}
The preview:
Android Studio preview
Any help as to why it isn't working will be appreciated, I have tried going through all the posts here, adding progresbar and webview in a linear layout, setting adviews visibility to visible but nothing works.
Locking at your log output the last line
I/Ads: Ad failed to load : 3
states that there went something wrong while loading the ad, so there probably is nothing to show?
As stated in this post failed to load ad : 3 regarding error "3":
If you are getting this error, then your code is correct. The issue is that AdMob does not always have an ad to return for every request.
So maybe this is just a temporary problem, have you tried your app on a different device or after a little break?
Also you could try to use the android sample ad ids
https://developers.google.com/admob/android/test-ads#sample_ad_units
they usually work
Related
i have a app set up which loads a website into the app which works fine, when i try to add another element to the content view the app crashes without a error, How can i add more than one element to my set content view? ive tried it with frame layout and more but they all dont seem to work.
Here is my code
package com.example.fiercepcs;
import android.content.Context;
import android.os.Bundle;
import com.example.fiercepcs.databinding.ActivityMainBinding;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.app.Application;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout screenLayout = new LinearLayout(this);
screenLayout.setOrientation(LinearLayout.VERTICAL);
Button button = (Button) findViewById(R.id.button);
WebView myWebView = new WebView(getApplicationContext());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("https://www.fiercepc.co.uk");
setContentView(myWebView);
setContentView(button);
}
}
my activity main xml file
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/Theme.FiercePcs.AppBarOverlay" />
<include
android:id="#+id/include"
layout="#layout/content_main" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:translationZ="-5dp">
</WebView>
<Button
android:id="#+id/button"
android:layout_width="312dp"
android:layout_height="179dp"
android:scaleX="1"
android:scaleY="1"
android:text="#string/button"
android:visibility="visible"
app:layout_anchor="#+id/include"
app:layout_anchorGravity="center" />
</FrameLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
your app crashes because your are trying to set button view and webView as the root layout, don't do that, inflate or bind the root of your layout with ActivityMainBinding
do it like this :
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bindnig = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
LinearLayout screenLayout = new LinearLayout(this);
screenLayout.setOrientation(LinearLayout.VERTICAL);
Button button = (Button) findViewById(R.id.button);
WebView myWebView = new WebView(getApplicationContext());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("https://www.fiercepc.co.uk");
}
}
I am working on an android project that reqires a home screen that I just have image buttons on for the time being, but would like to access different layouts, it access the different layouts just fine, but when using the same code for webview, webview refuses to load and just displays a blank screen, the same code worked fine on the main activity, but is giving me trouble now and im not sure where to go from here, I only have an image on the second activity as a sanity check that my buttons were going to the right places
Main Activity
package com.example.bsc_group;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
ImageButton foodButton = (ImageButton) findViewById(R.id.imageButtonFood);
foodButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
ImageButton techButton = (ImageButton) findViewById(R.id.imageButtonTech);
techButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
ImageButton calendarButton = (ImageButton) findViewById(R.id.imageButtonCalendar);
calendarButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.bcs_calendar_widget);
}
});
}
}
Second activity
package com.example.bsc_group;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class BcsCalendarWidget extends AppCompatActivity {
public WebView webView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
webView = findViewById(R.id.webviewWidget);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://google.com");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
setContentView(R.layout.bcs_calendar_widget);
{
//Spinner spinnerBcsListings = findViewById(R.id.spinner_bcs_group);
//ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.bcs_group_listings, android.R.layout.simple_spinner_item);
//adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
//spinnerBcsListings.setAdapter(adapter);
}
}
#Override
public void onBackPressed() {
if (webView.canGoBack()){
webView.goBack();
}else {
setContentView(R.layout.activity_main);}
}
}
XML file for second activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:id="#+id/webviewWidget"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_launcher_foreground" />
</RelativeLayout>
The issue is that you are not opening the activity. Only giving a context view without executing the code. This bad. Whenever you want to go to another activity, use this code:
Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
Also in the onBackpressed I see that you are just doing setContentView. Don't do that. Use this instead:
finish();
I am creating a Webview application and I need to add Splash Screen at load time.
I tried different ways, with this it "starts", but after Splash Screen it just turns off. What can I do to make the application show Splash Screen and open correctly?
SplashScreen.java:
package com.example.evrika;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SplashScreen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(SplashScreen.this,MainActivity.class));
finish();
}
},1000);
}
}
activity_main.xml:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java:
package com.example.evrika;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
WebView webView = findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(false);
webView.getSettings().setSupportZoom(false);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.loadUrl("https://evrikaspace.ru/");
WebViewClient webViewClient = new WebViewClient() {
#SuppressWarnings("deprecation") #Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#TargetApi(Build.VERSION_CODES.N) #Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.getUrl().toString());
return true;
}
};
webView.setWebViewClient(webViewClient);
}
}
Probably this line is making noise getSupportActionBar().hide();
This question already has answers here:
Null pointer Exception - findViewById()
(12 answers)
Closed 2 years ago.
This is my first post so apologies if I get any of the formalities wrong...
Before anyone tells me the question is invalid, every solution I have looked at says I should have:
setContentView(R.layout.whateverViewImCurrentlyTryingToFocus)
before I call a
findViewById()
When I debug my application it is crashing when I set up an onClickListener for my button (R.id.sign_in_button), line 75.
So I decided to check what findViewById() was returning so I run the code
Button button = findViewById(R.id.sign_in_button)
This caused the same error. I think it it returning null but not entirely sure.
Activitylogin.xml is the first layout to be loaded, and then the mainactivity.xml is supposed to launch after a firebase sign-in.
Java code:
LoginActivity.java
package com.styryl.socials.ui.login;
import android.app.Activity;
import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.snackbar.Snackbar;
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.styryl.socials.MainActivity;
import com.styryl.socials.R;
import com.styryl.socials.ui.login.LoginViewModel;
import com.styryl.socials.ui.login.LoginViewModelFactory;
public class LoginActivity extends AppCompatActivity {
private LoginViewModel loginViewModel;
private FirebaseAuth mAuth;
private GoogleSignInClient mGoogleSignInClient;
private final static int RC_SIGN_IN = 1;
private String TAG = "Login Activity";
#Override
protected void onStart() {
super.onStart();
FirebaseUser user = mAuth.getCurrentUser();
if(user != null){
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
createRequest();
// Button findViewByID returns null
findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
}
private void createRequest() {
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
firebaseAuthWithGoogle(account.getIdToken());
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
// ...
}
}
}
private void firebaseAuthWithGoogle(String idToken) {
AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication Failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
MainActivity.java
package com.styryl.socials;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.styryl.socials.ui.login.LoginActivity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
public class MainActivity extends AppCompatActivity {
TextView user_username;
TextView user_email;
Button logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_username = findViewById(R.id.user_username);
user_email = findViewById(R.id.user_email);
logout = findViewById(R.id.logout_button);
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.navigation_home, R.id.navigation_dashboard, R.id.navigation_profile)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(this);
if(signInAccount != null){
user_username.setText(signInAccount.getDisplayName());
user_email.setText(signInAccount.getEmail());
}
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
});
}
}
Layout Files:
LoginActivity.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".ui.login.LoginActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/status_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="110dp"
android:layout_height="wrap_content"
android:text="Sign Out"
android:id="#+id/sign_out_button" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.xml
<?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"
android:background="#color/colorDarkGrey"
android:paddingTop="?attr/actionBarSize">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
app:itemIconTint="#drawable/bottom_navigation_selector"
app:itemTextColor="#drawable/bottom_navigation_selector"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark"
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>
If you need anymore information please let me know and I will provide. I can't wrap my head around this issue and really hope some android studio experts can explain it to me as if I'm a idiot because I would love to learn!
I am attempting to fix this as soon as I wake up, because I never quit!
All,
Thank you for your replies,
I woke up this morning and after looking at the logcat as suggested by #Frank van puffelen, I noticed that the error was a nullPointerException on a textView. This was weird becuase there was no textView in my loginActivity. Upon further inspection, I hadn't created the username and the email textView in my main_activity.xml (Problem with late night coding, I should have spotted that). So this was returning a nullPointerException simply because it didn't exist. I added the username, email and logout button to the xml and it works.
Thanks for the help, not entirely sure how to close this thread (this is my first post), apologies for wasting time but I was a little desperate.
My app is a fullscreen activity. It is a webview app and I wanted to add three tabs to make each tab open a different site.
Here is my main activity java
package com.wEgyptpost.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.widget.TextView;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import java.util.Random;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.wEgyptpost.app.R;
public class MainActivity extends Activity {
WebView view;
SwipeRefreshLayout mySwipeRefreshLayout;
ProgressBar progressBar;
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AdView adView = (AdView) findViewById(R.id.admob_id);
AdRequest adRequest = new AdRequest.Builder()
.setRequestAgent("android_studio:ad_template").build();
adView.loadAd(adRequest);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
progressBar= (ProgressBar)findViewById(R.id.progressBar);
final SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipelayout);
final WebView mWebView = (WebView) findViewById(R.id.activity_main_webview);
swipeRefreshLayout.setColorSchemeResources(R.color.refresh,R.color.refresh1,R.color.refresh2);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mWebView.reload();
swipeRefreshLayout.setRefreshing(true);
(new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
mWebView.stopLoading();
swipeRefreshLayout.setRefreshing(false);
}
},20000);
}
});
// Force links and redirects to open in the WebView instead of in a browser
//mWebView.setWebViewClient(new WebViewClient());
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
// Use remote resource
mWebView.loadUrl("www.google.com");
// Stop local links and redirects from opening in browser instead of WebView
mWebView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(final WebView view, String url) {
progressBar.setVisibility(View.GONE);
swipeRefreshLayout.setRefreshing(false);
}
} );
// Use local resource
//mWebView.loadUrl("file:android_asset/web/google.html");
}
// Prevent the back-button from closing the app
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} 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.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);
}
}
And this is the activity xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ScrollView>
</android.support.v4.widget.SwipeRefreshLayout >
<com.google.android.gms.ads.AdView android:id="#+id/admob_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-1851250777225639/8300259415"
android:layout_gravity="center_horizontal|bottom" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_gravity="center" />
</FrameLayout>