how to get same realm instance between two activitys? - android

public class MyApp extends MultiDexApplication {
private static MyApp instance;
private static class LazyHolder {
private static final Realm INSTANCE = Realm.getDefaultInstance();
}
public static Realm getRealm() {
return LazyHolder.INSTANCE;
}
public static Context getContext() {
return instance;
}
#Override
public void onCreate() {
instance = this;
super.onCreate();
Realm.init(this);
}
}
this is my application activity.
one recyclerView Adapter is using two activities.
first, normal Article List Activity.
second, find Article List Activity.
when I select an Article with the same Url for any Activity, I want to save the Url for that Article.
And this is how I determine if it's stored in Realm in onBindViewHolder().
RealmResults<Article> results = MyApp.getRealm().where(Article.class).equalTo("link", list.get(position).getLink()).findAll();
boolean isSeenArticle = results.size() >= 1;
if(hasKeyword(position)) {
String[] temp = list.get(position).getTitle().split(keyword);
setTitleSpannable(holder.title, temp, isSeenArticle);
}
else {
holder.title.setText(list.get(position).getTitle());
holder.title.setTextColor(isSeenArticle ? context.getResources().getColor(R.color.OneDarkSemiSemiGray) : context.getResources().getColor(R.color.textColorPrimary));
}
color of the holder.articler_title text changes on one side only.
However, both activities appear to have different Realm Instances.
How can I use the same Realm Instance?

Related

Observing changes in Room Database table using ItemKeyedDataSource

I have implemented class which extends ItemKeyedDataSource and provides paging data from room database's data access object (DAO). My DAO's query methods pass lists of data objects (not wrapped by LiveData) to DataSource callbacks.
What is the recommended way to invalidate DataSource after changes occur in it's wrapped database table, for example if changes come from background Service? How automatic data invalidation is implemented in DataSource.Factory<Integer, T> return parameter that DAOs can generate?
Automatic DataSource invalidation can be implemented by hooking InvalidationTracker.Observer to InvalidationTracker.
You can get InvalidationTracker instance from getInvalidationTracker().
I implemented my InvalidationTracker.Observer like this:
public class DataSourceTableObserver extends InvalidationTracker.Observer {
private DataSource dataSource;
public DataSourceTableObserver(#NonNull String tableName) {
super(tableName);
}
#Override
public void onInvalidated(#NonNull Set<String> tables) {
if (dataSource != null) dataSource.invalidate();
}
public void setCurrentDataSource(DataSource source) {
dataSource = source;
}
}
And I'm using it in my inner DataSource.Factory class like this:
public static class Factory implements DataSource.Factory<TvProgram, TvProgram> {
private Context appContext;
private DataSourceTableObserver observer;
private InvalidationTracker tracker;
private int channelId;
public Factory(Context context, int channelId) {
appContext = context.getApplicationContext();
observer = new DataSourceTableObserver(AppDatabase.PROGRAMS_TABLE);
tracker = AppDatabase.getInstance(appContext).getInvalidationTracker();
tracker.addObserver(observer);
this.channelId = channelId;
}
#Override
public DataSource<TvProgram, TvProgram> create() {
EpgDataSource epgDataSource = new EpgDataSource(appContext, channelId);
observer.setCurrentDataSource(epgDataSource);
return epgDataSource;
}
public void cleanUp() {
tracker.removeObserver(observer);
observer = null;
}
}
When DataSourceTableObserver invalidates DataSource, it's Factory inner class creates new DataSource instance with newest data.

How do I prevent Mortar scopes from persisting across screens?

