ClassNotFoundException on subsequent builds after converting MainActivity to Kotlin - android

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

Related

SwitchCompat Unresolved reference - Android Kotlin

I'm using a SwitchCompat in a fragment where I keep getting and Unresolved reference that don't let me compile.
I don't know where to look at any more.. I believe I have my gradle files how they are supposed to be but I still suspect is something from there..
Any idea what I might be doing wrong?
Thank you in advance!! Any tip would be very appreciated
My gradle files:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.4.21"
ext.nav_version = '2.3.0'
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.1"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
And:
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'androidx.navigation.safeargs.kotlin'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.example.onemorepassword"
minSdkVersion 21
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
dataBinding true
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
//ViewModel
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
}
I have my XML:
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.SwitchCompat
android:id="#+id/lowLetters_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="30dp"
android:checked="true"
android:fontFamily="#font/nunito_sans_bold"
android:text="#string/switchLowLetters"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/lengthSize_seekBar" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
My Fragment:
package com.example.onemorepassword
import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.onemorepassword.databinding.OneMorePasswordFragmentBinding
class OneMorePasswordFragment : Fragment() {
private lateinit var binding: OneMorePasswordFragmentBinding
private lateinit var viewModel: OneMorePasswordViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate<OneMorePasswordFragmentBinding>(inflater, R.layout.one_more_password_fragment, container, false)
viewModel = ViewModelProvider(this).get(OneMorePasswordViewModel::class.java)
//All fun that update UI from viewModel
savedGeneratedPass()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
**val myLowLettersSwitch = binding.lowLettersSwitch
myLowLettersSwitch.setOnCheckedChangeListener { _, b ->
Toast.makeText(requireActivity(),b.toString(),Toast.LENGTH_SHORT).show(**)
}
......
More code...
....
**private fun switchLowLetters(): Boolean {
val myLowLettersSwitch= binding.lowLettersSwitch
return myLowLettersSwitch.isChecked
}**
....
More code...
And last my mainActivity
package com.example.onemorepassword
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.onemorepassword.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//setContentView(R.layout.activity_main)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
supportActionBar?.hide()
}
}
You need to add viewBinding true to buildFeatures in build.gradle (app) file in order to be able to use view binding.
Just replace:
buildFeatures {
dataBinding true
}
with:
buildFeatures {
dataBinding true
viewBinding true
}
Found out what was happening. Once you know it..!
I have to XML files for same Fragment, Portrait and Landscape.
Forgot to edit me Landscape XML file.... So in one I had <com.google.android.material.switchmaterial.SwitchMaterial> (or compat, does not matter)
and in other XML I only had
Maybe this will serve for someone to look into this before collapsing

Chat with Firestore crashes with NullPointerException on RecyclerView.setHasFixedSize

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);

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

Hello World app crashes on 2.3.3 (API 10), but works fine on 5.1 (API 22)

Using Android Studio I have created a very basic skeletal app. It works on android 5.1 API 22, but crashes on invocation on android 2.3.3 API 10.
Here is the crash log. It shows resource not found exception for abc_vector_test.xml file.
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo {com.myco.k5/com.myco.k5.MainActivity}:
android.content.res.Resources$NotFoundException: File res/drawable/abc_vector_test.xml from drawable resource ID #0x7f020052
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:1651)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3691)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/abc_vector_test.xml from drawable resource ID #0x7f020052
at android.content.res.Resources.loadDrawable(Resources.java:1977)
at android.content.res.Resources.getDrawable(Resources.java:602)
at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:388)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:202)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:190)
at android.support.v7.widget.AppCompatDrawableManager.checkVectorDrawableSetup(AppCompatDrawableManager.java:711)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:195)
at android.support.v7.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:81)
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:131)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:155)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:209)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:185)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:71)
at com.myco.k5.MainActivity.onCreate(MainActivity.java:13)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667) 
at android.app.ActivityThread.access$1500(ActivityThread.java:117) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:123) 
at android.app.ActivityThread.main(ActivityThread.java:3691) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:507) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #17: invalid drawable tag vector
at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:783)
at android.graphics.drawable.Drawable.createFromXml(Drawable.java:728)
at android.content.res.Resources.loadDrawable(Resources.java:1952)
at android.content.res.Resources.getDrawable(Resources.java:602) 
at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:388) 
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:202) 
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:190) 
at android.support.v7.widget.AppCompatDrawableManager.checkVectorDrawableSetup(AppCompatDrawableManager.java:711) 
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:195) 
at android.support.v7.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:81) 
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:131) 
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:155) 
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:209) 
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:185) 
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519) 
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:71) 
at com.myco.k5.MainActivity.onCreate(MainActivity.java:13) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667) 
at android.app.ActivityThread.access$1500(ActivityThread.java:117) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:123) 
at android.app.ActivityThread.main(ActivityThread.java:3691) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:507) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605) 
at dalvik.system.NativeStart.main(Native Method) 
I have already tried some of the approaches (see code below).
Files are:
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myco.k5" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:name="android.support.multidex.MultiDexApplication"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar android:id="#+id/toolbar"
android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main" tools:context=".MainActivity">
<TextView android:text="Hello World!"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
MainActivity.java:
package com.myco.k5;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
app's build.gradle file:
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "com.myco.k5"
minSdkVersion 10
targetSdkVersion 25
versionCode 1
versionName "1.0"
multiDexEnabled true
}
dexOptions {
incremental true
javaMaxHeapSize "4g"
}
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:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:multidex:1.0.1'
}
Top level build.gradle file:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.3.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
}
Please advice on how can this crash be resolved.
SOLVED: Solved this by using the following
In app level build.gradle file used
android {
// your entries here
generatedDensities = []
}
// Flag notifies aapt to keep the attribute IDs around
aaptOptions {
additionalParameters "--no-version-vectors"
}
In the top level build.gradle file changed classpath from 1.4.0 to 1.5.0
classpath 'com.android.tools.build:gradle:1.5.0'
// Earlier it was 1.4.0 here
In your case, you have to enable the Vector Drawable to use it in old android versions. Add this in your build.gradle file (module app).
For Gradle Plugin 2.0+
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
For Gradle Plugin 1.5 or below
android {
defaultConfig {
// Stops the Gradle plugin’s automatic rasterization of vectors
generatedDensities = []
}
// Flag notifies aapt to keep the attribute IDs around
aaptOptions {
additionalParameters "--no-version-vectors"
}
}
After do that, you have to change your ImageView to use the compat src like that:
<ImageView
app:srcCompat="#drawable/abc_vector_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

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