Java Code Examples for android.arch.lifecycle.ViewModelProviders

The following are top voted examples for showing how to use android.arch.lifecycle.ViewModelProviders. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GSoC-Info-Android   File: MainPageFragment.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_about, container, false);
    RecyclerView recyclerView = view.findViewById(R.id.rv_timeline);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

    MainPageViewModel mainPageViewModel = ViewModelProviders.of(getActivity()).get(MainPageViewModel.class);
    timelineAdapter = new TimelineAdapter();
    recyclerView.setAdapter(timelineAdapter);
    mainPageViewModel.getMainPageCopy().observe(this, new Observer<MainPage.Copy>() {
        @Override
        public void onChanged(@Nullable MainPage.Copy copy) {
            timelineAdapter.setData(copy);
        }
    });
    return view;
}
 
Example 2
Project: file.io-app   File: MainActivity.java   Source Code and License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);

    /* Animate the views */
    MaterialIn.animate(rootView);

    /* Get the view model */
    uploadItemViewModel = ViewModelProviders.of(this).get(UploadItemViewModel.class);

    /* Handle incoming intent content */
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();
    // FIXME: Google photos URI
    if (type != null) {
        Log.d(TAG, "Receive Type: " + type);
        Uri fileUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
        Log.d(TAG, "\nURI: " + fileUri);
        if (Intent.ACTION_SEND.equals(action) && fileUri != null) {
            handleExplicitFileShare(intent);
        }
    }
    linkTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Copy the content of the link text to Clipboard
            ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            ClipData clipData = ClipData.newPlainText("link", linkTextView.getText());
            if (clipboardManager != null) {
                clipboardManager.setPrimaryClip(clipData);
                Toast.makeText(MainActivity.this, getString(R.string.link_copy), Toast.LENGTH_SHORT).show();
            }
        }
    });
}
 
Example 3
Project: android-arch-mvvm   File: LoginActivity.java   Source Code and License 6 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_activity_layout);

    // step0 获取相关的viewModel
    mLoginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);

    // step1 获取view
    mLoginBtn = (Button) findViewById(R.id.loginBtn);

    // step2 设置监听
    mLoginBtn.setOnClickListener(this);

    // setp3 绑定数据
    mLoginViewModel.loginResult.observe(this, mLoginObserver);
}
 
Example 4
Project: MVVMArms   File: WeatherDailyFragment.java   Source Code and License 6 votes vote down vote up
@Override
public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //获取 Activity 的ViewModel 来共享数据
    mWeatherViewModel = ViewModelProviders.of(getActivity(), mViewModelFactory).get(WeatherViewModel.class);
    mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(WeatherDailyViewModel.class);
    mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_weather_daily, container, false);
    //设置ViewModel
    mBinding.setViewModel(mViewModel);
    mBinding.retry.setViewModel(mViewModel);
    mBinding.retry.setRetry(mViewModel);
    mBinding.weatherSource.setViewModel(mViewModel);
    //RecyclerView设置Adapter
    mBinding.recyclerWeatherDaily.setAdapter(mAdapter);
    //设置Refresh
    mBinding.refresh.setColorSchemeColors(
            ContextCompat.getColor(getContext(), R.color.colorPrimary),
            ContextCompat.getColor(getContext(), R.color.colorAccent),
            ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
    return mBinding.getRoot();
}
 
Example 5
Project: friendlyeats-android   File: MainActivity.java   Source Code and License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    setSupportActionBar(mToolbar);

    // View model
    mViewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);

    // Enable Firestore logging
    FirebaseFirestore.setLoggingEnabled(true);

    // Initialize Firestore and the main RecyclerView
    initFirestore();
    initRecyclerView();

    // Filter Dialog
    mFilterDialog = new FilterDialogFragment();
}
 
Example 6
Project: MVP-Architecture-Components   File: BaseActivity.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@CallSuper
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    BaseViewModel<V, P> viewModel = ViewModelProviders.of(this).get(BaseViewModel.class);
    boolean isPresenterCreated = false;
    if (viewModel.getPresenter() == null) {
        viewModel.setPresenter(initPresenter());
        isPresenterCreated = true;
    }
    presenter = viewModel.getPresenter();
    presenter.attachLifecycle(getLifecycle());
    presenter.attachView((V) this);
    if (isPresenterCreated)
        presenter.onPresenterCreated();
}
 
Example 7
Project: MVP-Architecture-Components   File: BaseFragment.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@CallSuper
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    BaseViewModel<V, P> viewModel = ViewModelProviders.of(this).get(BaseViewModel.class);
    boolean isPresenterCreated = false;
    if (viewModel.getPresenter() == null) {
        viewModel.setPresenter(initPresenter());
        isPresenterCreated = true;
    }
    presenter = viewModel.getPresenter();
    presenter.attachLifecycle(getLifecycle());
    presenter.attachView((V) this);
    if (isPresenterCreated)
        presenter.onPresenterCreated();
}
 