I have an app set up using Mortar/Flow and Dagger 2. It seems to work except for when I switch between two views of the same class. The new view ends up with the previous view's presenter.
For example, I have a ConversationScreen that takes a conversationId as a constructor argument. The first time I create a ConversationScreen and add it to Flow it creates the ConversationView which injects itself with a Presenter which is created with the conversationId that was passed to the screen. If I then create a new ConversationScreen with a different conversationId, when the ConversationView asks for a Presenter, Dagger returns the old Presenter, because the scope has not yet closed on the previous ConversationScreen.
Is there a way for me to manually close the scope of the previous screen before I set up the new one? Or have I just set up the scoping wrong to begin with?
ConversationView
public class ConversationView extends RelativeLayout {
#Inject
ConversationScreen.Presenter presenter;
public ConversationView(Context context, AttributeSet attrs) {
super(context, attrs);
DaggerService.<ConversationScreen.Component>getDaggerComponent(context).inject(this);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
presenter.takeView(this);
}
#Override
protected void onDetachedFromWindow() {
presenter.dropView(this);
super.onDetachedFromWindow();
}
}
ConversationScreen
#Layout(R.layout.screen_conversation)
public class ConversationScreen extends Paths.ConversationPath implements ScreenComponentFactory<SomeComponent> {
public ConversationScreen(String conversationId) {
super(conversationId);
}
#Override
public String getTitle() {
title = Conversation.get(conversationId).getTitle();
}
#Override
public Object createComponent(SomeComponent parent) {
return DaggerConversationScreen_Component.builder()
.someComponent(parent)
.conversationModule(new ConversationModule())
.build();
}
#dagger.Component(
dependencies = SomeComponent.class,
modules = ConversationModule.class
)
#DaggerScope(Component.class)
public interface Component {
void inject(ConversationView conversationView);
}
#DaggerScope(Component.class)
#dagger.Module
public class ConversationModule {
#Provides
#DaggerScope(Component.class)
Presenter providePresenter() {
return new Presenter(conversationId);
}
}
#DaggerScope(Component.class)
static public class Presenter extends BasePresenter<ConversationView> {
private String conversationId;
#Inject
Presenter(String conversationId) {
this.conversationId = conversationId;
}
#Override
protected void onLoad(Bundle savedInstanceState) {
super.onLoad(savedInstanceState);
bindData();
}
void bindData() {
// Show the messages in the conversation
}
}
}
If you use the default ScreenScoper and PathContextFactory classes from Mortar/Flow example project, you will see that the name of the new scope to create is the name of the Screen class.
Because you want to navigate from one instance of ConversationScreen to another instance of ConversationScreen, the name of the new scope will be equal to the name of previous scope. Thus, you won't create a new Mortar scope but just reuse the previous one, which means reusing the same presenter.
What you need is to change the naming policy of the new scope. Rather than using only the name of the new screen class, add something else.
Easiest fix is to use the instance identifier: myScreen.toString().
Another better fix is to have a tracking of the screen/scope names.
Following example extracted from https://github.com/lukaspili/Mortar-architect
class EntryCounter {
private final SimpleArrayMap<Class, Integer> ids = new SimpleArrayMap<>();
int get(History.Entry entry) {
Class cls = entry.path.getClass();
return ids.containsKey(cls) ? ids.get(cls) : 0;
}
void increment(History.Entry entry) {
update(entry, true);
}
void decrement(History.Entry entry) {
update(entry, false);
}
private void update(History.Entry entry, boolean increment) {
Class cls = entry.path.getClass();
int id = ids.containsKey(cls) ? ids.get(cls) : 0;
ids.put(cls, id + (increment ? 1 : -1));
}
}
And then use this counter when creating new scope:
private ScopedEntry buildScopedEntry(History.Entry entry) {
String scopeName = String.format("ARCHITECT_SCOPE_%s_%d", entry.path.getClass().getName(), entryCounter.get(entry));
return new ScopedEntry(entry, MortarFactory.createScope(navigator.getScope(), entry.path, scopeName));
}
And in some other place, i'm incrementing/decrementing the counter if new scope is pushed or scope is detroyed.
The scope in ScreenScoper is based on a string, which if you create the same path, it will use the same name as it bases it on the class name of your path.
I solved this by removing some noise from the ScreenScoper, considering I'm not using #ModuleFactory in my Dagger2-driven project anyways.
public abstract class BasePath
extends Path {
public abstract int getLayout();
public abstract Object createComponent();
public abstract String getScopeName();
}
public class ScreenScoper {
public MortarScope getScreenScope(Context context, String name, Object screen) {
MortarScope parentScope = MortarScope.getScope(context);
return getScreenScope(parentScope, name, screen);
}
/**
* Finds or creates the scope for the given screen.
*/
public MortarScope getScreenScope(MortarScope parentScope, final String name, final Object screen) {
MortarScope childScope = parentScope.findChild(name);
if (childScope == null) {
BasePath basePath = (BasePath) screen;
childScope = parentScope.buildChild()
.withService(DaggerService.TAG, basePath.createComponent())
.build(name);
}
return childScope;
}
}

