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.
Related
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.
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);
I have a button and I want to change text on it after it was clicked.
#BindView(R.id.btn) Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
#OnClick(R.id.btn)
public void click()
{
btn.setText("anything");
}
I've realized that I can do this with normal onclickListener, but I am wondering if I can do this using butterknife.
EDIT
Gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.0"
defaultConfig {
applicationId "com.jnx.test"
minSdkVersion 14
targetSdkVersion 25
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:25.3.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
}
EDIT
Error log
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jnx.test/com.jnx.test.MainActivity}: java.lang.IllegalStateException: Required view 'btn' with ID 2131427422 for field 'btn' and method 'click' was not found. If this view is optional add '#Nullable' (fields) or '#Optional' (methods) annotation.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: Required view 'btn' with ID 2131427422 for field 'btn' and method 'click' was not found. If this view is optional add '#Nullable' (fields) or '#Optional' (methods) annotation.
at butterknife.internal.Utils.findRequiredView(Utils.java:92)
at com.jnx.test.MainActivity_ViewBinding.<init>(MainActivity_ViewBinding.java:29)
at java.lang.reflect.Constructor.newInstance(Native Method)
at butterknife.ButterKnife.createBinding(ButterKnife.java:199)
at butterknife.ButterKnife.bind(ButterKnife.java:124)
at com.jnx.test.MainActivity.onCreate(MainActivity.java:22)
Line 22 in MainActivity is setContentView(R.layout.activity_main);
Ok, I got it. I think someone have posted such answer before, but it didn't worked for me at first. It started working after the restart of android studio.
#BindView(R.id.btn) Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
#OnClick(R.id.btn)
public void click(View v)
{
btn.setText("dsdssd");
}
You have to pass the View as an argument.
You can pass the view :
#OnClick(R.id.btn)
public void click(Button button) {
button.setText("Hello");
}
And you don't need this line so remove this:
#BindView(R.id.btn) Button btn;
Can someone help me on this? In my test I want to check if the login button is displayed on the StartPage.
I've been struggling with this error for a while today and I don't know how it should be resolved.What am I missing here?
Maybe this problem is somehow similar to this question:
Espresso test fails with java.lang.String cannot be cast to com.abc.events.databinding.SponsorDetailBinding
android.view.InflateException: Binary XML file line #6: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:770)
at android.view.LayoutInflater.inflate(LayoutInflater.java:483)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
at io.turbela.turbela.login.view.StartActivity.onCreate(StartActivity.java:16)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.support.test.runner.MonitoringInstrumentation.callActivityOnCreate(MonitoringInstrumentation.java:532)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2655)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void io.turbela.turbela.databinding.FragmentStartBinding.setViewModel(io.turbela.turbela.login.viewmodel.DispatchViewModel)' on a null object reference
at io.turbela.turbela.StartActivityFragment.onCreateView(StartActivityFragment.java:34)
at android.app.Fragment.performCreateView(Fragment.java:2114)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:875)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1060)
at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1162)
at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2131)
at android.app.Activity.onCreateView(Activity.java:5610)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:34)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:740)
... 20 more
LoginTest.java
#RunWith(AndroidJUnit4.class)
public class LoginTest {
#Rule
public ActivityTestRule<StartActivity> mActivityRule = new ActivityTestRule(StartActivity.class);
#Test
public void displayLoginPage() {
onView(withId(R.id.login_button)).check(matches(isDisplayed()));
}
}
StartActivity.java
public class StartActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
}
...onCreateOptionsMenu(...
...onOptionsItemSelected(...
}
activity_start.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment"
class="io.turbela.turbela.StartActivityFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
StartActivityFragment.java
public class StartActivityFragment extends Fragment {
public StartActivityFragment() {
}
public static StartActivityFragment newInstance(){
Bundle args = new Bundle();
args.putString("key", "value");
StartActivityFragment fragment = new StartActivityFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
FragmentStartBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_start, container, false);
binding.setViewModel(new DispatchViewModel());
return binding.getRoot();
}
}
fragment_start.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="viewModel" type="io.turbela.turbela.login.viewmodel.DispatchViewModel" />
</data>
<RelativeLayout
style="#android:style/Theme.Holo"
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">
<Button
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginTop="128dp"
android:onClick="#{viewModel.onClickLogin}"
android:text="#string/login" />
</RelativeLayout>
</layout>
DispatchViewModel.java
public class DispatchViewModel extends BaseObservable{
public View.OnClickListener onClickLogin() {
//loginWithEmail
return v -> Log.d("H", "onClickLogin");
}
}
build.gradle
apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'
android {
compileSdkVersion 23
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "io.turbela.turbela"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
dataBinding{
enabled = true
}
packagingOptions {
exclude 'LICENSE.txt'
}
lintOptions {
abortOnError false
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:cardview-v7:23.1.1'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.parse:parse-android:1.12.0'
compile 'com.parse.bolts:bolts-android:1.3.0'
compile 'com.facebook.android:facebook-android-sdk:4.8.1'
compile 'com.parse:parsefacebookutils-v4-android:1.10.3#aar'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
androidTestCompile 'com.android.support.test:runner:0.5'
}
There is android:name attribute missing from <fragment> tag in your activity_start.xml
As per the docs, you must include it.
So your activity.start.xml should look like this:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment"
android:name="io.turbela.turbela.StartActivityFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Note:
The class= attribute you are trying to use is for custom Views as in here
I want to give Kotlin a try, so I decided to try to convert a single class of my project to Kotlin and see how it integrates with my workflow before trying to convert my entire project. I am able to build and my app works properly, but on every subsequent build after the first, I get the below exception from ClassLoader. The app only works properly after cleaning, and worked fine before I converted anything. I'm able to run a HelloWorld project on the same machine multiple times without error. The responses in this question did not help: ClassNotFoundException in custom flavor using kotlin
07-31 14:35:41.563 1878-1878/com.ddiehl.android.htn.debug
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.ddiehl.android.htn.debug, PID: 1878
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.ddiehl.android.htn.debug/com.ddiehl.android.htn.view.activities.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.ddiehl.android.htn.view.activities.MainActivity" on path: DexPathList[[zip file "/data/app/com.ddiehl.android.htn.debug-1/base.apk"],nativeLibraryDirectories=[/data/app/com.ddiehl.android.htn.debug-1/lib/arm, /vendor/lib, /system/lib]]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.ddiehl.android.htn.view.activities.MainActivity" on path: DexPathList[[zip file "/data/app/com.ddiehl.android.htn.debug-1/base.apk"],nativeLibraryDirectories=[/data/app/com.ddiehl.android.htn.debug-1/lib/arm, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Suppressed: java.lang.ClassNotFoundException: com.ddiehl.android.htn.view.activities.MainActivity
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 13 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
Anyone have an idea why my app might work on first build, but not on subsequent builds? Here is my build.gradle, manifest, and activity, for reference.
build.gradle (app module)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'com.jakewharton.hugo'
apply plugin: 'com.getkeepsafe.dexcount'
apply plugin: 'me.tatarka.retrolambda'
android {
compileSdkVersion 22
buildToolsVersion "23 rc3"
defaultConfig {
applicationId "com.ddiehl.android.htn"
minSdkVersion 15
targetSdkVersion 22
versionCode 4
versionName "0.3.0-dev"
ndk {
moduleName "app"
}
}
signingConfigs {
release {
storeFile file(ANDROID_KEYSTORE_PATH)
storePassword ANDROID_KEYSTORE_PWD
keyAlias HTN_KEYSTORE_ALIAS
keyPassword HTN_KEYSTORE_PWD
}
}
buildTypes {
debug {
applicationIdSuffix ".debug"
minifyEnabled false
}
release {
debuggable false
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
debug.java.srcDirs += 'src/debug/kotlin'
}
}
def getLocalProperty(s) {
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
return properties.getProperty(s)
}
retrolambda {
jdk getLocalProperty("jdk8.dir")
}
dependencies {
compile project(':reddit')
compile project(':mopub')
compile project(':flurry')
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.android.support:support-v4:22.2.1'
compile 'com.android.support:design:22.2.0'
compile 'com.android.support:recyclerview-v7:22.2.1'
compile 'com.android.support:cardview-v7:22.2.1'
compile 'com.google.android.gms:play-services-ads:7.5.0'
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.okhttp:okhttp-urlconnection:2.4.0'
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.squareup:otto:1.3.5'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.jakewharton:butterknife:7.0.0'
compile 'com.jakewharton:kotterknife:0.1.0-SNAPSHOT'
compile 'io.reactivex:rxandroid:0.25.0'
compile 'com.facebook.stetho:stetho:1.1.1'
compile 'com.facebook.stetho:stetho-okhttp:1.1.1'
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3.1'
}
buildscript {
ext.kotlin_version = '0.12.1230'
repositories {
mavenCentral()
maven {
url 'http://oss.sonatype.org/content/repositories/snapshots'
}
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
repositories {
mavenCentral()
maven {
url 'http://oss.sonatype.org/content/repositories/snapshots'
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ddiehl.android.htn" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:name="com.ddiehl.android.htn.HoldTheNarwhal"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:supportsRtl="true">
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name="com.ddiehl.android.htn.view.activities.MainActivity"
android:label="#string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="www.damiendiehl.net"
android:scheme="http" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.kt (I redacted most of the View-related logic, it was 400 lines and this is a closed-source project at the moment. I can pastebin the full file, though, if necessary).
package com.ddiehl.android.htn.view.activities
import android.app.Dialog
import android.app.ProgressDialog
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.design.widget.Snackbar
import android.support.v4.content.ContextCompat
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.MenuItem
import android.view.View
import android.view.Window
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import butterknife.Bind
import butterknife.ButterKnife
import butterknife.OnClick
import butterknife.bindView
import com.flurry.android.FlurryAgent
import com.flurry.android.FlurryAgentListener
import com.mopub.common.MoPub
import com.mopub.mobileads.MoPubConversionTracker
import hugo.weaving.DebugLog
import java.util.HashMap
import kotlin.properties.Delegates
public class MainActivity : AppCompatActivity(), MainView, ConfirmSignOutDialog.Callbacks, NavigationView.OnNavigationItemSelectedListener {
private val mBus = BusProvider.getInstance()
private var mMainPresenter: MainPresenter? = null
private var mLastAuthCode: String? = null
private var mProgressBar: ProgressDialog? = null
private var mSubredditNavigationDialog: Dialog? = null
val mDrawerLayout: DrawerLayout by bindView(R.id.drawer_layout)
private var mAccessTokenManager: AccessTokenManager? = null
DebugLog
override fun onCreate(savedInstanceState: Bundle?) {
super<AppCompatActivity>.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
ButterKnife.bind(this#MainActivity)
Init().execute()
}
private inner class Init : AsyncTask<Void, Void, Void>() {
override fun onPreExecute() {
super.onPreExecute()
mNavigationView.setNavigationItemSelectedListener(this#MainActivity)
val toolbar = ButterKnife.findById<Toolbar>(this#MainActivity, R.id.toolbar)
setSupportActionBar(toolbar)
val actionBar = getSupportActionBar()
if (actionBar != null) {
actionBar.setHomeAsUpIndicator(R.drawable.ic_navigation_menu)
actionBar.setDisplayHomeAsUpEnabled(true)
}
}
override fun doInBackground(vararg params: Void): Void? {
mAccessTokenManager = AccessTokenManager.getInstance(this#MainActivity)
return null
}
override fun onPostExecute(aVoid: Void?) {
super.onPostExecute(aVoid)
onAppInitialized()
}
}
override fun onStart() {
super<AppCompatActivity>.onStart()
if (mAccessTokenManager == null) {
showSpinner(R.string.application_loading)
} else {
onAppInitialized()
}
}
private fun onAppInitialized() {
mBus.register(mAccessTokenManager)
FlurryAgent.onStartSession(this)
dismissSpinner()
updateUserIdentity()
showSubredditIfEmpty(null)
}
override fun onStop() {
super<AppCompatActivity>.onStop()
FlurryAgent.onEndSession(this)
mBus.unregister(mAccessTokenManager)
}
companion object {
public val TAG: String = javaClass<MainActivity>().getSimpleName()
private val DIALOG_CONFIRM_SIGN_OUT = "dialog_confirm_sign_out"
private val FLURRY_SESSION_TIMEOUT_SECONDS = 30
}
}
When converting an existing Android app from Java to Konlin there are many configuration changes to make. If you only convert the actual Java files to Kotlin the compile would work, but you will get those runtime loading errors.
The easiest way is to add a Kotlin class to the project:
new->kotlin class/file
The Android studio will then do all the necessary setting up for the support of kotlin. After you can remove the new class
One possible cause could be an annotation processing library.
I am also getting same error and I have checked so many SO question and some blogs but none of them worked. As #Haggai's answer that we need do so many configuration when we directly convert Java project to Kotlin from Android Studio.
When I convert my project then all JAVA files are converted from Java to Kotlin but both Gradle files are same as previous files. So what I have done is I have added Kotlin classpath to my project level gradle file and add kotlin plugin to app level gradle file. Below is my both files and its worked for me.
Project level build.gradle file
dependencies {
classpath 'com.android.tools.build:gradle:4.2.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.20"//---Add this class path to your project
}
This is app leve build.gradle file
plugins {//---Apply plugin like this
id 'com.android.application'
id 'kotlin-android'
}
android {
defaultConfig {
...
...
}
kotlinOptions {//---I have added this block of code
jvmTarget = '1.8'
}
}
dependencies {
...
...
}
I was missing 'apply plugin: 'kotlin-android' from my module build.gradle file