Example 8
Project: recyclerview-android   File: MultipleChoiceModeExampleActivity.java   Source Code and License 6 votes vote down vote up
@Override
protected void onCreate(@Nullable final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_multiple_choice_mode_example);

    final PersonsViewModel viewModel = ViewModelProviders.of(this).get(PersonsViewModel.class);
    final Datasource<Person> datasource = viewModel.getDatasource();
    final CheckedPersonsAdapter adapter = new CheckedPersonsAdapter(datasource, true);

    mRecyclerView = (RecyclerView) findViewById(android.R.id.list);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    mRecyclerView.setAdapter(adapter);

    mChoiceMode = new MultipleChoiceMode(savedInstanceState);
    mChoiceMode.setChoiceModeListener(this::onItemCheckedChanged);
    mChoiceModeHelper = new ChoiceModeHelper<>(adapter, mChoiceMode);
    mChoiceModeHelper.setRecyclerView(mRecyclerView);

    findViewById(R.id.action_clear_choices).setOnClickListener(v -> mChoiceMode.clearChoices());
    findViewById(R.id.action_get_checked_items).setOnClickListener(v -> showCheckedItems());
}
 
Example 9
Project: app-android   File: VmTestActivity.java   Source Code and License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_vm_test);
    ButterKnife.bind(this);

    testViewModel = ViewModelProviders.of(this).get(TestViewModel.class);
    testViewModel.getMutableIntList().observe(this, list -> {
        Timber.d("trigger %s", list);
        if (list != null) {
            textNumList.setText(list.toString());
        }
    });

    setSupportActionBar(toolbar);
    if (getSupportActionBar() != null)
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}
 
Example 10
Project: recyclerview-android   File: SingleModalChoiceModeExampleActivity.java   Source Code and License 6 votes vote down vote up
@Override
protected void onCreate(@Nullable final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_single_modal_choice_mode_example);
    
    mViewModel = ViewModelProviders.of(this).get(PersonsViewModel.class);
    final Datasource<Person> datasource = mViewModel.getDatasource();
    final ActivatedPersonsAdapter adapter = new ActivatedPersonsAdapter(datasource);
    
    mRecyclerView = (RecyclerView) findViewById(android.R.id.list);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    mRecyclerView.setAdapter(adapter);
    
    final ActionModeCompat actionMode = ActionModeCompat.from(this);
    mChoiceMode = new SingleModalChoiceMode(actionMode, mModalChoiceModeListener, savedInstanceState);
    // mChoiceMode.setStartOnSingleTapEnabled(true);
    // mChoiceMode.setFinishActionModeOnClearEnabled(false);
    
    mChoiceModeHelper = new ChoiceModeHelper<>(adapter, mChoiceMode);
    mChoiceModeHelper.setOnItemClickListener(this::onItemClick);
    mChoiceModeHelper.setRecyclerView(mRecyclerView);
    
    findViewById(R.id.action_clear_choices).setOnClickListener(v -> mChoiceMode.clearChoices());
    findViewById(R.id.action_get_checked_item).setOnClickListener(v -> showCheckedItem());
}
 
Example 11
Project: android-instant-apps-demo   File: CartActivity.java   Source Code and License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cart);
    viewModel = ViewModelProviders.of(this).get(CartViewModel.class);

    fab = (FloatingActionButton) findViewById(R.id.fab);
    toolbar = (Toolbar) findViewById(R.id.toolbar);

    setupToolbar();
    handleDeepLink();

    fab.setImageDrawable(VectorDrawableCompat.create(getResources(), R.drawable.ic_share_white_24dp, null));
    fab.setOnClickListener(view -> {
        String cartId = viewModel.getCartId().getValue();
        ShareCompat.IntentBuilder.from(this)
                .setText(String.format(Locale.US, "Check out my shopping cart now using Android Instant Apps! \n%s/cart/%s", ROOT_ENDPOINT, cartId))
                .setType("text/plain")
                .setChooserTitle(share_cart)
                .startChooser();
    });
}
 
Example 12
Project: EasyIPC   File: EasyIpcArchActivity.java   Source Code and License 6 votes vote down vote up
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_test);
	RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler);
	recyclerView.setAdapter(adapter = new Adapter());

	viewModel = ViewModelProviders
			.of(this)
			.get(IpcViewModel.class)
			.init(MainService.class, BIND_AUTO_CREATE);

	viewModel.dispatchEvent(new EarlyData("sent from the activity")); // get's queued

	viewModel
			.getLiveData(Data.class)
			.observe(ProcessLifecycleOwner.get(), onData);

	viewModel
			.getLiveData(Data.List.class)
			.observe(this, onDataList);

	viewModel
			.getLiveData(EarlyData.class)
			.observe(this, onEarlyData);

}
 
Example 13
Project: RoomDemo2017   File: ListFragment.java   Source Code and License 6 votes vote down vote up
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    //Set up and subscribe (observe) to the ViewModel
    listItemCollectionViewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(ListItemCollectionViewModel.class);

    listItemCollectionViewModel.getListItems().observe(this, new Observer<List<ListItem>>() {
        @Override
        public void onChanged(@Nullable List<ListItem> listItems) {
            if (ListFragment.this.listOfData == null) {
                setListData(listItems);
            }
        }
    });

}
 
