My Class in not an enclossing class - android

so I have class constructor:
public class HealthDataStore { // this class is 3rd party api - can't modify
public HealthDataStore(Context context, HealthDataStore.ConnectionListener listener){ /* bla... */ }
/* bla... */
// with Listener Interface:
public interface ConnectionListener {
void onConnected();
void onConnectionFailed(HealthConnectionErrorResult var1);
void onDisconnected();
}
}
and in my repository class i have:
public class HealthRepository {
private string DSConnectionStatus;
public void connectDataStore(HealthDSConnectionListener listener) {
mStore = new HealthDataStore(app, listener);
mStore.connectService();
}
// with inner class:
public class HealthDSConnectionListener implements HealthDataStore.ConnectionListener{
#Override public void onConnected() { DSConnectionStatus = "Connected"; }
#Override public void onConnectionFailed(HealthConnectionErrorResult healthConnectionErrorResult) { DSConnectionStatus = "Connection Failed"; }
#Override public void onDisconnected() { DSConnectionStatus = "Disconnected"; }
};
}
and in my view model class i have below object:
public class SplashViewModel extends AndroidViewModel {
public void connectRepoDataStore(){
// repo is object of class HealthRepository
repo.connectDataStore(mConnectionListener)
// other things to do here
}
private final HealthRepository.HealthDSConnectionListener mConnectionListener = new HealthRepository.HealthDSConnectionListener(){
#Override public void onConnected() {
super.onConnected(); // i need this super to set DSConnectionStatus value
// other things to do here
}
#Override public void onConnectionFailed(HealthConnectionErrorResult error) {
super.onConnectionFailed(error); // i need this super to set DSConnectionStatus value
// other things to do here
}
#Override public void onDisconnected() {
super.onDisconnected(); // i need this super to set DSConnectionStatus value
// other things to do here
}
}
why is private final HealthRepository.HealthDSConnectionListener mConnectionListener = new HealthRepository.HealthDSConnectionListener() throw me error that the class is not enclosing class?
then how should i achieve this? to have my final listener class have capability to set DSConnectionStatus in healthrepository class?

Always try to avoid using inner classes if you know you'll have to extend them. Instead use a separate class, and swap the outer class with a field. If you need to modify a private field that you do not want to expose then create a package-private setter.
public class HealthRepository {
private String DSConnectionStatus;
public void connectDataStore(HealthDSConnectionListener listener) {
mStore = new HealthDataStore(app, listener);
mStore.connectService();
}
void setConnectionStatus(String status) {
DSConnectionStatus = status;
}
}
// create another class in the same package
public class HealthDSConnectionListener implements HealthDataStore.ConnectionListener {
private final HealthRepository repo;
public HealthDSConnectionListener(HealthRepository repo) {
this.repo = repo;
}
#Override public void onConnected() { repo.setConnectionStatus("Connected"); }
#Override public void onDisconnected() { repo.setConnectionStatus("Disconnected"); }
#Override public void onConnectionFailed(HealthConnectionErrorResult error) {
repo.setConnectionStatus("Connection Failed");
}
};
public class SplashViewModel extends AndroidViewModel {
private final HealthRepository repo;
public void connectRepoDataStore() {
// repo is object of class HealthRepository
repo.connectDataStore(mConnectionListener)
// other things to do here
}
private final HealthDSConnectionListener mConnectionListener = new HealthDSConnectionListener(repo) {
#Override public void onConnected() {
super.onConnected();
// ...
}
#Override public void onConnectionFailed(HealthConnectionErrorResult error) {
super.onConnectionFailed(error);
// ...
}
#Override public void onDisconnected() {
super.onDisconnected();
// ...
}
}
}

Related

How to access data from a Roomdatabase inside a BroadcastReceiver class

