This is my log cat. When i click on specific tab, my app crashes.
java.lang.NullPointerException: Attempt to invoke virtual method 'io.reactivex.Flowable io.reactivex.Flowable.observeOn(io.reactivex.Scheduler)' on a null object reference
at com.example.haji.Fragment.RecentFragment.loadRecents(RecentFragment.java:93)
at com.example.haji.Fragment.RecentFragment.onCreateView(RecentFragment.java:86)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2346)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1428)
When i call loadRecents, it give me error. Please help.
private void loadRecents() {
Disposable disposable = recentsRepository.getAllRecents().observeOn(AndroidSchedulers
.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Consumer <List <Recents>>() {
#Override
public void accept(List <Recents> recents) throws Exception {
onGetAllRecentsSuccess(recents);
}
}, new Consumer <Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
Log.d("Error",throwable.getMessage());
}
});
compositeDisposable.add(disposable);
}
Your method recentsRepository.getAllRecents() return null instead of Flowable<List <Recents>>
Add this line to Biuld.gradle dependencies
dependencies {
//other code...
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
}
error - null object reference
maybe because you have not initialized
compositeDisposable = new CompositeDisposable();
Databasename databasename= Databasename.getInstance(this);
recentsRepository=RecentsRepository.getInstance(RecentsDataSource.getInstance(mainDatabase.recentsDAO()));
Related
I have a method:
public void clearLogItems() {
if (logItems != null) {
this.logItems.clear();
this.logItems = null;
}
}
and I would like to write a unit test for it.. If my logic is right, I should check 3 things here:
Don't call logItems.clear() if logItems is null
Call logItems.clear() if logItems is not null
Set logItems to null after calling logItems.clear()
Now I'm not sure how to Mock logItems to null, to verify clear() will be called 0 times..
#RunWith(MockitoJUnitRunner.class)
public class LogItemDataTest {
LogItemData SUT;
#Mock
List<LogItemData> logItems;
#Before
public void setup() throws Exception {
SUT = new LogItemData();
}
#Test
public void clearLogItems() {
// Arrange
// Act
SUT.clearLogItems();
// Assert
Mockito.verify(logItems, times(1)).clear();
}
}
With this code, I tried to cover the case where logItems is not null and when logItems.clear() is called 1 time, but when I run it, it says there were 0 interactions with this mock...
How do I mock the logItems list to cover the null case?
The LogItemData object SUT does not know about the logItems. You have to create SUT so that it knows about your logItems. How that works depends on your implementation of LogItemData E.g. if it has a constructor it may look like this
#Before
public void setup() throws Exception {
SUT = new LogItemData(logItems);
}
In MainActivity I make two calls one by one getAddress(), this is code getAddress method:
public class RemoteRepository {
private ApiRequest apiRequest;
private LiveData<List<AddressResponse>> allAddresses = new MutableLiveData<>();
public RemoteRepository() {
apiRequest = RetrofitRequest.getInstance().create(ApiRequest.class);
}
public LiveData<List<AddressResponse>> getAddresses() {
return allAddresses;
}
public void getAddress(double query1, double query2) {
apiRequest.getAddress(query1, query2)
.enqueue(new Callback<AddressResponse>() {
#Override
public void onResponse(Call<AddressResponse> call, Response<AddressResponse> response) {
if(response.body() != null) {
allAddresses.getValue().add(response.body());
}
}
#Override
public void onFailure(Call<AddressResponse> call, Throwable t) {
}
});
}
}
Unfortunately, I get the following error: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference.
Is there any way to add data from each call to LiveData<List<AddressResponse>> allAddresses ?
I believe this what you need to change this
allAddresses.getValue().add(response.body());
to this:
allAddresses.postValue(response.body())
If want to post or add a task to the main thread of the application whenever there is a change in the value then use:
allAddresses.postValue(response.body())
While the setValue() method is used to set the changed value i.e. the change value will be dispatched to the active observer of the application:
allAddresses.setValue(response.body())
First it's better to create instance of your LiveData in getter method not in top of your class like this:
Public LiveData<List<ResponseAddress> getAddress(){
if(allAddress == Null)
allAddress = new MutableLiveData ();
return allAddress;
}
Then ensure your response body is not null :
if(response.body() != null ){
// Replacement Bellow
}
And in your if statement body just Replace :
allAddresses.getValue().add(response.body());
With this :
allAddresses.setValue(response.body());
I'm trying to test that an error dialog appear when an exception is thrown. For that i want to emulate an UninitializedPropertyAcessException to test this piece of code :
try {
account.solde?.let { view?.displaySolde(it) }
} catch (ex : Exception) {
view?.displayErrorMessage()
}
And my test looks like this :
#Before
fun setUp() {
view = mock(AccountDetailActivity::class.java)
presenter = AccountDetailPresenterImpl(
mock(OperationServiceFactory::class.java),
mock(StatisticsHelper::class.java)
)
presenter.view = view
}
#Test
fun testAccountIsNotInitialized() {
presenter.account = null
verify(view).displayErrorMessage()
}
But the parameter account can not be null or not initialized because it is a non-null type.
Have you a workaround to test that the error dialog is correctly shown ?
Thanks
I've already added onErrorReturn and doOnError, but I still get fatal error. Here's my code:
apiInterface.submitDataToAnalyze("dataToAnalyze", HelperFunctions.authenticationData, 1, uuid, dataToAnalyze.toString(), todayDate)
.onErrorReturn(new Func1<Throwable, BasicResponse>() {
#Override
public BasicResponse call(Throwable throwable) {
Log.e(FILE_NAME, "submitDataToAnalyze throwable??");
Log.e(FILE_NAME, throwable.getMessage().toString());
return null;
}
})
.flatMap(new Func1<BasicResponse, Observable<LocationSuggestion>>() {
#Override
public Observable<LocationSuggestion> call(BasicResponse basicResponse) {
Log.v(FILE_NAME, "basicResponse: " + basicResponse.toString());
if (basicResponse.getResult() == 1) {
//update TABLE_REQUEST_SUGGESTIONS with serverResponse = 1
dbc.updateRequestSuggestionLog(strTodayDate, strDataToAnalyze, basicResponse.getResult());
return apiInterface.getSuggestion("getSuggestion", HelperFunctions.authenticationData, HelperFunctions.requestVersion, uuid,
strLocationLat, strLocationLng, radius, requestForDate);
} else {
return Observable.just(null);
}
}
}).doOnError(new Action1<Throwable>() {
#Override
public void call(Throwable t) {
Log.e(FILE_NAME, "masuk doOnError??");
Log.e(FILE_NAME, t.getMessage().toString());
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe();
}
Specifically, here's the error message:
E/ISRS: masuk doOnError??
E/ISRS: masuk 22??
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Exception thrown on Scheduler.Worker thread. Add `onError` handling.
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:60)
Additional information: the fatal error would occur if submitDataToAnalyze() has problem connecting to my server due to bad connection etc
In onErrorReturn method you return null, and then this null is propagated further along the chain. So it causes NPE (eg basicResponse.toString()). In this case doOnError is invocated, but your subscriber still get Throwable, that stays unhandled.
So you have to pass Subscriber instance with onError implementation.
Another option: in your chain you can use something like onErrorResumeNext(Observable.empty()), so it'll emit nothing and then complete. In this case you are have not to pass Subscriber implementation to subscribe.
I am getting the following exception in my application...
java.lang.RuntimeException: Could not dispatch event: class com.example.event.SelectedOptionsChangedEvent to handler [EventHandler public void com.example.activity.MainActivity.onSelectedOptionsChanged(com.example.event.SelectedOptionsChangedEvent)]Attempt to read from field 'int com.example.model.Option.id' on a null object reference
I am not able to resolve the error..please help..!
in the MainActivity i have a method :
#Subscribe
public void onSelectedOptionsChanged( SelectedOptionsChangedEvent optionsChanged )
{
if( Fragment != null )
{
Fragment.setSelectedOptions( AppController.getInstance().getSelectedOptions() );
}
}
I have a class :
public class SelectedOptionsChangedEvent
{
public SelectedOptionsChangedEvent()
{
}
}