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.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to an app for login app for emplyees, I have made three activities MainActivity, Register and Login. I have only designed the register activity and an onclick listener in login, and if the user is not logged in, the user is directed to Login, and an onclick listener to Register.Java, There is no error but the app keeps crashing and whenever i am opening the app in the emulator, the app does not open and it shows the this app keeps stopping.
MainActivity.java
package com.example.employeedatabase;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
FirebaseUser currentUser;
public void updateUI(FirebaseUser account){
if(account != null){
Toast.makeText(this,"U Signed In successfully",Toast.LENGTH_LONG).show();
startActivity(new Intent(this,this.getClass()));
}else {
Toast.makeText(this,"U Didnt signed in", Toast.LENGTH_LONG).show();
startActivity(new Intent(this,Login.class));
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
mAuth = FirebaseAuth.getInstance();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
}
Login.java
package com.example.employeedatabase;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class Login extends AppCompatActivity {
TextView Nuser = findViewById(R.id.new_user);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Nuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Login.this, Register.class);
startActivity(intent);
}
});
}
}
And at last there is Register.java
package com.example.employeedatabase;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.tabs.TabLayout;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class Register extends AppCompatActivity {
private FirebaseAuth mAuth;
private static final String TAG = "Register";
public void updateUI(FirebaseUser account){
if(account != null){
Toast.makeText(this,"U Signed In successfully",Toast.LENGTH_LONG).show();
startActivity(new Intent(this,this.getClass()));
}else {
Toast.makeText(this,"U Didnt signed in", Toast.LENGTH_LONG).show();
startActivity(new Intent(this,Login.class));
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
String email = findViewById(R.id.email).toString();
String password = findViewById(R.id.password).toString();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "createUserWithEmail : Success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
}
else {
Log.w(TAG, "createUserWithEmail : Failure", task.getException());
Toast.makeText(Register.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});
}
}
I want that if the user is not logged in it should open login.java, and if user click this text 'New User?, Sign In!'
I want the user to go to the Register.java
My Activity_register.xml is as follows.-
<?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=".Register">
<TextView
android:id="#+id/textView2"
android:layout_width="228dp"
android:layout_height="52dp"
android:text="Register"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.743"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.048" />
<EditText
android:id="#+id/email"
android:layout_width="263dp"
android:layout_height="39dp"
android:ems="10"
android:hint="Email"
android:inputType="textEmailAddress"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.479"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2"
app:layout_constraintVertical_bias="0.187" />
<EditText
android:id="#+id/password"
android:layout_width="257dp"
android:layout_height="40dp"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/email"
app:layout_constraintVertical_bias="0.14" />
<Button
android:id="#+id/Rdone"
android:layout_width="143dp"
android:layout_height="60dp"
android:layout_marginTop="20dp"
android:text="Register"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/password"
app:layout_constraintVertical_bias="0.24000001" />
</androidx.constraintlayout.widget.ConstraintLayout>
In your login activity, You cannot put this TextView Nuser = findViewById(R.id.new_user); initialization at top level. it should be in oncreate method like this:
package com.example.employeedatabase;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class Login extends AppCompatActivity {
TextView Nuser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Nuser = (TextView) findViewById(R.id.new_user);
Nuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Login.this, Register.class);
startActivity(intent);
}
});
}
}
Note: You should put your logcat error in your question to get to the issue quickly or to solve any other issue which exists.
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
I am trying to get data from my firebase firestore and everything seems correct to me but I am getting blank on my text view.I am also not getting any error in the logs related to the profile activity and class.I have used firestore the same way in my other application and it worked perfectly fine there.enter image description here
it would be amazing if you guys could help me as I am stalled because of this error.
My logcat
2020-05-29 14:53:38.381 4280-4280/? E/Zygote: v2
2020-05-29 14:53:38.385 4280-4280/? E/Zygote: accessInfo : 0
2020-05-29 14:53:43.495 4280-4280/com.example.feedme E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib64, /vendor/lib64]]
My java code:
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class profile extends AppCompatActivity {
TextView namea;
CircleImageView circleImageView;
BottomNavigationView bottomNavigationView;
String user_id;
String url;
FirebaseFirestore fStore;
FirebaseAuth fAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Toast.makeText(this, user_id, Toast.LENGTH_SHORT).show();
circleImageView = findViewById(R.id.profilepictureuser);
Picasso.with(this).load(url).resize(400, 400).centerCrop().into(circleImageView);
namea = findViewById(R.id.profilename);
fStore = FirebaseFirestore.getInstance();
fAuth = FirebaseAuth.getInstance();
user_id = fAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("User data").document(user_id);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
namea.setText(documentSnapshot.getString("Full name"));
}
});
bottomNavigationView = findViewById(R.id.bottom_navigation1);
bottomNavigationView.setSelectedItemId(R.id.profilelogo);
bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
switch (item.getItemId()) {
case R.id.profilelogo:
return true;
case R.id.home:
startActivity(new Intent(getApplicationContext(), homepage.class));
return true;
}
return false;
});
}
}
[enter image description here][1]
The layout file for the profile
<?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=".profile">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/linearlayout"
android:orientation="vertical">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:src="#drawable/profile"
android:id="#+id/profilepictureuser"
android:layout_gravity="center"
android:layout_marginTop="30dp"/>
<TextView
android:id="#+id/profilename"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:textColor="#000000"
android:textSize="24sp" />
</LinearLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bottom_navigation1"
android:background="#047cfb"
app:itemIconTint="#ffffff"
app:itemTextColor="#ffffff"
app:menu="#menu/menu_navigation"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
My firestore collection:
I added a toast to check the user_id here's the screeshot and the code is updated btw
enter image description here
In this code i need to apply jingle when the video is getting downloaded from the server to mobile device
code : This the main activity which is java file where the videos are downloaded from server and getting situated in android device and will be played in video view
MainActivity.java
package ivmshd.mcu.com.demo;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.VideoView;
import java.io.File;
import static android.R.attr.path;
public class MainActivity extends AppCompatActivity {
private long enqueue;
private DownloadManager dm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
VideoView view= (VideoView) findViewById(R.id.videoView);
enter code here
String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
view.setVideoURI(Uri.parse(uriString));
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClick(View view) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request =new DownloadManager.Request(Uri.parse("http://eZeeReview.com/login/pages/examples/video/1.mp4"));
enqueue = dm.enqueue(request);
final VideoView videoView;
videoView = (VideoView) findViewById(R.id.videoView);
Uri video = Uri.parse("http://eZeeReview.com/login/pages/examples/video/1.mp4");
videoView.setVideoURI(video);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
videoView.start();
}
});
}
public void showDownload(View view) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
}
XML File: In this code the widgets are applied
widgets are like Video view and 2 buttons
where videos are played in video view.This videos are the videos which are fetched from server
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:text="Start Download" android:id="#+id/button1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:onClick="onClick"></Button>
<Button android:text="View Downloads" android:id="#+id/button2"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:onClick="showDownload"></Button>
<VideoView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/videoView" />
</LinearLayout>
I want to add a button to one of my activities (that displays a news article), so when the user clicks the button the article is opened in their browser. So far I have added the button in my xml and it appears. I'm just having some trouble with the click listener. Below is my code, i'm getting an error for 'setOnClickListener' which is 'Non-static method 'setOnClickListener(android.view.View.onClickListener)' cannot be referenced from a static content.
I'm not sure what this means! maybe i'm not calling the method in the right place or there is just an error with the method itself?
Please could someone take a look, thanks!
import android.content.Intent;
import android.media.Image;
import android.net.Uri;
import android.support.v4.app.ShareCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ShareActionProvider;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.View.OnClickListener;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import org.json.JSONException;
import org.json.JSONObject;
public class NewsItemActivity extends AppCompatActivity {
//Declare java object for the UI elements
private TextView itemTitle;
private TextView itemDate;
private TextView itemContent;
private NetworkImageView itemImage;
private ShareActionProvider mShareActionProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_item);
itemTitle = (TextView) findViewById(R.id.itemTitle);
itemDate = (TextView) findViewById(R.id.itemDate);
itemContent = (TextView) findViewById(R.id.itemContent);
itemImage = (NetworkImageView) findViewById(R.id.itemImage);
EDANewsApp app = EDANewsApp.getInstance();
Intent intent = getIntent();
int itemId = intent.getIntExtra("newsItemId", 0);
String url = "http://www.efstratiou.info/projects/newsfeed/getItem.php?id="+itemId;
JsonObjectRequest request = new JsonObjectRequest(url, listener, errorListener);
app.requestQueue.add(request);
Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = getIntent();
int itemId = intent.getIntExtra("newsItemId", 0);
String shareUrl = "http://www.efstratiou.info/projects/newsfeed/getItem.php?id=" + itemId;
Intent buttonIntent = new Intent();
buttonIntent.setAction(Intent.ACTION_VIEW);
buttonIntent.addCategory(Intent.CATEGORY_BROWSABLE);
buttonIntent.setData(Uri.parse(shareUrl));
startActivity(buttonIntent);
}
});
};
activity_news_item.xml
<RelativeLayout 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"
tools:context=".NewsItemActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/itemTitle"
android:layout_margin="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#3183b9"/>
<TextView
android:id="#+id/itemDate"
android:layout_marginLeft="15dp"
android:layout_marginBottom="15dp"
android:textSize="16sp"
android:textStyle="italic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/itemImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/itemContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:textSize="16sp"
/>
<Button
android:id="#+id/BrowserButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View in browser"
android:layout_marginLeft="15dp"
style="#style/BrowserButton"
/>
</LinearLayout>
</ScrollView>
</RelativeLayout>
Change
Button.setOnClickListener(new View.OnClickListener() { ... });
to
Button button = (Button) findViewById(R.id.BrowserButton);
button.setOnClickListener(new View.OnClickListener() { ... });
You need to call the setOnClickListener method on an instance of Button, not on the class itself.
The problem is this :
Button.setOnClickListener(new View.OnClickListener() {
You have to declare it out of onCreate() as you did with your Textviews as :
Button btn;
Why?
Because if you put it on onCreate() you wont be able to use this object out of onCreate() so it's recomendable to put it as a public object.
Then in your onCreate() do this :
btn = (Button)findViewById(R.id.BrowserButton);
Then you do the OnclickListener() as follows :
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = getIntent();
int itemId = intent.getIntExtra("newsItemId", 0);
String shareUrl = "http://www.efstratiou.info/projects/newsfeed/getItem.php?id=" + itemId;
Intent buttonIntent = new Intent();
buttonIntent.setAction(Intent.ACTION_VIEW);
buttonIntent.addCategory(Intent.CATEGORY_BROWSABLE);
buttonIntent.setData(Uri.parse(shareUrl));
startActivity(buttonIntent);
}
});
I'm still getting an error for onClickListener, saying it 'cannot resolve symbol'.
Make sure that you've imported this :
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
You can do it doing this :
Add implements OnClickListener { as follows :
public class NewsItemActivity extends AppCompatActivity implements View.OnClickListener {
Then on your Button you do this :
btn = (Button)findViewById(R.id.BrowserButton);
btn.setOnClickListener(this);
Then add a switch case as follows :
public void onClick(View v) {
switch(v.getId()) {
case R.id.BrowserButton:
Intent intent = getIntent();
int itemId = intent.getIntExtra("newsItemId", 0);
String shareUrl = "http://www.efstratiou.info/projects/newsfeed/getItem.php?id=" + itemId;
Intent buttonIntent = new Intent();
buttonIntent.setAction(Intent.ACTION_VIEW);
buttonIntent.addCategory(Intent.CATEGORY_BROWSABLE);
buttonIntent.setData(Uri.parse(shareUrl));
startActivity(buttonIntent);
}
break;
}
}