Chat with Firestore crashes with NullPointerException on RecyclerView.setHasFixedSize - android

I am pretty new to RecyclerView, so please forgive me if the resolution is very simple. I digged around but no luck so I need guidance.
Adapting the Chat with FirebaseUI with Firestore grabbing the code from https://github.com/firebase/FirebaseUI-Android.
Here is the main code:
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.auth.util.ui.ImeHelper;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Class demonstrating how to setup a {#link RecyclerView} with an adapter while taking sign-in
* states into consideration. Also demonstrates adding data to a ref and then reading it back using
* the {#link FirestoreRecyclerAdapter} to build a simple chat app.
* <p>
* For a general intro to the RecyclerView, see <a href="https://developer.android.com/training/material/lists-cards.html">Creating
* Lists</a>.
*/
public class BlaBlaBlaChat extends AppCompatActivity
implements FirebaseAuth.AuthStateListener {
private static final String TAG = "BlaBlaBlaChat";
private static final CollectionReference sChatCollection =
FirebaseFirestore.getInstance().collection("chats");
/** Get the last 50 chat messages ordered by timestamp . */
private static final Query sChatQuery = sChatCollection.orderBy("timestamp").limit(50);
static {
FirebaseFirestore.setLoggingEnabled(true);
}
#BindView(R.id.messagesList)
RecyclerView mRecyclerView;
#BindView(R.id.sendButton)
Button mSendButton;
#BindView(R.id.messageEdit)
EditText mMessageEdit;
#BindView(R.id.emptyTextView)
TextView mEmptyListMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ireland_chat);
ButterKnife.bind(this);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
ImeHelper.setImeOnDoneListener(mMessageEdit, new ImeHelper.DonePressedListener() {
#Override
public void onDonePressed() {
onSendClick();
}
});
}
#Override
public void onStart() {
super.onStart();
if (isSignedIn()) { attachRecyclerViewAdapter(); }
FirebaseAuth.getInstance().addAuthStateListener(this);
}
#Override
protected void onStop() {
super.onStop();
FirebaseAuth.getInstance().removeAuthStateListener(this);
}
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth auth) {
mSendButton.setEnabled(isSignedIn());
mMessageEdit.setEnabled(isSignedIn());
if (isSignedIn()) {
attachRecyclerViewAdapter();
} else {
Toast.makeText(this, R.string.signing_in, Toast.LENGTH_SHORT).show();
auth.signInAnonymously().addOnCompleteListener(new BlaBlaBlaChatSignInHolder(this));
}
}
private boolean isSignedIn() {
return FirebaseAuth.getInstance().getCurrentUser() != null;
}
private void attachRecyclerViewAdapter() {
final RecyclerView.Adapter adapter = newAdapter();
// Scroll to bottom on new messages
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
mRecyclerView.smoothScrollToPosition(adapter.getItemCount());
}
});
mRecyclerView.setAdapter(adapter);
}
#OnClick(R.id.sendButton)
public void onSendClick() {
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
String name = "User " + uid.substring(0, 6);
onAddMessage(new BlaBlaBlaChatAbstractExtend(name, mMessageEdit.getText().toString(), uid));
mMessageEdit.setText("");
}
protected RecyclerView.Adapter newAdapter() {
FirestoreRecyclerOptions<BlaBlaBlaChatAbstractExtend> options =
new FirestoreRecyclerOptions.Builder<BlaBlaBlaChatAbstractExtend>()
.setQuery(sChatQuery, BlaBlaBlaChatAbstractExtend.class)
.setLifecycleOwner(this)
.build();
return new FirestoreRecyclerAdapter<BlaBlaBlaChatAbstractExtend, BlaBlaBlaChatHolder>(options) {
#Override
public BlaBlaBlaChatHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new BlaBlaBlaChatHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.message, parent, false));
}
#Override
protected void onBindViewHolder(#NonNull BlaBlaBlaChatHolder holder, int position, #NonNull BlaBlaBlaChatAbstractExtend model) {
holder.bind(model);
}
#Override
public void onDataChanged() {
// If there are no chat messages, show a view that invites the user to add a message.
mEmptyListMessage.setVisibility(getItemCount() == 0 ? View.VISIBLE : View.GONE);
}
};
}
protected void onAddMessage(BlaBlaBlaChatAbstractExtend chat) {
sChatCollection.add(chat).addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "Failed to write message", e);
}
});
}
And here is the xml:
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.balblabla.BlaBlaBlaChat">
<TextView
android:id="#+id/emptyTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="#string/start_chatting" />
<android.support.v7.widget.RecyclerView
android:id="#+id/messagesList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_above="#+id/footer"
android:clipToPadding="false"
android:padding="16dp"
tools:listitem="#layout/ireland_chat_message" />
<LinearLayout
android:id="#+id/footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:paddingStart="16dp"
android:paddingEnd="16dp"
android:paddingLeft="16dp"
android:orientation="horizontal">
<EditText
android:id="#+id/messageEdit"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:imeOptions="actionDone"
android:inputType="text" />
<Button
android:id="#+id/sendButton"
style="#style/Widget.AppCompat.Button.Borderless.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:text="#string/send" />
</LinearLayout>
</RelativeLayout>
From logcat:
01-12 18:07:36.443 31599-31599/com.example.carlo.blablabla E/UncaughtException: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.carlo.blablabla/com.example.carlo.blablabla.BlaBlaBlaChat}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
at com.example.carlo.blablabla.BlaBlaBlaChat.onCreate(BlaBlaBlaChat.java:73)
at android.app.Activity.performCreate(Activity.java:6681)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2677)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527) 
at android.os.Handler.dispatchMessage(Handler.java:110) 
at android.os.Looper.loop(Looper.java:203) 
at android.app.ActivityThread.main(ActivityThread.java:6251) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924) 
01-12 18:07:36.715 31599-31599/com.example.carlo.blablabla E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.carlo.blablabla, PID: 31599
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.carlo.blablabla/com.example.carlo.blablabla.BlaBlaBlaChat}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
at com.example.carlo.blablabla.BlaBlaBlaChat.onCreate(BlaBlaBlaChat.java:73)
at android.app.Activity.performCreate(Activity.java:6681)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2677)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527) 
at android.os.Handler.dispatchMessage(Handler.java:110) 
at android.os.Looper.loop(Looper.java:203) 
at android.app.ActivityThread.main(ActivityThread.java:6251) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924) 
Gradle Project
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath 'com.google.gms:google-services:3.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
google()
maven {
url "https://maven.google.com" // Google's Maven repository
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Gradle APP:
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
buildToolsVersion '26.0.2'
defaultConfig {
applicationId "com.example.blablabla.albalbalb"
minSdkVersion 19
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:27.0.2'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile 'com.google.android.gms:play-services-location:11.8.0'
compile 'com.google.android.gms:play-services-maps:11.8.0'
compile 'com.google.firebase:firebase-core:11.8.0'
compile 'com.google.firebase:firebase-auth:11.8.0'
compile 'com.google.firebase:firebase-firestore:11.8.0'
compile 'com.google.firebase:firebase-storage:11.8.0'
implementation 'com.android.support:cardview-v7:27.0.2'
implementation 'com.android.support:recyclerview-v7:27.0.2'
compile 'de.hdodenhof:circleimageview:1.3.0'
compile 'com.google.android.gms:play-services-appinvite:11.8.0'
compile 'com.google.firebase:firebase-messaging:11.8.0'
compile 'com.google.android.gms:play-services-ads:11.8.0'
compile 'com.google.firebase:firebase-appindexing:11.8.0'
compile 'com.google.firebase:firebase-crash:11.8.0'
compile 'com.google.firebase:firebase-analytics:11.8.0'
compile 'com.android.support:design:27.0.2'
compile 'com.github.bumptech.glide:glide:4.3.1'
compile 'com.google.firebase:firebase-database:11.8.0'
compile 'com.google.firebase:firebase-config:11.8.0'
compile 'com.firebaseui:firebase-ui-database:3.1.3'
compile 'com.firebaseui:firebase-ui-auth:3.1.3'
implementation 'com.firebaseui:firebase-ui-firestore:3.1.3'
implementation 'com.firebaseui:firebase-ui-storage:3.1.3'
compile 'com.google.android.gms:play-services-auth:11.8.0'
implementation 'com.jakewharton:butterknife:8.8.1'
// Testing dependencies
androidTestCompile 'com.android.support.test:runner:1.0.1'
androidTestCompile 'com.android.support:support-annotations:27.0.2'
}
apply plugin: 'com.google.gms.google-services'
The code is just a cut/paste from the Github code, but something went wrong.

It looks like you didn't add the ButterKnife library to your project correctly.
In your app's build.gradle file, you must add the annotationProcessor after implementation "com.jakewharton:butterknife:8.8.1" like this:
annotationProcessor "com.jakewharton:butterknife-compiler:8.8.1"
And in your project's build.gradle file add the ButterKnife plugin to your buildscript:
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath 'com.google.gms:google-services:3.1.0'
classpath 'com.jakewharton:butterknife-gradle-plugin:8.8.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}

You are using mRecyclerView which is never initialized and that's why you are getting that error. In order to solve this, you must first initialize it before you use it. Assuming that the id of your RecyclerView is recycler_view, please use the following code in your onCreate() method:
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);