I need to access data from my Room database inside a BroadCastReceiver class, but as you know we need a lifecycle owner to get an instance of ViewModel class as shown below.
public class AlertReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationHelper.sendFinanceLoggingNotification(context);
RecurrenceInfoViewModel recurrenceInfoViewModel = new ViewModelProvider(this).get(RecurrenceInfoViewModel.class);
}
}
when passing "this" as the lifecycle owner android studio is throwing error. Can anyone please guide me from where I can get a lifecycle owner inside a BroadCastReceiver or if you can suggest any other way of accessing the data. Below are my ViewModel and Repository classes
public class RecurrenceInfoViewModel extends AndroidViewModel {
private LiveData<List<RecurrenceInfoEntity>> allRecurrenceInfos;
private RecurrenceInfoRepository recurrenceInfoRepository;
public RecurrenceInfoViewModel(#NonNull Application application) {
super(application);
recurrenceInfoRepository=new RecurrenceInfoRepository(application);
}
public void insertRecurrenceInfo(RecurrenceInfoEntity recurrenceInfoEntity) {
recurrenceInfoRepository.insertRecurrenceInfo(recurrenceInfoEntity);
}
public void updateRecurrenceInfo(RecurrenceInfoEntity recurrenceInfoEntity) {
recurrenceInfoRepository.updateRecurrenceInfo(recurrenceInfoEntity);
}
public void deleteRecurrenceInfo(RecurrenceInfoEntity recurrenceInfoEntity) {
recurrenceInfoRepository.deleteRecurrenceInfo(recurrenceInfoEntity);
}
public void deleteAllRecurrenceInfos() {
recurrenceInfoRepository.deleteAllRecurrenceInfo();
}
public LiveData<RecurrenceInfoEntity> getAllRecurrenceInfos(String recurrenceInfoKey) {
return recurrenceInfoRepository.getRecurrenceInfoEntityList(recurrenceInfoKey);
}
}
public class RecurrenceInfoRepository {
private RecurrenceInfoDao recurrenceInfoEntityDao;
private LiveData<List<RecurrenceInfoEntity>> recurrenceInfoEntityList;
public RecurrenceInfoRepository(Context context) {
MoneyManagerDatabase moneyManagerDatabase = MoneyManagerDatabase.getInstance(context);
recurrenceInfoEntityDao = moneyManagerDatabase.getRecurrenceInfoDao();
recurrenceInfoEntityList = recurrenceInfoEntityDao.getAllRecurrenceInfo();
}
public void insertRecurrenceInfo(RecurrenceInfoEntity data) {
new PerformSingleColumnDataOperations(recurrenceInfoEntityDao,
Constants.INSERT_SINGLE_NODE_DATABASE_OPERATION).execute(data);
}
public void updateRecurrenceInfo(RecurrenceInfoEntity data) {
new PerformSingleColumnDataOperations(recurrenceInfoEntityDao,
Constants.UPDATE_SINGLE_NODE_DATABASE_OPERATION).execute(data);
}
public void deleteRecurrenceInfo(RecurrenceInfoEntity data) {
new PerformSingleColumnDataOperations(recurrenceInfoEntityDao,
Constants.DELETE_SINGLE_NODE_DATABASE_OPERATION).execute(data);
}
public void deleteRecurrenceInfo(String type) {
new PerformSingleColumnDataOperations(recurrenceInfoEntityDao,
Constants.DELETE_SINGLE_NODE_DATABASE_OPERATION).execute();
}
public void deleteAllRecurrenceInfo() {
new PerformSingleColumnDataOperations(recurrenceInfoEntityDao,
Constants.DELETE_ALL_NODES_DATABASE_OPERATION).execute();
}
public LiveData<RecurrenceInfoEntity> getRecurrenceInfoEntityList(String key) {
return recurrenceInfoEntityDao.getAllRecurrenceInfo(key);
}
private static class PerformSingleColumnDataOperations extends AsyncTask<RecurrenceInfoEntity, Void, Void> {
private RecurrenceInfoDao dataDao;
private String operationType;
PerformSingleColumnDataOperations(RecurrenceInfoDao dataDao, String operationType) {
this.dataDao = dataDao;
this.operationType = operationType;
}
#Override
protected Void doInBackground(RecurrenceInfoEntity... recurrenceInfoEntities) {
switch (operationType) {
case Constants.INSERT_SINGLE_NODE_DATABASE_OPERATION:
dataDao.insertRecurrenceInfo(recurrenceInfoEntities[0]);
break;
case Constants.UPDATE_SINGLE_NODE_DATABASE_OPERATION:
dataDao.updateRecurrenceInfo(recurrenceInfoEntities[0]);
break;
case Constants.DELETE_SINGLE_NODE_DATABASE_OPERATION:
dataDao.deleteRecurrenceInfo(recurrenceInfoEntities[0]);
break;
case Constants.DELETE_ALL_NODES_DATABASE_OPERATION:
dataDao.deleteAllRecurrenceInfo();
}
return null;
}
}
}
Thanks in advance.
I have solved the above problem by NOT using LiveData.
You can access data from Room anywhere by just providing the ApplicationContext as shown below.
DAO:
#Query("SELECT * FROM reference_info where recurrenceInfoPrimaryKey=:recurrenceinfoprimkey")
RecurrenceInfoEntity getAllRecurrenceInfoWithOutLiveData(String recurrenceinfoprimkey);
Repository:
public RecurrenceInfoEntity getRecurrenceInfoEntityWithOutLiveData(String key) {
return recurrenceInfoEntityDao.getAllRecurrenceInfoWithOutLiveData(key);
}
BroadCastReceiver:
public class AlertReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
new Thread(() -> {
RecurrenceInfoEntity recurrenceInfoEntity =
recurrenceInfoRepository.getRecurrenceInfoEntityWithOutLiveData(Constants.LOG_FINANCES_RECURRENCE_KEY);
}).start();
}