How to pass values without using argument in android

Friends In My Application , i want to use text box value in
all other activity without passing any argument. how it's possible? Anyone
know these give me a example, thanks in advance. by Nallendiran.S
There are a few different ways you can achieve what you are asking for.
1.) Extend the application class and instantiate your controller and model objects there.
public class FavoriteColorsApplication extends Application {
private static FavoriteColorsApplication application;
private FavoriteColorsService service;
public FavoriteColorsApplication getInstance() {
return application;
}
#Override
public void onCreate() {
super.onCreate();
application = this;
application.initialize();
}
private void initialize() {
service = new FavoriteColorsService();
}
public FavoriteColorsService getService() {
return service;
}
}
Then you can call the your singleton from your custom Application object at any time:
public class FavoriteColorsActivity extends Activity {
private FavoriteColorsService service = null;
private ArrayAdapter<String> adapter;
private List<String> favoriteColors = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorite_colors);
service = ((FavoriteColorsApplication) getApplication()).getService();
favoriteColors = service.findAllColors();
ListView lv = (ListView) findViewById(R.id.favoriteColorsListView);
adapter = new ArrayAdapter<String>(this, R.layout.favorite_colors_list_item,
favoriteColors);
lv.setAdapter(adapter);
}
2.) You can have your controller just create a singleton instance of itself:
public class Controller {
private static final String TAG = "Controller";
private static sController sController;
private Dao mDao;
private Controller() {
mDao = new Dao();
}
public static Controller create() {
if (sController == null) {
sController = new Controller();
}
return sController;
}
}
Then you can just call the create method from any Activity or Fragment and it will create a new controller if one doesn't already exist, otherwise it will return the preexisting controller.
3.) Finally, there is a slick framework created at Square which provides you dependency injection within Android. It is called Dagger. I won't go into how to use it here, but it is very slick if you need that sort of thing.
I hope I gave enough detail in regards to how you can do what you are hoping for.
Create it static type and than you can get it where you want.
Private TextVeiw txtvw;
Public static String myText="";
myText=txtvw.getText();
Access this variable with class name in which it defined.
MyActivity.myString

How to declare a variable that can be accessed by all the classes in android?

I'm a new to android please help me with the following.
I'm having an integer value which stores the id of a checked radiobutton. I need to access this value throughout the various classes of my app for a validation purpose.
Please let me know how to declare and access this variable from all the classes.
Thank you.
U can use:
MainActivity.class
Public static int myId;
In other Activities.
int otherId=MainActivity.myId;
following singleton pattern is the only way to do this.in java/android if u create a instance for a class every time it create a new object.what you should do is
1.create a model class and make its as singleton
2.try to access the modelclass from every class
public class CommonModelClass
{
private static CommonModelClass singletonObject;
/** A private Constructor prevents any other class from instantiating. */
private CommonModelClass()
{
// Optional Code
}
public static synchronized CommonModelClass getSingletonObject()
{
if (singletonObject == null)
{
singletonObject = new CommonModelClass();
}
return singletonObject;
}
/**
* used to clear CommonModelClass(SingletonClass) Memory
*/
public void clear()
{
singletonObject = null;
}
public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
//getters and setters starts from here.it is used to set and get a value
public String getcheckBox()
{
return checkBox;
}
public void setcheckBox(String checkBox)
{
this.checkBox = checkBox;
}
}
accessing the model class values from other class
commonModelClass = CommonModelClass.getSingletonObject();
commonModelClass.getcheckBox();
http://javapapers.com/design-patterns/singleton-pattern/
You can declare your integer variable as static and access in any class.Like this
class A{
static int a;
}
You can access in another class like this.
class B{
int b = A.a;
}