Example 14
Project: RoomDemo2017   File: DetailFragment.java   Source Code and License 6 votes vote down vote up
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    //Set up and subscribe (observe) to the ViewModel
    listItemViewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(ListItemViewModel.class);

    listItemViewModel.getListItemById(itemId).observe(this, new Observer<ListItem>() {
        @Override
        public void onChanged(@Nullable ListItem listItem) {
            if (listItem != null) {
                dateAndTime.setText(listItem.getItemId());
                message.setText(listItem.getMessage());
                coloredBackground.setImageResource(listItem.getColorResource());
            }

        }
    });


}
 
Example 15
Project: android-architecture-components   File: UserFragment.java   Source Code and License 6 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    userViewModel = ViewModelProviders.of(this, viewModelFactory).get(UserViewModel.class);
    userViewModel.setLogin(getArguments().getString(LOGIN_KEY));
    userViewModel.getUser().observe(this, userResource -> {
        binding.get().setUser(userResource == null ? null : userResource.data);
        binding.get().setUserResource(userResource);
        // this is only necessary because espresso cannot read data binding callbacks.
        binding.get().executePendingBindings();
    });
    RepoListAdapter rvAdapter = new RepoListAdapter(dataBindingComponent, false,
            repo -> navigationController.navigateToRepo(repo.owner.login, repo.name));
    binding.get().repoList.setAdapter(rvAdapter);
    this.adapter = new AutoClearedValue<>(this, rvAdapter);
    initRepoList();
}
 
Example 16
Project: app-android   File: MainActivity.java   Source Code and License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);

    //UI elements setup
    setSupportActionBar(toolbar);

    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    navigationView.setNavigationItemSelectedListener(this);


    //Init shared usermodels
    ViewModelProviders.of(this).get(SharedUserViewModel.class);


    //Init nav, Load dashboard fragment
    NavigationController.init(this);
    NavigationController.getInstance().navigateToDashboard();
}
 
Example 17
Project: Android-CleanArchitecture-Java   File: WikiEntryActivity.java   Source Code and License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //WikiEntry feature component scope start here
    ((CleanArchApp)getApplication()).buildWikiEntryComponent();

    setContentView(R.layout.activity_main);

    title = (EditText) findViewById(R.id.entryTitle);
    TextView extract = (TextView) findViewById(R.id.entryDetails);
    Button submitButton = (Button) findViewById(R.id.submitButton);
    submitButton.setOnClickListener(submitButtonOnClickListener);

    progressBar = (ContentLoadingProgressBar) findViewById(R.id.progressBar);

    wikiEntryViewModel = ViewModelProviders.of(this).get(WikiEntryViewModel.class);
    wikiEntryViewModel.getWikiEntry().observe(this, wikiEntry -> {

        Log.d(TAG, "received update for wikiEntry");
        extract.setText(wikiEntry.getExtract());
        progressBar.hide();
    });
}
 
Example 18
Project: mvvm-template   File: ContributorsFragment.java   Source Code and License 6 votes vote down vote up
@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        adapter.setContributor(true);
        adapter.setFilter(false);
        recyclerView.addKeyLineDivider();
        RepoDetailViewModel repoDetailViewModel = ViewModelProviders.of(getActivity()).get(RepoDetailViewModel.class);
        repoDetailViewModel.getOnDataReady().observe(this, ready -> {
            if (ready != null && ready) {
                // noinspection ConstantConditions
                viewModel.initRepoDetail(repoDetailViewModel);
            }
        });
        setNoDataText("No Contributors");
        viewModel.getContributorsCount().observe(this, count -> {
            int n = count != null ? count : 0;
            Fragment fragment = getParentFragment();
            if (fragment != null && fragment instanceof TabBadgeListener) {
//                ((TabBadgeListener) fragment).setBadge(1, n);
            }
        });
    }
 
Example 19
Project: mapbox-navigation-android   File: NavigationView.java   Source Code and License 5 votes vote down vote up
private void initViewModels() {
  try {
    locationViewModel = ViewModelProviders.of((FragmentActivity) getContext()).get(LocationViewModel.class);
    routeViewModel = ViewModelProviders.of((FragmentActivity) getContext()).get(RouteViewModel.class);
    navigationViewModel = ViewModelProviders.of((FragmentActivity) getContext()).get(NavigationViewModel.class);
  } catch (ClassCastException exception) {
    throw new ClassCastException("Please ensure that the provided Context is a valid FragmentActivity");
  }
}
 
Example 20
Project: SampleAppArch   File: FeedActivityModule.java   Source Code and License 5 votes vote down vote up
/**
 * Created by Charles Ng on 26/9/2017.
 */


@Provides
FeedEntryListViewModel provideViewModel(FeedEntry feedEntry, FeedActivity feedActivity,
    FeedEntryListViewModelFactory factory) {
  FeedEntryListViewModel viewModel = ViewModelProviders.of(feedActivity, factory)
      .get(FeedEntryListViewModel.class);
  viewModel.getFeedEntry().set(feedEntry);
  return viewModel;
}
 