Xposed - I can print inner class methods, but method hooking doesn't work

I'm trying to hook a method in inner class, but nothing happen, while I can print all the methods of that class.
All of the logs printed except which is in the replaceHookedMethod.
public class Keyguard implements IXposedHookLoadPackage {
#Override
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
if (!lpparam.packageName.equals("com.android.keyguard"))
return;
XposedBridge.log("we are in keyguard!");
Class HwClockView = XposedHelpers.findClass("com.android.keyguard.AbsClockView$HwClockView",
lpparam.classLoader);
for (Method m : HwClockView.getDeclaredMethods()) {
XposedBridge.log("method: " + m.getName());
}
XposedHelpers.findAndHookMethod(HwClockView, "getDateString",
TimeZone.class, new XC_MethodReplacement() {
#Override
protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
XposedBridge.log("we are in getDateString!");
return String.format("%s", Utils.getPersianDateShort());
}
});
}
Update:
After second comment changed code to this, but same as before nothing happens:
public class Keyguard implements IXposedHookLoadPackage {
#Override
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) {
if (!lpparam.packageName.equals("com.android.keyguard"))
return;
XposedBridge.log("we are in keyguard!");
Class HwClockView = XposedHelpers.findClass("com.android.keyguard.AbsClockView$HwClockView",
lpparam.classLoader);
for (Method m : HwClockView.getDeclaredMethods()) {
XposedBridge.log("method: " + m.getName());
if ("getDateString".equalsIgnoreCase(m.getName())) {
XposedBridge.hookMethod(m, new XC_MethodReplacement() {
#Override
protected Object replaceHookedMethod(MethodHookParam param) {
XposedBridge.log("we are in getDateString!");
return String.format("%s", Utils.getPersianDateShort());
}
});
}
}
}
Target class:
public class AbsClockView extends RelativeLayout {
protected Calendar mCalendar;
private HwCustKeyguardStatusViewEx mCustKeyguardStatusViewEx;
protected TextView mDateView;
protected TextView mDescriptionView;
protected Factory mFactory;
protected final AtomicBoolean mFixedTimeZone;
protected FrameLayout mTimeParent;
protected TextView mTimeView;
public interface Factory {
void refreshDate();
void setHwDateFormat();
void updateHwTimeStyle();
}
private class HwClockView implements Factory {
protected Context mContext;
public HwClockView(Context context) {
...
}
private CharSequence getDateString(TimeZone timeZone) {
return someString;
}
}
public AbsClockView(Context context) {
this(context, null);
}
}

How to notify activity when repository class gets the data?

