When click button on TradersActivity start JsonViewActivity
I need to check is success started JsonViewActivity. Here Espresso test:
#RunWith(AndroidJUnit4::class)
class TradersActivityTest {
val context = InstrumentationRegistry.getInstrumentation().getContext()
val targetContext = InstrumentationRegistry.getInstrumentation().getTargetContext()
#Rule
#JvmField
var tradersActivitytRule = ActivityTestRule(TradersActivity::class.java)
#Test
fun itemList_viewJsonButton_click_check() {
//scroll
onView(withId(R.id.tradersRecyclerView))
.perform(scrollToPosition<RecyclerView.ViewHolder>(checkItemCount));
// click
onView(withRecyclerView(R.id.tradersRecyclerView).atPositionOnView(checkItemCount, R.id.viewJsonButton))
.perform(click())
// check is start JsonViewActivity activity
intended(hasComponent(JsonViewActivity::class.java.getName()))
}
But test is fail:
Started running tests
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.test.espresso.intent.Intents.internalIntended(org.hamcrest.Matcher, androidx.test.espresso.intent.VerificationMode, java.util.List)' on a null object reference
at androidx.test.espresso.intent.Intents$2.check(Intents.java:194)
at androidx.test.espresso.ViewInteraction$SingleExecutionViewAssertion.check(ViewInteraction.java:419)
at androidx.test.espresso.ViewInteraction$2.call(ViewInteraction.java:282)
at androidx.test.espresso.ViewInteraction$2.call(ViewInteraction.java:268)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
You should use IntentsTestRule instead of ActivityTestRule.
Related
So I am using firebase to upload my data by filling a form and sending a cover picture. After I filled the form and provide the picture, I pressed a "save" button, which is basically sending all those information and pictures to firebase and then return to the main activity. Before the main activity appears, the app crashed and this error appears:
2022-08-16 20:49:53.847 21445-21445/com.example.gesit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.gesit, PID: 21445
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.button.MaterialButton.setEnabled(boolean)' on a null object reference
at com.example.gesit.TambahProduk.saveProductInformation$lambda-6(TambahProduk.kt:313)
at com.example.gesit.TambahProduk.$r8$lambda$WSqVgd-3d_M5F9vVqHMPnqwiv5o(Unknown Source:0)
at com.example.gesit.TambahProduk$$ExternalSyntheticLambda3.onComplete(Unknown Source:2)
at com.google.android.gms.tasks.zzi.run(com.google.android.gms:play-services-tasks##18.0.1:1)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8751)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
What caused this crash? Thanks.
Code for sending data and picture to firebase:
private fun saveProductInformation(downloadedUrl: String) {
auth = FirebaseAuth.getInstance()
val uid = auth.currentUser?.uid.toString()
databaseReference =
FirebaseDatabase.getInstance()
.getReference("User")
val productName = productName.text.toString()
val productInfo =
DataProduk(productName, uid)
if (uid != null) {
databaseReference.child(uid).setValue(productInformation)
.addOnCompleteListener {
saveButton.isEnabled = false
Toast.makeText(this#AddProduct,"Product added",Toast.LENGTH_SHORT).show()
hideProgressBar()
}
}
}
package com.example.absolutelydumb
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.InputType
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
//sets var to some random number and asks for a guess, giving feedback on proximity to answer
class MainActivity : AppCompatActivity() {
private val startButton: Button = findViewById(R.id.startButton)
private val submitButton: Button = findViewById(R.id.submit)
private val instructionsText: TextView = findViewById(R.id.instructionView)
private val response: EditText = findViewById(R.id.answerInput)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val startText: String = getString(R.string.startText)
startButton.text = startText
//TODO("Add autofillHints")
startButton.setOnClickListener {
numberGuess()
}
//TODO("Set text back to start after guessing is done")
}
fun numberGuess() {
response.inputType = InputType.TYPE_CLASS_NUMBER
val clickText: String = getString(R.string.clickText)
startButton.text = clickText
//TODO("Add autofillHints")
instructionsText.text = getString(R.string.instructions)
val randomNumber: Int = rand(0,10)
submitButton.setOnClickListener {
val responseText = Integer.parseInt(answerInput.text.toString())
if(responseText == randomNumber) {
instructionsText.text = getString(R.string.correctGuess)
} else {
instructionsText.text = getString(R.string.badGuess)
}
}
}
fun rand(start: Int, end: Int): Int {
//require(start <= end) { "Illegal Argument" }
return (start..end).random()
}
}
Above is the code that I've been writing. This is my first project, so I don't know what went wrong. I fixed a variable type problem in the numberGuess function but when I finished fixing it the app wouldn't open and the virtual device stated a "app keeps stopping" error.
Here is the Run log that lists off errors. The build log didn't have any errors.
07/09 19:58:05: Launching 'app' on phone1.
Install successfully finished in 1 s 266 ms.
$ adb shell am start -n "com.example.absolutelydumb/com.example.absolutelydumb.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 5935 on device 'phone1 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.absolutelydumb, PID: 5935
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.absolutelydumb/com.example.absolutelydumb.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2843)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:159)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
at android.content.Context.obtainStyledAttributes(Context.java:675)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.absolutelydumb.MainActivity.<init>(MainActivity.kt:13)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2831)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
You cannot call findViewById before onCreate() or setContentView() is called. Since you are using findViewById at the declaration site of your four properties, it is being called at the time your Activity class is being instantiated, which is before onCreate is called.
There are two ways to handle this.
Use lateinit var and set the properties right after your call to setContentView():
private lateinit var startButton: Button
//...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button = findViewById(R.id.startButton)
//...
Use by lazy so it is only called when the property is first accessed, which will be after setContentView() is called:
private val startButton: Button by lazy { findViewById(R.id.startButton) }
Or you can use view binding, which gets rid of most of this boilerplate and is less error-prone. By error-prone, I mean you can call findViewById and accidentally search for a view that isn't present in the current layout and it will crash at runtime. View binding makes this impossible.
I know this has been asked before but my problem is strange and I couldn't find an answer.
I have a parent class where a member is declared protected
class BaseContoller<G: BaseContract.BasePresenter, F: BaseModel> {
protected var presenter: G? = null
// ...
}
In each of BaseController's descendants, I refer to presenter with no problem as it is accessible in the same package and subclasses.
One BaseController's descendant has to be extended by other classes too but I have to do one check before of performing certain actions in where presenter is referenced again
class BackupPrinterController<G: BackupPrinterContract.Presenter, F: BaseModel>: BackupController<G, F>
private fun startScan() {
if(this is PrinterAssociationController) {
PrinterConnection.onConnection = { presenter?.onDeviceConnected(it) }
// ...
}
}
}
The strange behaviour comes here, presenter is perfectly accessible only without the filter if(this is PrinterAssociationController), with that if statement, when the onConnection callback is invoked, an IllegalAccessError exception is thrown by presenter
Here is the declaration of PrinterAssociationController
class PrinterAssociationController: BackupPrinterController<PrinterAssociationContract.Presenter, PrinterAssociationModel>(),
PrinterAssociationContract.View
and here is the exception
java.lang.IllegalAccessError: Method 'package.common.base.BaseContract$BasePresenter package.common.base.BaseController.getPresenter()' is inaccessible to class 'package.project.features.shared.controllers.BackupPrinterController$startScan$1' (declaration of 'package.project.features.shared.controllers.BackupPrinterController$startScan$1' appears in /data/app/package.project-1/base.apk:classes2.dex)
at package.project.features.shared.controllers.BackupPrinterController$startScan$1.invoke(BackupPrinterController.kt:53)
at package.project.features.shared.controllers.BackupPrinterController$startScan$1.invoke(BackupPrinterController.kt:35)
at package.project.utils.print.PrinterConnection$scan$1$4.accept(PrinterConnection.kt:84)
at package.project.utils.print.PrinterConnection$scan$1$4.accept(PrinterConnection.kt:24)
at io.reactivex.internal.observers.LambdaObserver.onNext(LambdaObserver.java:63)
at io.reactivex.internal.operators.observable.ObservableFilter$FilterObserver.onNext(ObservableFilter.java:52)
at io.reactivex.internal.operators.observable.ObservableDistinct$DistinctObserver.onNext(ObservableDistinct.java:85)
at io.reactivex.internal.operators.mixed.CompletableAndThenObservable$AndThenObservableObserver.onNext(CompletableAndThenObservable.java:65)
at io.reactivex.internal.operators.observable.ObservableFlatMap$MergeObserver.tryEmit(ObservableFlatMap.java:265)
at io.reactivex.internal.operators.observable.ObservableFlatMap$InnerObserver.onNext(ObservableFlatMap.java:562)
at io.reactivex.internal.operators.observable.ObservableDoOnEach$DoOnEachObserver.onNext(ObservableDoOnEach.java:101)
at io.reactivex.internal.operators.observable.ObservableMap$MapObserver.onNext(ObservableMap.java:62)
at io.reactivex.internal.operators.observable.ObservableUnsubscribeOn$UnsubscribeObserver.onNext(ObservableUnsubscribeOn.java:60)
at io.reactivex.internal.operators.observable.ObservableCreate$CreateEmitter.onNext(ObservableCreate.java:66)
at com.polidea.rxandroidble2.internal.serialization.FIFORunnableEntry$1.onNext(FIFORunnableEntry.java:66)
at io.reactivex.internal.operators.observable.ObservableUnsubscribeOn$UnsubscribeObserver.onNext(ObservableUnsubscribeOn.java:60)
at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeOnObserver.onNext(ObservableSubscribeOn.java:58)
at io.reactivex.internal.operators.observable.ObservableCreate$CreateEmitter.onNext(ObservableCreate.java:66)
at com.polidea.rxandroidble2.internal.operations.ScanOperationApi21$1.onScanResult(ScanOperationApi21.java:77)
at android.bluetooth.le.BluetoothLeScanner$BleScanCallbackWrapper$1.run(BluetoothLeScanner.java:471)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at com.osama.firecrasher.FireLooper.run(FireLooper.kt:39)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6780)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1500)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1390)
I don't understand why this is happening when I put that if statement
private fun setupGeckoView() {
val runtime = GeckoRuntime.create(this) // crashes on this line
geckoSession.open(runtime)
geckoView.setSession(geckoSession)
val url = String(Base64.decode(MYURL, Base64.DEFAULT))
geckoSession.loadUri(url)
geckoSession.progressDelegate = createProgressDelegate()
geckoSession.settings.allowJavascript = true
}
i call setUpGeckoView methon in onCreat() but when i click back and
reopen the app then app crashes with IllegalStateException saying
"Failed to initialize GeckoRuntime. It works first time only crashed when i click back and then open app again"
Logs are given below
Process: arholding.kargoshop.mk, PID: 16444
java.lang.RuntimeException: Unable to start activity ComponentInfo{arholding.kargoshop.mk/arholding.kargoshop.mk.SeckoActivity}: java.lang.IllegalStateException: Failed to initialize GeckoRuntime
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3447)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3594)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2146)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7762)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1047)
Caused by: java.lang.IllegalStateException: Failed to initialize GeckoRuntime
at org.mozilla.geckoview.GeckoRuntime.create(GeckoRuntime.java:458)
at org.mozilla.geckoview.GeckoRuntime.create(GeckoRuntime.java:333)
at arholding.kargoshop.mk.SeckoActivity.setupGeckoView(SeckoActivity.kt:23)
at arholding.kargoshop.mk.SeckoActivity.onCreate(SeckoActivity.kt:19)
at android.app.Activity.performCreate(Activity.java:7981)
at android.app.Activity.performCreate(Activity.java:7970)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
This exception will be thrown if there is already an active Gecko instance running. There are many ways to resolve this problem.
Solution 1: Get the default runtime for the given context.
Change your code from
val runtime = GeckoRuntime.create(this)
to
val runtime = GeckoRuntime.getDefault(this)
Solution 2: Kill the process when exit app by finishing activity, add this code into your activity.
override fun onDestroy() {
Process.killProcess(Process.myPid())
super.onDestroy()
}
Solution 3: Only create a new instance if there is no active instance running
private fun setupGeckoView() {
if (geckoRuntime == null) {
geckoRuntime = GeckoRuntime.create(this)
}
geckoSession.open(geckoRuntime!!)
geckoView.setSession(geckoSession)
val url = String(Base64.decode(MYURL, Base64.DEFAULT))
geckoSession.loadUri(url)
geckoSession.progressDelegate = createProgressDelegate()
geckoSession.settings.allowJavascript = true
}
companion object {
var geckoRuntime: GeckoRuntime? = null
}
I'm trying to run an app adopting MVVM pattern architecture, but I'm getting an exception that I can't solve.
I have my MainActivity.java which has an observe to the firstTime() method in the MainViewModel.java.
MainActivity.java
(...)
ViewModelProvider.Factory mViewModelFactory;
ActivityMainBinding mActivityStartBinding;
private MainViewModel mainViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivityStartBinding = getViewDataBinding();
mainViewModel.firstTime().observe(this, new Observer<Boolean>() {
#Override
public void onChanged(#Nullable Boolean aBoolean) {
if(aBoolean !=null && aBoolean){
mainViewModel.setisFirstRun();
}
}
});
MainViewModel.java
(...)
private final DataManager mDataManager; <--- repository
public LiveData<Boolean> firstTime(){
if(mDataManager.isFirstRun())
{
Timber.d("-------------- Is first read from database ");
return mDataManager.saveValues();
}
else
{
Timber.d("-------------- Is not first read from database ");
return null;
}
}
And every time I run I get the following Exception that I can't resolve.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rd.ch/com.rd.ch.ui.main.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.arch.lifecycle.LiveData.observe(android.arch.lifecycle.LifecycleOwner, android.arch.lifecycle.Observer)' on a null object reference
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.NullPointerException: Attempt to invoke virtual method 'void android.arch.lifecycle.LiveData.observe(android.arch.lifecycle.LifecycleOwner, android.arch.lifecycle.Observer)' on a null object reference
at com.rd.ch.ui.main.MainActivity.onCreate(MainActivity.java:55)
at android.app.Activity.performCreate(Activity.java:6251)
How can I solve this?
The reason of getting NPE is that you have missed to initialize your viewModel object in activity onCreate.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
// Rest of the code
}