Example 21
Project: SampleAppArch   File: SimpleListActivityModule.java   Source Code and License 5 votes vote down vote up
@Provides
SimpleMasterDetailShareViewModel provideVm(SimpleListActivity simpleListActivity,
    SimpleMasterDetailShareViewModelFactory factory) {
  return ViewModelProviders
      .of(simpleListActivity, factory).get(SimpleMasterDetailShareViewModel.class);

}
 
Example 22
Project: ArchitectureComponents   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    viewModel = ViewModelProviders.of(this).get(FilmsViewModel.class);
    viewModel.init();
    lstFIlms = (ListView) findViewById(R.id.lstFilms);

    subscribeUi(viewModel);

    getLifecycle().addObserver(this);
}
 
Example 23
Project: DataBindingDemos   File: CounterActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    CounterViewModel viewModel = ViewModelProviders.of(this).get(CounterViewModel.class);

    ActivityCounterBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_counter);
    binding.setViewModel(viewModel);
}
 
Example 24
Project: PADC-MyanmarAttractions-AC   File: AttractionListActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_attraction_list);
    ButterKnife.bind(this, this);

    setActionBar(toolbar);

    ActionBar actionBar = getActionBar();
    if (actionBar != null) {
        actionBar.setTitle(getString(R.string.app_title_mm));
    }

    mAttractionAdapter = new AttractionAdapter(getApplicationContext(), this);
    rvAttractions.setAdapter(mAttractionAdapter);

    LinearLayoutManager verticalSingleColumnLM = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
    rvAttractions.setLayoutManager(verticalSingleColumnLM);

    mAttractionsModel = ViewModelProviders.of(this).get(AttractionsModel.class);
    mAttractionsModel.initDatabase(getApplicationContext());
    mAttractionsModel.getAttractions().observe(this, new Observer<List<AttractionVO>>() {
        @Override
        public void onChanged(@Nullable List<AttractionVO> attractionVOs) {
            mAttractionAdapter.setNewData(attractionVOs);
        }
    });
}
 
Example 25
Project: RxRedux   File: UserListActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void initialize() {
    eventObservable = Observable.empty();
    viewModel = ViewModelProviders.of(this,
            new ViewModelFactory(DataServiceFactory.getInstance())).get(UserListVM.class);
    if (viewState == null) {
        eventObservable = Single.<BaseEvent>just(new GetPaginatedUsersEvent(0))
                .doOnSuccess(event -> Log.d("GetPaginatedUsersEvent", FIRED)).toObservable();
    }
}
 
Example 26
Project: MVVMArms   File: WeatherActivity.java   Source Code and License 5 votes vote down vote up
@Override
public int initView(Bundle savedInstanceState) {
    //创建ViewModel
    mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(WeatherViewModel.class);
    if (savedInstanceState != null) {
        //Restore data
        mReplace = savedInstanceState.getInt(EventBusTags.ACTIVITY_FRAGMENT_REPLACE);
    }
    return R.layout.activity_weather;
}
 
Example 27
Project: Android-ArchComponents   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void callLocationListener() {
    ViewModelProviders.of(this)
            .get(MainActivityViewModel.class)
            .getLocation(this)
            .observe(this, location -> {
                // Update UI
            });
}
 
Example 28
Project: Android-Code-Demos   File: LoginActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ViewModelFactory factory = ViewModelFactory.getInstance(getApplication());
    final LoginViewModel loginViewModel =
            ViewModelProviders.of(this, factory).get(LoginViewModel.class);

    final ActivityLoginBinding binding =
            DataBindingUtil.setContentView(this, R.layout.activity_login);
    binding.setViewmodel(loginViewModel);

    loginViewModel.getOpenUserList().observe(this, new Observer<String>() {
        @Override
        public void onChanged(@Nullable String s) {
            Intent intent = new Intent(LoginActivity.this, UserListActivity.class);
            intent.putExtra("token", s);
            startActivity(intent);
            finish();
        }
    });

    loginViewModel.getSnackbarMessage().observe(this, new SnackbarMessage.SnackbarObserver() {
        @Override
        public void onNewMessage(String message) {
            SnackbarUtil.showSnackbar(binding.getRoot(), message);
        }
    });

    findViewById(R.id.submit).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            loginViewModel.login();
        }
    });
}
 
Example 29
Project: FitnessHabits   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    viewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);
    viewModel.init(FitnessHabitsApplication.application.getParamRepository());
}
 
Example 30
Project: permission-bitte   File: ArchitectureComponentsActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	findViewById(R.id.button).setOnClickListener(this);
	vm = ViewModelProviders.of(this).get(ArchitectureComponentsViewModel.class);
	vm.getState().observe(this, this);
	vm.shouldAskPermission(PermissionBitte.shouldAsk(this, vm));

}
 
Example 31
Project: DaggerAndroidMVVM   File: LobbyActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    AndroidInjection.inject(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.lobby_activity);

    ButterKnife.bind(this);

    viewModel = ViewModelProviders.of(this, viewModelFactory).get(LobbyViewModel.class);

    viewModel.response().observe(this, response -> processResponse(response));
}
 