I'm new in android architecture component. this is my code , i'm at the point that I don't know how to notify my activity and get the results back
these are my codes:
Activity:
private void iniViewModels() {
Observer<List<User>>usersObserver=new Observer<List<User>>() {
#Override
public void onChanged(#Nullable List<User> users) {
Log.v("this","LiveData: ");
for (int i=0;i<users.size();i++){
Log.v("this",users.get(i).getName());
}
}
};
mViewModel = ViewModelProviders.of(this)//of-->name of act or fragment
.get(AcActivityViewModel.class);///get -->the name of viewModelClass
mViewModel.mUsers.observe(this,usersObserver);
}
this is my viewModel Class:
public class IpStaticViewModel extends AndroidViewModel {
public LiveData<List<Ipe>> ips;
private AppRepository repository;
public IpStaticViewModel(#NonNull Application application) {
super(application);
repository=AppRepository.getInstance(application.getApplicationContext());
}
public void getIpStatics() {
repository.getStaticIps();
}
}
this is my repository class:
public class AppRepository {
private static AppRepository ourInstance ;
private Context context;
private IpStaticInterface ipInterface;
public static AppRepository getInstance(Context context) {
if (ourInstance == null) {
ourInstance=new AppRepository(context);
}
return ourInstance;
}
private AppRepository(Context context) {
this.context=context;
}
public void getStaticIps() {
ipInterface= ApiConnection.getClient().create(IpStaticInterface.class);
ipInterface.getIpes()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new SingleObserver<IpStaticList>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onSuccess(IpStaticList ipStaticList) {
List<Ipe>ips=ipStaticList.getIpes();
}
#Override
public void onError(Throwable e) {
Log.v("this","Eror "+ e.getMessage());
}
});
}
}
I'm using retrofit for fetching the data ,it fetch the data successfully but I don't know how to notify my activity
can you help me?
Have a MutableLiveData
final MutableLiveData<List<Ipe>> data = new MutableLiveData<>();
In onSucess
public MutableLiveData<List<Ipe>> getStaticIps() {
ipInterface= ApiConnection.getClient().create(IpStaticInterface.class);
ipInterface.getIpes()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new SingleObserver<IpStaticList>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onSuccess(IpStaticList ipStaticList) {
List<Ipe>ips=ipStaticList.getIpes();
data.setValue(ips);
}
#Override
public void onError(Throwable e) {
Log.v("this","Eror "+ e.getMessage());
}
});
return data;
}
In repository expose this to viewmodel
public LiveData<List<Ipe>> getIpStatics() {
return repository.getStaticIps();
}
In Activity you observe the livedata
IpStaticViewModel viewmodel = ViewModelProviders.of(this
.get(IpStaticViewModel.class)
viewModel.getIpStatics().observe(this, new Observer<List<Ipe>>() {
#Override
public void onChanged(#Nullable List<Ipe> ipes) {
if (ipes != null) {
// dosomething
}
}
});
If you want to generalize your response in case you have a error or something have a look at https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/vo/Resource.kt

Is it possible to make 2 or more DataBindingComponent?

I would like to ask is it possible to make 2 or more DataBindingComponent class in android? because i want to escape the static method in binding so i try to use the injection with DataBindingComponent but I got the error of Class 'AppDataBindingComponent' must be either be declared abstract or implement abstract method 'getLoginViewDataBinding' in 'DataBindingComponent' because of this error I can't make the non-static one.
this is the class which i got the problem
public class AppDataBindingComponent implements android.databinding.DataBindingComponent {
#Override
public RecyclerViewDataBinding getRecyclerViewDataBinding() {
return new RecyclerViewDataBinding();
}
}
First binding class
public class RecyclerViewDataBinding {
#BindingAdapter({"app:adapter", "app:data"})
public void bind(RecyclerView recyclerView, DataAdapter adapter, List<DataModel> data) {
recyclerView.setAdapter(adapter);
adapter.updateData(data);
}
}
Second Binding Class
public class LoginViewDataBinding {
#BindingAdapter({"validation", "errorMsg"})
public void setErrorEnable(TextInputLayout textInputLayout, StringRule stringRule,
final String errorMsg) {
Observable<CharSequence> textObservable = RxTextView.textChanges(
Objects.requireNonNull(textInputLayout.getEditText()));
compositeDisposable.add(textObservable
.map(charSequence -> {
......
})
.distinctUntilChanged()
.replay(1).refCount()
.subscribe());
}
}
In the Main Class I call the DataBindingComponent
public class MainActivity extends AppCompatActivity {
private DataViewModel dataViewModel;
private ActivityMainListMvvmBinding activityBinding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bind();
}
private View bind() {
activityBinding = DataBindingUtil
.setContentView(this, R.layout.activity_main_list_mvvm, new AppDataBindingComponent());
dataViewModel = new DataViewModel();
activityBinding.setViewModel(dataViewModel);
return activityBinding.getRoot();
}
}
The problem is solved if I put getLoginViewDataBinding
public class AppDataBindingComponent implements android.databinding.DataBindingComponent {
#Override
public RecyclerViewDataBinding getRecyclerViewDataBinding() {
return new RecyclerViewDataBinding();
}
#Override
public LoginViewDataBinding getLoginViewDataBinding() {
return null;
}
}
the answers that I want is somehow like this: (is this possible?)
public class AppDataBindingComponent implements android.databinding.DataBindingComponent {
#Override
public RecyclerViewDataBinding getRecyclerViewDataBinding() {
return new RecyclerViewDataBinding();
}
}
public class LoginDataBindingComponent implements android.databinding.DataBindingComponent {
#Override
public LoginViewDataBinding getLoginViewDataBinding() {
return null;
}
}
What about this:
public class DataBindingComponent<T> implements android.databinding.DataBindingComponent {
private T activity;
public DataBindingComponent(T activity) {
this.activity = activity;
}
public LoginViewDataBinding getLoginViewDataBinding() {
return (LoginViewDataBinding) activity;
}
public RecyclerViewDataBinding getRecyclerViewDataBinding() {
return (RecyclerViewDataBinding) activity;
}
}
And than create in both of your class's:
new AppDataBindingComponent(this)