Related

Unable to Sign in with google

I have to add sign in with google feature to my app. I have tried several tutorials but nothing works. Whenever I select an account from the list, that pop up gets closed and nothing happens. I don't know what is the problem since there is no errors showing on the logcat.
Login.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
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.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;
public class Login extends AppCompatActivity {
GoogleSignInClient mGoogleSignInClient;
FirebaseAuth auth;
RelativeLayout googlesignin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this,gso);
googlesignin = (RelativeLayout) findViewById(R.id.googlesignin);
googlesignin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, 101);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 101) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
auth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = auth.getCurrentUser();
Intent i = new Intent(getApplicationContext(),Homewindow.class);
startActivity(i);
finish();
Toast.makeText(getApplicationContext(),"User Logged In Successfully",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(),"Login Failed",Toast.LENGTH_SHORT).show();
}
}
});
}
}
activity_login
<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"
android:background="#00BFFF"
android:orientation="vertical"
android:scrollbarAlwaysDrawVerticalTrack="true">
<RelativeLayout
android:id="#+id/loginmain"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/logincontents"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#drawable/relativelayout_custom"
android:orientation="vertical"
android:padding="20dp">
<RelativeLayout
android:id="#+id/googlesignin"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="40dp"
android:orientation="horizontal"
android:background="#drawable/loginlayout">
<ImageView
android:id="#+id/googleicon"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:src="#drawable/googleicon"/>
<TextView
android:id="#+id/googletext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_centerVertical="true"
android:layout_toRightOf="#id/googleicon"
android:fontFamily="#font/averia_gruesa_libre"
android:text="Sign in with Google"
android:textColor="#db3236"
android:textSize="14dp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/facebooksignin"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:layout_below="#id/googlesignin"
android:layout_marginTop="40dp"
android:background="#drawable/loginlayout">
<ImageView
android:id="#+id/facebookicon"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:src="#drawable/facebookicon"/>
<TextView
android:id="#+id/facebooktext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:fontFamily="#font/averia_gruesa_libre"
android:layout_toRightOf="#id/facebookicon"
android:text="Sign in with Facebook"
android:textColor="#3b5998"
android:textSize="14dp"
android:textStyle="bold" />
</RelativeLayout>
<TextView
android:id="#+id/skipbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/facebooksignin"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:fontFamily="#font/averia_gruesa_libre"
android:paddingTop="5dp"
android:text="SKIP NOW >>"
android:textColor="#00BFFF"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/profileicon"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="40dp"
android:layout_above="#id/logincontents">
<androidx.appcompat.widget.AppCompatImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_centerHorizontal="true"
android:src="#drawable/profile_icon"/>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
Here I used onClickListener for the Relative layout containing googleicon and text.
build.gradle (app)
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.1"
defaultConfig {
vectorDrawables.useSupportLibrary = true
applicationId "com.example.parethumukal"
minSdkVersion 18
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.firebase:firebase-auth:18.1.0'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
//noinspection GradleCompatible
implementation "com.google.android.material:material:1.0.0-rc01"
implementation 'com.github.bumptech.glide:glide:4.3.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1'
//noinspection GradleCompatible
def lifecycle_version = "2.0.0"
// ViewModel and LiveData
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
implementation files('libs\\YouTubeAndroidPlayerApi.jar')
implementation 'com.google.firebase:firebase-core:17.0.0'
implementation 'com.google.firebase:firebase-database:18.0.0'
implementation 'com.google.firebase:firebase-storage:18.1.0'
implementation 'de.hdodenhof:circleimageview:3.0.0'
}
apply plugin: 'com.google.gms.google-services'
build.gradle(project)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.2'
classpath 'com.google.gms:google-services:4.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
maven {
url "https://maven.google.com"
}
maven { url 'https://jitpack.io' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
logcat error
07-23 21:48:22.994 21934-21934/com.example.parethumukal E/MultiWindowProxy: getServiceInstance failed!
07-23 21:48:27.924 21934-21982/com.example.parethumukal E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb37a4d60
I don't know if any errors with my codes. Codes are taken from firebase site.
Try this
GoogleSignInOptions gso;
GoogleApiClient googleApiClient;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.firebase_web_client_id))
.requestEmail()
.build();
googleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.enableAutoManage(this, null)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}