Example 32
Project: Moneycim   File: AddAndEditSpendingFragment.java   Source Code and License 5 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    viewModel = ViewModelProviders.of(this).get(AddAndEditSpendingViewModel.class);
    subscribeSpendingGroups();
    if(spendingGroupList != null){
        fillSpinner(groupSpinner, spendingGroupList);
    }
}
 
Example 33
Project: LabDayApp   File: LoginFragment.java   Source Code and License 5 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    viewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(LoginViewModel.class);

    observeLogin();
}
 
Example 34
Project: GmArchMvvm   File: RtoFragment.java   Source Code and License 5 votes vote down vote up
@Override
public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(RtoViewModel.class);
    mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_rto, container, false);
    mBinding.setViewModel(mViewModel);//Set ViewModel
    return mBinding.getRoot();
}
 
Example 35
Project: android-persistence   File: BooksBorrowedByUserActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.db_activity);
    mBooksTextView = findViewById(R.id.books_tv);

    // Get a reference to the ViewModel for this screen.
    mViewModel = ViewModelProviders.of(this).get(BooksBorrowedByUserViewModel.class);

    // Update the UI whenever there's a change in the ViewModel's data.
    subscribeUiBooks();
}
 
Example 36
Project: android-persistence   File: TypeConvertersActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.db_activity);
    mBooksTextView = findViewById(R.id.books_tv);

    // Get a reference to the ViewModel for this screen.
    mViewModel = ViewModelProviders.of(this).get(TypeConvertersViewModel.class);

    // Update the UI whenever there's a change in the ViewModel's data.
    subscribeUiBooks();
}
 
Example 37
Project: Inshorts   File: ArticleListActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_article_list);

    ButterKnife.bind(this);

    mRootView = findViewById(R.id.root);

    //Getting the ApiService
    ApiService apiService = NetworkInstance.getInstance(this).getApiService();

    //Getting the Database
    AppDatabase database = Room.databaseBuilder(getApplicationContext(),
            AppDatabase.class, AppDatabase.DB_NAME).build();

    //Getting the ViewModel
    ListActivityViewModel.Factory factory = new ListActivityViewModel.Factory(getApplication(),
            new RepositoryImpl(apiService, database));
    mViewModel = ViewModelProviders.of(this, factory).get(ListActivityViewModel.class);

    rvArticleList.setLayoutManager(new LinearLayoutManager(this));

    NetworkInfo.getInstance(this).observe(this, connectedToInternet -> {
        if (!connectedToInternet) {
            //offline
            showMsg(getString(R.string.no_internet));
        } else {
            //online fetch the list if not fetched already
            mViewModel.fetchListIfNotFetched();
        }
    });
}
 
Example 38
Project: android-persistence   File: BooksBorrowedByUserActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.db_activity);
    mBooksTextView = findViewById(R.id.books_tv);

    // Get a reference to the ViewModel for this screen.
    mViewModel = ViewModelProviders.of(this).get(BooksBorrowedByUserViewModel.class);

    // Update the UI whenever there's a change in the ViewModel's data.
    subscribeUiBooks();
}
 
Example 39
Project: lead-management-android   File: ContactsFragment.java   Source Code and License 5 votes vote down vote up
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_contacts, container, false);
    setHasOptionsMenu(true);
    mUnbinder = ButterKnife.bind(this, view);

    mViewModel = ViewModelProviders.of(this).get(ContactsFragmentViewModel.class);
    mViewModel.getContacts().observe(this, contacts -> {
        mAdapter.replaceData(contacts);
    });

    final MainActivity activity = (MainActivity) getActivity();
    if (activity != null) {
        activity.initFab();
    }

    mAdapter = new ContactsAdapter(this);
    recyclerView.setAdapter(mAdapter);

    textView.setVisibility(View.GONE);

    swipeToRefresh.setOnRefreshListener(() -> {
        mAdapter.replaceData(mViewModel.getContacts().getValue());
        swipeToRefresh.setRefreshing(false);
    });
    return view;
}
 
Example 40
Project: recyclerview-android   File: ListDatasourceExampleActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(@Nullable final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_datasource_example);

    mViewModel = ViewModelProviders.of(this).get(ListDatasourceExampleViewModel.class);

    final Datasource<Person> datasource = mViewModel.getDatasource();
    final PersonsAdapter adapter = new PersonsAdapter(datasource);

    mRecyclerView = (RecyclerView) findViewById(android.R.id.list);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    mRecyclerView.setAdapter(adapter);

    // Add click support to RecyclerView. Adapter implements ItemClickHelper.Callback
    mItemClickHelper = new ItemClickHelper<>(adapter);
    mItemClickHelper.setOnItemClickListener(this::onItemClick);
    mItemClickHelper.setOnItemLongClickListener(this::onItemLongClick);
    mItemClickHelper.setRecyclerView(mRecyclerView);

    // Add enable view holder behavior. Adapter implements SimpleEnableBehavior.Callback
    mViewHolderTracker = new ViewHolderTracker();
    mViewHolderTracker.registerViewHolderObserver(new RecursiveEnableBehavior(adapter));
    mViewHolderTracker.setRecyclerView(mRecyclerView);

    findViewById(R.id.action_add_item).setOnClickListener(v -> mViewModel.addSingleItem());
    findViewById(R.id.action_add_multiple_items).setOnClickListener(v -> mViewModel.addMultipleItems());
}
 