Call a method in the calling class on API success in android

I use the following class to make an API call in android using Retrofit
public Class Checkin {
public static void checkinViaApi(CheckinSendModel checkinSendModel) {
final ApiHandler apiHandler = new ApiHandler();
apiHandler.setApiResponseListener(new ApiResponseListener() {
#Override
public void onApiResponse(ApiResponseModel apiResponse) {
Log.i("CheckedIn","true");
}
#Override
public void onApiException(Error error) {
Log.i("fail",error.getErrorMessage());
}
});
List<CheckinSendModel> checkinSendModelList = new ArrayList<CheckinSendModel>();
checkinSendModelList.add(checkinSendModel);
Call<ApiResponseModel> request = RetrofitRestClient.getInstance().checkinToMainEvent(checkinSendModelList,Constant.API_KEY);
apiHandler.getData(request);
}
}
I call that method as follows:
Checkin.checkinViaApi(checkinSendModelObject);
Now, when the API call is successful, I want to execute a function checkedInSuccessfully() in the class from where I make the call. How can I do it?
Thanks in advance
Pass in the response interface.
public class Checkin {
public static void checkinViaApi(CheckinSendModel checkinSendModel, ApiResponseListener listener) {
final ApiHandler apiHandler = new ApiHandler();
apiHandler.setApiResponseListener(listener);
Other class - Call that method
CheckinSendModel model;
Checkin.checkinViaApi(model, new ApiResponseListener() {
#Override
public void onApiResponse(ApiResponseModel apiResponse) {
Log.i("CheckedIn","true");
checkedInSuccessfully();
}
#Override
public void onApiException(Error error) {
Log.i("fail",error.getErrorMessage());
}
);
Interface is your handy man. Create an interface like below.
Interface CheckInListener {
void onCheckIn();
}
Change the checkinViaApi() to below signature.
public static void checkinViaApi(CheckinSendModel checkinSendModel, CheckinListener listener) {
#Override
public void onApiResponse(ApiResponseModel apiResponse) {
Log.i("CheckedIn","true");
listener.onCheckIn();
}
}
When you call the above function you can provide an instance of the interface.
Checkin.checkinViaApi(checkinSendModelObject, new CheckInListener() {
#Override
void onCheckIn() {
//Do your action here
}
});

Categories

Resources