AppCompatImageButton cannot be cast to android.widget.Button even though it's not an ImageButton

I'm getting an error that I can't understand:
07-19 22:14:50.750 23192-23192/com.example.shun.zeatbeta E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.shun.zeatbeta, PID: 23192
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.shun.zeatbeta/com.example.shun.zeatbeta.ReauthenticateActivity}: java.lang.ClassCastException: android.support.v7.widget.AppCompatImageButton cannot be cast to android.widget.Button
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: java.lang.ClassCastException: android.support.v7.widget.AppCompatImageButton cannot be cast to android.widget.Button
at com.example.shun.zeatbeta.ReauthenticateActivity.onCreate(ReauthenticateActivity.java:59)
at android.app.Activity.performCreate(Activity.java:6942)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2880)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988) 
at android.app.ActivityThread.-wrap14(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6682) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410) 
Line that crashes program in activity:
private Button loginButton;
loginButton = (Button) findViewById(R.id.loginButton);
activity_reauthenticate2.xml:
<com.example.shun.zeatbeta.ComfortaaButton
android:id="#+id/loginButton"
android:layout_width="match_parent"
android:layout_height="#dimen/button_height"
android:layout_marginTop="20dp"
android:background="#drawable/round_button_blue"
android:text="#string/login"
android:textColor="#color/white"
android:textSize="15dp"
app:layout_constraintBottom_toTopOf="#id/facebookWrapper"
app:layout_constraintTop_toBottomOf="#id/textFields" />
ComfortaaButton.java
package com.example.shun.zeatbeta;
import android.content.Context;
import android.graphics.Typeface;
import android.support.v7.widget.AppCompatButton;
import android.util.AttributeSet;
public class ComfortaaButton extends AppCompatButton {
public ComfortaaButton(Context context) {
super(context);
init();
}
public ComfortaaButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ComfortaaButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void init() {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font/Comfortaa-Regular.ttf");
setTypeface(tf, 1);
}
}
Why am I getting this error? The button is clearly a Button, not an ImageButton. I've tried cleaning project, restarted, clearing cache, etc. I even tried creating a new activity and layout file, and the error came back!
UPDATE: I got this info for the line in activity crashing the code:
Unexpected cast to AppCompatButton: layout tag was ImageButton (Id bound to an ImageButton in activity_landing_page.xml) less... (⌘F1)
Keeps track of the view types associated with ids and if it finds a usage of the id in the Java code it ensures that it is treated as the same type.
So it seems like it looks for activities by id in activity_landing_page.xml instead of in activity_reauthenticate2.xml. Why? How can I change that?
the app gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
buildToolsVersion '27.0.3'
defaultConfig {
applicationId "com.example.s.company"
minSdkVersion 17
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation 'com.android.support:support-v4:27.1.1'
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
implementation 'com.facebook.android:facebook-android-sdk:4.33.0'
implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.github.bumptech.glide:glide:4.7.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
implementation 'com.stripe:stripe-android:6.1.2'
compile 'com.google.firebase:firebase-auth:15.0.0'
compile 'com.google.firebase:firebase-core:15.0.0'
compile 'com.google.firebase:firebase-database:15.0.0'
compile 'com.google.firebase:firebase-storage:15.0.0'
compile 'com.firebaseui:firebase-ui-storage:3.3.1'
compile 'com.android.volley:volley:1.1.0'
compile 'com.felipecsl.asymmetricgridview:library:2.0.1'
compile 'com.google.android.gms:play-services-maps:15.0.1'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
compile 'com.github.ittianyu:BottomNavigationViewEx:1.2.1'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.android.support.constraint:constraint-layout:1.1.0'
compile 'com.github.arimorty:floatingsearchview:2.1.1'
implementation 'info.hoang8f:android-segmented:1.0.6'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
There must be are other duplicate id for your loginButton. Just make sure that you will get the correct import when you type R.id.loginButton from loginButton = (Button) findViewById(R.id.loginButton); for your target Activity or xml.
Update:
Button should also work fine.
Initiating the view as AppCompatButton,
private AppCompatButton mLoginButton;
mLoginButton=findViewById(R.id.loginButton);
//This error occured when I mistakenly coded
val deleteButton = itemView.findViewById<(Button)>(R.id.item_delete_button)
//Actually in the XML file I used a Image View instead of a Button to make that image //clickable.
// So I changed the <(Button)> to <(ImageView)>. Then this problem was resolved.

Firebase App is crashing

I'm following this tutorial:- https://www.youtube.com/watch?v=x0ScnHJi8WY
and I don't know, why my app is crashing
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="com.vks_apps.blogs.MainActivity">
</RelativeLayout>
MainActivity.java
package com.vks_apps.blogs;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if(item.getItemId()==R.id.action_add)
{
startActivity(new Intent(MainActivity.this,PostActivity.class));
}
return super.onOptionsItemSelected(item);
}
}
activity_post.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="com.vks_apps.blogs.PostActivity">
<ImageButton
android:id="#+id/imageSelect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:adjustViewBounds="true"
android:background="#00ffffff"
android:scaleType="centerCrop"
android:src="#mipmap/add_btn" />
<EditText
android:id="#+id/titleField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageSelect"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="#drawable/input_outline"
android:hint="Post Title..."
android:paddingBottom="15dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="15dp"
android:singleLine="true" />
<EditText
android:id="#+id/descField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/titleField"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="#drawable/input_outline"
android:ems="10"
android:hint="Post Description..."
android:inputType="textMultiLine"
android:paddingBottom="15dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="15dp" />
<Button
android:id="#+id/submitBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#color/colorPrimary"
android:text="Submit Post"
android:textColor="#ffffff" />
</RelativeLayout>
PostActivity.java
package com.vks_apps.blogs;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class PostActivity extends AppCompatActivity
{
private ImageButton mSelectImage;
public static final int GALLERY_REQUEST = 1;
private Uri mImageUri = null;
private EditText mPostTitle, mPostDesc;
private Button mSubmitBtn;
private StorageReference mStorage;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mSelectImage = (ImageButton)findViewById(R.id.imageSelect);
mPostTitle = (EditText)findViewById(R.id.titleField);
mPostDesc = (EditText)findViewById(R.id.descField);
mSubmitBtn = (Button) findViewById(R.id.submitBtn);
mProgress = new ProgressDialog(this);
mStorage = FirebaseStorage.getInstance().getReference();
mSelectImage.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,GALLERY_REQUEST);
}
});
mSubmitBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
startPosting();
}
});
}
private void startPosting()
{
mProgress.setMessage("Posting to Blog...");
mProgress.show();
String title_val = mPostTitle.getText().toString().trim();
String desc_val = mPostDesc.getText().toString().trim();
if((!TextUtils.isEmpty(title_val)) && (!TextUtils.isEmpty(desc_val)) && (mImageUri != null))
{
StorageReference filepath = mStorage.child("Blog_Images").child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>()
{
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
#SuppressWarnings("VisibleForTests") Uri downloadUri = taskSnapshot.getDownloadUrl();
mProgress.dismiss();
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==GALLERY_REQUEST && resultCode==RESULT_OK)
{
mImageUri = data.getData();
mSelectImage.setImageURI(mImageUri);
}
}
}
app/build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.0"
defaultConfig {
applicationId "com.vks_apps.blogs"
minSdkVersion 19
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support:recyclerview-v7:26.+'
compile 'com.android.support:cardview-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-database:10.0.1'
compile 'com.google.firebase:firebase-storage:10.0.1'
compile 'com.google.firebase:firebase-auth:10.0.1'
compile 'com.firebaseui:firebase-ui-database:2.1.0'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
project/build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
classpath 'com.google.gms:google-services:3.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.vks_apps.blogs">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".PostActivity"></activity>
</application>
</manifest>
res/drawable/input_outline.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:color="#color/greyColor" android:width="1dp"/>
<corners android:radius="5dp"/>
</shape>
res/values/colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#0488d1</color>
<color name="colorPrimaryDark">#0477bd</color>
<color name="colorAccent">#FF4081</color>
<color name="greyColor">#c2c2c2</color>
</resources>
LOGCAT
07-23 23:22:31.904 6461-6461/com.vks_apps.blogs D/AndroidRuntime: Shutting down VM
--------- beginning of crash
07-23 23:22:31.904 6461-6461/com.vks_apps.blogs E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.vks_apps.blogs, PID: 6461
java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/internal/zzac;
at com.google.firebase.storage.FirebaseStorage.getInstance(Unknown Source)
at com.vks_apps.blogs.PostActivity.onCreate(PostActivity.java:42)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.common.internal.zzac" on path: DexPathList[[zip file "/data/app/com.vks_apps.blogs-2/base.apk", zip file "/data/app/com.vks_apps.blogs-2/split_lib_dependencies_apk.apk", zip file "/data/app/com.vks_apps.blogs-2/split_lib_slice_0_apk.apk", zip file "/data/app/com.vks_apps.blogs-2/split_lib_slice_1_apk.apk", zip file "/data/app/com.vks_apps.blogs-2/split_lib_slice_2_apk.apk", zip file "/data/app/com.vks_apps.blogs-2/split_lib_slice_3_apk.apk", zip file "/data/app/com.vks_apps.blogs-2/split_lib_slice_4_apk.apk", zip file "/data/app/com.vks_apps.blogs-2/split_lib_slice_5_apk.apk", zip file "/data/app/com.vks_apps.blogs-2/split_lib_slice_6_apk.apk", zip file "/data/app/com.vks_apps.blogs-2/split_lib_slice_7_apk.apk", zip file "/data/app/com.vks_apps.blogs-2/split_lib_slice_8_apk.apk", zip file "/data/app/com.vks_apps.blogs-2/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.vks_apps.blogs-2/lib/x86, /system/lib, /vendor/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at com.google.firebase.storage.FirebaseStorage.getInstance(Unknown Source) 
at com.vks_apps.blogs.PostActivity.onCreate(PostActivity.java:42) 
at android.app.Activity.performCreate(Activity.java:6662) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
PS: Don't mark this question as duplicate, as I've already tried all the other methods. Here I've written the original code without any modification. Also I've uploaded the video of my app's crashing - You can see it: http://www.mediafire.com/file/xb61s4k0wojxy2z/app.mp4
also I think it's happening because of this line :
mStorage = FirebaseStorage.getInstance().getReference();
because when i remove this line, my app is working fine, but i need this line to upload the file
The FirebaseUI documentation contains a section on dependencies with the following warning and a table of compatible versions:
If you are using any dependencies in your app of the form compile
'com.google.firebase:firebase-:x.y.z' or compile
'com.google.android.gms:play-services-:x.y.z' you need to make sure
that you use the same version that your chosen version of FirebaseUI
requires.
You are using version 10.0.1 of the Firebase libraries. For those, you must use version 1.1.1 of the FirebaseUI components: com.firebaseui:firebase-ui-database:1.1.1.
Update:
The problem may be a version incompatibility with the v26 support libs. Try these dependencies:
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support:recyclerview-v7:26.+'
compile 'com.android.support:cardview-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-database:11.0.2' // CHANGED
compile 'com.google.firebase:firebase-storage:11.0.2' // CHANGED
compile 'com.google.firebase:firebase-auth:11.0.2' // CHANGED
compile 'com.firebaseui:firebase-ui-database:2.1.0' // CHANGED

OnClick linstener using Butterknife not working

OnClick linstener using Butterknife is not working when i click button it's not happening any thing,someone please check the code below and suggest me any modifications if any.
MainActivity.java
package com.example.niranjan.sample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
#BindView(R.id.button)
Button button;
#BindView(R.id.edit)
EditText edit;
#BindView(R.id.text)
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
#OnClick(R.id.button)
public void onClick(View view)
{
String text1 = edit.getText().toString();
text.setText(text1);
}
}
activity_main.xml
<?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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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="com.example.niranjan.sample.MainActivity">
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/edit"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="addtext" />
</LinearLayout>
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.2"
defaultConfig {
applicationId "com.example.niranjan.sample"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.jakewharton:butterknife:8.4.0'
testCompile 'junit:junit:4.12'
}
I done below steps and successfully implemented butter knife
In build.gradle(project)
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
apply the 'android-apt' and dependency in build.gradle(app)
apply plugin: 'android-apt'
android {
...
}
dependencies {
compile 'com.jakewharton:butterknife:8.4.0'
apt 'com.jakewharton:butterknife-compiler:8.4.0'
}
I had the same problem, try this in your build.gradle(Module.app)
compile 'com.jakewharton:butterknife:8.4.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
and then
apt 'com.jakewharton:butterknife-compiler:8.4.0'
also do not forget
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' in build.gradle(Project)
You neeed to add apt 'com.jakewharton:butterknife-compiler:8.4.0' under apply plugin in build.gradle
Also add
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
In your project build.gradle inside buildScript->dependencies