Example 41
Project: trust-wallet-android   File: AddTokenActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    AndroidInjection.inject(this);

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_add_token);

    toolbar();

    addressLayout = findViewById(R.id.address_input_layout);
    address = findViewById(R.id.address);
    symbolLayout = findViewById(R.id.symbol_input_layout);
    symbol = findViewById(R.id.symbol);
    decimalsLayout = findViewById(R.id.decimal_input_layout);
    decimals = findViewById(R.id.decimals);
    systemView = findViewById(R.id.system_view);
    systemView.hide();

    findViewById(R.id.save).setOnClickListener(this);

    viewModel = ViewModelProviders.of(this, addTokenViewModelFactory)
            .get(AddTokenViewModel.class);
    viewModel.progress().observe(this, systemView::showProgress);
    viewModel.error().observe(this, this::onError);
    viewModel.result().observe(this, this::onSaved);
}
 
Example 42
Project: BestPracticeApp   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    UserProfileViewModel viewModel = ViewModelProviders.of(this).get(UserProfileViewModel.class);
    viewModel.getUser(123L).observe(this, new Observer<User>() {
        @Override
        public void onChanged(@Nullable User user) {
            Log.i("test", "获取了"+user.toString());
        }
    });
}
 
Example 43
Project: trust-wallet-android   File: WalletsActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
	AndroidInjection.inject(this);
	super.onCreate(savedInstanceState);

	setContentView(R.layout.activity_wallets);
	// Init toolbar
	toolbar();

	adapter = new WalletsAdapter(this::onSetWalletDefault, this::onDeleteWallet, this::onExportWallet);
	SwipeRefreshLayout refreshLayout = findViewById(R.id.refresh_layout);
	systemView = findViewById(R.id.system_view);
	backupWarning = findViewById(R.id.backup_warning);

	RecyclerView list = findViewById(R.id.list);

	list.setLayoutManager(new LinearLayoutManager(this));
	list.setAdapter(adapter);

	systemView.attachRecyclerView(list);
	systemView.attachSwipeRefreshLayout(refreshLayout);
	backupWarning.setOnPositiveClickListener(this::onNowBackup);
	backupWarning.setOnNegativeClickListener(this::onLaterBackup);

	viewModel = ViewModelProviders.of(this, walletsViewModelFactory)
			.get(WalletsViewModel.class);

	viewModel.error().observe(this, this::onError);
	viewModel.progress().observe(this, systemView::showProgress);
	viewModel.wallets().observe(this, this::onFetchWallet);
	viewModel.defaultWallet().observe(this, this::onChangeDefaultWallet);
       viewModel.createdWallet().observe(this, this::onCreatedWallet);
       viewModel.createWalletError().observe(this, this::onCreateWalletError);
       viewModel.exportedStore().observe(this, this::openShareDialog);
       viewModel.exportWalletError().observe(this, this::onExportWalletError);
       viewModel.deleteWalletError().observe(this, this::onDeleteWalletError);

	refreshLayout.setOnRefreshListener(viewModel::fetchWallets);
}
 
Example 44
Project: UpdogFarmer   File: AutoDiscoverDialog.java   Source Code and License 5 votes vote down vote up
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    viewModel = ViewModelProviders.of(this).get(AutoDiscoverViewModel.class);
    viewModel.init(SteamWebHandler.getInstance());
    viewModel.getQueueItem().observe(this, new Observer<AutoDiscoverViewModel.QueueItem>() {
        @Override
        public void onChanged(@Nullable AutoDiscoverViewModel.QueueItem queueItem) {
            handleQueueItem(queueItem);
        }
    });
}
 
Example 45
Project: PlayAndroid   File: GankMeiZhiFragment.java   Source Code and License 5 votes vote down vote up
@Override
public void initData() {
    Log.d("LazyLoadFragment", "initData: ");
    Bundle arguments = getArguments();
    String title = arguments.getString(C.gank.gank_title);

    GankViewModel gankViewModel = ViewModelProviders.of(this).get(GankViewModel.class);
    gankViewModel.getGankLiveData(title).observe(this, new Observer<PagedList<Gank>>() {
        @Override
        public void onChanged(@Nullable PagedList<Gank> ganks) {
            mGankMeiZhiAdapter.setList(ganks);
        }
    });

}
 
Example 46
Project: android-lifecycles   File: Fragment_step5.java   Source Code and License 5 votes vote down vote up
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.fragment_step5, container, false);
    mSeekBar = root.findViewById(R.id.seekBar);

    mSeekBarViewModel = ViewModelProviders.of(getActivity()).get(SeekBarViewModel.class);

    subscribeSeekBar();

    return root;
}
 