Static singleton not initialized in activity. What could be wrong?

I'm trying to track down a new null pointer exception which is appearing in my ACRA logs and which I can't reproduce. Here's the relevant code:
public class MyApplication extends Application {
public void onCreate() {
DataManager.instance().initializeData(this);
}
}
public class DataManager {
private static DataManger instance = new DataManger();
private List<DataModel> dataModels;
private List<I_Callback> callbacks = new ArrayList<I_Callback>();
private boolean isInitialized = false;
private DataManager(){}
public static DataManager instance() {
return instance;
}
public void initializeData(Context context) {
new DataManagerInitializer().execute(context);
}
public void setDataModels(List<DataModel> models) {
dataModels = models;
}
public void synchronized registerInitializeCallbacks(I_Callback callback) {
if (isInitialized) {
callback.executeCallback();
} else {
callbacks.add(callback);
}
}
public void synchronized setInitialized() {
isInitialized = true;
for (I_Callback callback:callbacks) {
callback.executeCallback();
}
callbacks.clear();
}
}
public class DataManagerInitializer extends AsyncTask<Context, Void, Void>{
protected Void doInBackground(Context... contexts){
List<DataModel> dataModels = new ArrayList<DataModel>();
/*various code to create DataModel objects and add to dataModels list*/
DataManager.instance().setDataModels(dataModels);
return null;
}
protected void onPostExecute(Void result) {
DataManager.instance().setInitialized();
}
}
public class ActivityA extends Activity implements I_Callback{
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.graphical_layout);
DataManager.instance().registerInitializeCallbacks(this);
}
public void executeCallback() {
/* wire up button to call Activity B */
}
}
public class ActivityB extends Activity {
public void onCreate(Bundle savedInstanceState) {
List<DataModel> dataModels = DataManager.instance().getDataModels();
/* The following line of code throws a null pointer exception
in the stack trace*/
for (int i=0; i < dataModels.size(); i++){
/* do something with the data model */
}
}
}
To break down the above more simply, the application is launched which kicks off the initializion of the data manager singleton. ActivityA, the main activity, launches and waits for the data manager to complete initialization before allowing any actions, wiring up any events, etc. From ActivityA, its not possible to get to ActivityB without the call back method executing and ActivityB is only reachable from ActivityA. The only way for the list of data models to be null in the DataManager is for it to not have been initialized, but I'm struggling to see how this is possible. Any suggestions on how my null pointer may have occurred?
private static DataManger instance = new DataManger();
...
public static DataManager instance() {
return instance;
}
Is where the problem is. So your instance variable is getting garbage collected. As it is instantiated when it is declared, it is not being appropriately re-instantiated. So, try this instead:
private static DataManger instance = null;
...
public static DataManager instance() {
if (instance == null){
instance = new DataManager();
}
return instance;
}
This will ensure the call to instance() (usually called getInstance() but this is only convention), will return a valid single instance of the datamanager. Try to avoid instantiating global variables with their declaration, to avoid this specific problem.
Let's assume that:
you are interacting with the Activity B
press the home button:
start playing with other apps (consuming memory)
at some point the so needs memory and it's gonna start garbage collecting objects, included your "instance".
If that happens when you launch your app the framework will resume the activity B and the npe will happen.
You need to re-create the instance (in the activity B) if it is null.

Categories

Resources