Implementing ButterKnife giving NullPointer Exception

I'm trying to implement the ButterKnife library in a small project, how ever my app crashes when it starts, details:
here is my MainActivity.java :
package com.example.odai.playwithme;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
#BindView(R.id.hello_world) TextView hello;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
hello.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Hello",
Toast.LENGTH_SHORT).show();
}
});
}
}
my activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<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"
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="com.example.odai.playwithme.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="#+id/hello_world"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
my build.gradle :
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.example.odai.playwithme"
minSdkVersion 17
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.jakewharton:butterknife:8.0.1'
}
and this is the error I get whenever I try to run my app :
05-22 20:32:52.019 24076-24076/com.example.odai.playwithme E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.odai.playwithme, PID: 24076
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.odai.playwithme/com.example.odai.playwithme.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2484)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2544)
at android.app.ActivityThread.access$900(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1394)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5845)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.odai.playwithme.MainActivity.onCreate(MainActivity.java:22)
at android.app.Activity.performCreate(Activity.java:6248)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1125)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2437)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2544) 
at android.app.ActivityThread.access$900(ActivityThread.java:150) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1394) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:168) 
at android.app.ActivityThread.main(ActivityThread.java:5845) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
any ideas?
I had this problem a while back, too, and actually just tried again to see if it was just a one time thing. Apparently the newer ButterKnife requires a bit more stuff in your build.gradle:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
apply plugin: 'com.neenbedankt.android-apt'
dependencies {
compile 'com.jakewharton:butterknife:8.0.1'
apt 'com.jakewharton:butterknife-compiler:8.0.1'
}
(https://github.com/JakeWharton/butterknife)
Remove #Bindview line and do the following to bind elements properly:
Click on your layout name in setContentView line
Press alt+enter , it will bring insert options
Click generate butterknief injections
Choose elements that you want to bind
Click ok.
And it will work.
You can also set onclick events directly from there while choosing the views to bind.

Categories

Resources