Example 47
Project: chaosflix   File: EventDetailsFragment.java   Source Code and License 5 votes vote down vote up
@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		postponeEnterTransition();
		Transition transition = TransitionInflater.from(getContext())
				.inflateTransition(android.R.transition.move);
//		transition.setDuration(getResources().getInteger(R.integer.anim_duration));
		setSharedElementEnterTransition(transition);

		if (getArguments() != null) {
			mEvent = getArguments().getParcelable(EVENT_PARAM);
		}
		viewModel = ViewModelProviders.of(this).get(ChaosflixViewModel.class);
	}
 
Example 48
Project: blockvote   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);

	// init google services
	GoogleApiAvailability.getInstance().makeGooglePlayServicesAvailable(this);
	FirebaseMessaging.getInstance().subscribeToTopic("v1");
	if (BuildConfig.DEBUG) {
		FirebaseMessaging.getInstance().subscribeToTopic("debug");
	}

	// bind views
	statsView = findViewById(R.id.stats);
	historyView = findViewById(R.id.card_history);
	historyView.setOnRetryListener(this::onRetryHistory);

	// get viewmodel
	viewModel = ViewModelProviders.of(this).get(MainViewModel.class);
	// TODO get rid of this line?
	viewModel.init(this);
	viewModel.observeData(this, this::onHistoryUpdated);
	viewModel.loadHistory();

	// bind ticker
	Ticker.with(this).bind(this::onTick);

	// load stats
	getSupportLoaderManager().initLoader(0, null, this);
}
 
Example 49
Project: elevator-room   File: ElevatorActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_elevator);
    appComponent = MyApplication.getAppComponent(this);
    appComponent.inject(this);
    unbinder = ButterKnife.bind(this);
    gameStateManager.multiWindowDividerSize.setRightView(this, rootView);
    gameStateManager.gameState.observe(this, this::onApplyState);
    gameStateManager.doorsOpen.observe(this, this::updateDoors);

    viewModel = ViewModelProviders.of(this).get(ElevatorViewModel.class);
    view = new ElevatorView(appComponent, this, viewModel.currentFloorLive);
    viewModel.writePressureToDatabase(this);
    viewModel.gameLoopTimer.observe(this, view::updateWidgets);
    viewModel.activePeople().observe(this, view::updateForPeople);
    btnStart.setEnabled(false); // disable until pressure reading starts
    viewModel.barometer.observe(this, aFloat -> btnStart.setEnabled(true));
    viewModel.barometer.getGroundPressure().observe(this, aFloat -> {
        if (gameStateManager.gameState.getValue() == CALIBRATION) {
            gameStateManager.gameState.setValue(PLAYING);
            viewModel.generateFirstPerson();
        }
    });
    viewModel.getCurrentPressurePercentage().observe(this, integer -> {
        pressureIndicator.setProgress(integer, true);
    });
}
 
Example 50
Project: RoomDemo2017   File: CreateFragment.java   Source Code and License 5 votes vote down vote up
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    //Set up and subscribe (observe) to the ViewModel
    newListItemViewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(NewListItemViewModel.class);

}
 
Example 51
Project: LabDayApp   File: MainFragment.java   Source Code and License 5 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    viewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(MainViewModel.class);

    //quick architecture test
    binding.setHelloWorld(viewModel.getProjectRepositoryHelloWorld());

    observeAppData();

    viewModel.loadAppData(getContext());
}
 
Example 52
Project: android-architecture-components   File: SearchFragment.java   Source Code and License 5 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    searchViewModel = ViewModelProviders.of(this, viewModelFactory).get(SearchViewModel.class);
    initRecyclerView();
    RepoListAdapter rvAdapter = new RepoListAdapter(dataBindingComponent, true,
            repo -> navigationController.navigateToRepo(repo.owner.login, repo.name));
    binding.get().repoList.setAdapter(rvAdapter);
    adapter = new AutoClearedValue<>(this, rvAdapter);

    initSearchInputListener();

    binding.get().setCallback(() -> searchViewModel.refresh());
}
 
Example 53
Project: android-architecture-components   File: ProductFragment.java   Source Code and License 5 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    ProductViewModel.Factory factory = new ProductViewModel.Factory(
            getActivity().getApplication(), getArguments().getInt(KEY_PRODUCT_ID));

    final ProductViewModel model = ViewModelProviders.of(this, factory)
            .get(ProductViewModel.class);

    mBinding.setProductViewModel(model);

    subscribeToModel(model);
}
 
Example 54
Project: android-architecture-components   File: ProductListFragment.java   Source Code and License 5 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    final ProductListViewModel viewModel =
            ViewModelProviders.of(this).get(ProductListViewModel.class);

    subscribeUi(viewModel);
}
 
Example 55
Project: android-architecture-components   File: UserActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user);

    mUserName = findViewById(R.id.user_name);
    mUserNameInput = findViewById(R.id.user_name_input);
    mUpdateButton = findViewById(R.id.update_user);

    mViewModelFactory = Injection.provideViewModelFactory(this);
    mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(UserViewModel.class);
    mUpdateButton.setOnClickListener(v -> updateUserName());
}
 
Example 56
Project: mvvm-template   File: BaseViewModelFragment.java   Source Code and License 5 votes vote down vote up
@Override
@CallSuper
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    viewModel = ViewModelProviders.of(this, viewModelFactory).get(getViewModelClass());
    viewModel.onCreate(getFragmentArguments(), navigatorHelper);

    viewModel.getStateLiveData().observe(this, this::handleState);
}
 
Example 57
Project: mvvm-template   File: OverviewFragment.java   Source Code and License 5 votes vote down vote up
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    profileViewModel = ViewModelProviders.of(getActivity()).get(ProfileViewModel.class);
    profileViewModel.getUser().observe(this, this::populateUserDetail);

    if (profileViewModel.isMyOrOrganization()) {
        binding.follow.followBtn.setVisibility(GONE);
    } else {
        binding.follow.followBtn.setVisibility(VISIBLE);
    }
    binding.follow.setVm(viewModel);

    viewModel.initUser(profileViewModel.getUser().getData().getLogin(), profileViewModel);
    viewModel.getFollowState().observe(this, this::invalidateFollowBtn);
    viewModel.getOrgansState().observe(this, this::invalidateOrgans);
    viewModel.getPinnedState().observe(this, this::invalidatePinned);
    viewModel.getContributionsData().observe(this, this::invalidateContributions);

    // organizations
    binding.organizationList.setAdapter(organizationAdapter);
    ((GridManager) binding.organizationList.getLayoutManager()).setIconSize(getResources().getDimensionPixelSize(R.dimen.header_icon_zie) + getResources()
            .getDimensionPixelSize(R.dimen.spacing_xs_large));
    viewModel.getOrganizations().observe(this, users -> organizationAdapter.setData(users));
    organizationAdapter.setItemClickListener((v, item) -> {
        navigatorHelper.navigateUserProfile(item);
    });

    // pinned
    binding.pinnedList.setAdapter(pinnedAdapter);
    binding.pinnedList.addDivider();
    viewModel.getPinnedNodes().observe(this, nodes -> pinnedAdapter.setData(nodes));
    pinnedAdapter.setItemClickListener( (v, node) -> {
        SchemeParser.launchUri(getContext(), node.url().toString());
    });
}
 
Example 58
Project: trust-wallet-android   File: SendActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    AndroidInjection.inject(this);

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_send);
    toolbar();

    viewModel = ViewModelProviders.of(this, sendViewModelFactory)
            .get(SendViewModel.class);

    toInputLayout = findViewById(R.id.to_input_layout);
    toAddressText = findViewById(R.id.send_to_address);
    amountInputLayout = findViewById(R.id.amount_input_layout);
    amountText = findViewById(R.id.send_amount);

    contractAddress = getIntent().getStringExtra(C.EXTRA_CONTRACT_ADDRESS);
    decimals = getIntent().getIntExtra(C.EXTRA_DECIMALS, C.ETHER_DECIMALS);
    symbol = getIntent().getStringExtra(C.EXTRA_SYMBOL);
    symbol = symbol == null ? C.ETH_SYMBOL : symbol;
    sendingTokens = getIntent().getBooleanExtra(C.EXTRA_SENDING_TOKENS, false);

    setTitle(getString(R.string.title_send) + " " + symbol);
    amountInputLayout.setHint(getString(R.string.hint_amount) + " " + symbol);

    // Populate to address if it has been passed forward
    String toAddress = getIntent().getStringExtra(C.EXTRA_ADDRESS);
    if (toAddress != null) {
        toAddressText.setText(toAddress);
    }

    ImageButton scanBarcodeButton = findViewById(R.id.scan_barcode_button);
    scanBarcodeButton.setOnClickListener(view -> {
        Intent intent = new Intent(getApplicationContext(), BarcodeCaptureActivity.class);
        startActivityForResult(intent, BARCODE_READER_REQUEST_CODE);
    });
}
 
Example 59
Project: mvvm-template   File: RepoFilesFragment.java   Source Code and License 5 votes vote down vote up
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    repoDetailViewModel = ViewModelProviders.of(getActivity()).get(RepoDetailViewModel.class);
    RepoFilePathsViewModel parentViewModel = ViewModelProviders.of(getParentFragment()).get(RepoFilePathsViewModel.class);
    viewModel.initParentViewModel(parentViewModel);
    viewModel.initFragmentManager(getChildFragmentManager());

    parentViewModel.getOnRefresh().observe(this, o -> {
        if (o != null) {
            viewModel.refresh();
        }
    });
    adapter.setOnMenuClick(this::onMenuClicked);
}
 
Example 60
Project: android-architecture-boilerplate   File: BrowseActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    AndroidInjection.inject(this);
    setContentView(R.layout.activity_browse);
    mUserViewModel = ViewModelProviders.of(this, mViewModelFactory)
            .get(UserViewModel.class);

    mRecyclerView = findViewById(R.id.recycler_browse);
    mProgressBar = findViewById(R.id.progress);
    mEmptyView = findViewById(R.id.view_empty);
    mErrorView = findViewById(R.id.view_error);

    setupBrowseRecycler();
}