Giter Site home page Giter Site logo

janishar / android-mvvm-architecture Goto Github PK

View Code? Open in Web Editor NEW
2.9K 122.0 940.0 835 KB

This repository contains a detailed sample app that implements MVVM architecture using Dagger2, Room, RxJava2, FastAndroidNetworking and PlaceholderView

Home Page: https://janisharali.com

License: Apache License 2.0

Java 100.00%
mvvm mvvm-architecture android android-architecture dagger2 dagger2-mvvm rxjava2 rxjava room database

android-mvvm-architecture's Introduction

Deprecated


This Project is [Deprecated] goto latest project: Modern Android Development - WhereIsMyMotivation


Deprecated

Android MVVM Architecture: Sample App

This repository contains a detailed sample app that implements MVVM architecture using Dagger2, Room, RxJava, FastAndroidNetworking, PlaceHolderView and AndroidDebugDatabase




About The Author

You can connect with me here:

The app has following packages:

  1. data: It contains all the data accessing and manipulating components.
  2. di: Dependency providing classes using Dagger2.
  3. ui: View classes along with their corresponding ViewModel.
  4. utils: Utility classes.

Classes have been designed in such a way that it could be inherited and maximize the code reuse.

Library reference resources:

  1. Dagger2: https://github.com/janishar/android-dagger2-example
  2. PlaceHolderView: https://github.com/janishar/PlaceHolderView
  3. Calligraphy: https://github.com/chrisjenx/Calligraphy
  4. Room: https://developer.android.com/topic/libraries/architecture/room.html

Concept reference resources:

  1. Introduction to Dagger 2: Part 1
  2. Introduction to Dagger 2: Part 2
  3. Android Dagger2: Critical things to know before you implement
  4. Android Tinder Swipe View Example
  5. RxJava Anatomy: What is RxJava, how RxJava is designed, and how RxJava works.

Looking for Kotlin MVP Architecture - Check here

Looking for MVP Architecture - Check here

License

   Copyright (C) 2023 JANISHAR ALI ANWAR

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

Contributing to Android MVVM Architecture

Just make pull request. You are in!

android-mvvm-architecture's People

Contributors

adisiji avatar al4al avatar amitshekhariitbhu avatar janishar avatar jyotid avatar jyotidubey avatar kessir avatar kukhyun avatar legalimpurity avatar rotbolt avatar salmanseifian avatar subuday avatar tranngoclam avatar vignesh150493 avatar vy8 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

android-mvvm-architecture's Issues

Service calling issue

Getting this error when i call server using this structure:

<!doctype html><title>HTTP Status 415 – Unsupported Media Type</title><style type="text/css">H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}</style>

HTTP Status 415 – Unsupported Media Type


Type Status Report

Message Unsupported Media Type

Description The origin server is refusing to service the request because the payload is in a format not supported by this method on the target resource.


Apache Tomcat/7.0.90

415 Unsupported Media Type okhttp error

blogFragment ,RecyclerView item Binding

hello.
in BlogFragment you use RecyclerView that bind to blogObservableArrayList . this is okey but there is another LiveData object that use when blogs receive. why you not bind list to livedata object? there is a useless loop : blogListLiveData receive data and notify to fragment and fragment notify viewmodel to fill blogObservableArrayList then list getting update!

performDataBinding() take too much time

Hi @amitshekhariitbhu...
First, i would like to say thanks for your awesome lib

i have problem in my project. when i start new activity performDataBinding() take to much time (sometimes more than 5-6 sec)
and new activity start so slow.
what is the cause of this problem?
& is there any way to fix this?

Thanks 👍

Queries

Hey Amit,

Had few queries.

  1. I have custom font setup in base activity. But in recycler view unable to extend those is it okay to pass context to Recycler view?. Secondly is it okay to use recycler view onAddItemTouchListener from the activity rather clicking from the adapter?

  2. Also, how do you direct to activity from a service in this architecture. A local Broadcast receiver is a viable option but I guess its a rudimentary approach. Using event bus is an option (green robot, otto) but does that breaks the architecture anyhow?

Handle Token Expired

Can you please explain how to handle token when it is expired?
I see a function to handle when token is expired in BaseActivity.
Thanks

blogViewModel and openSourceViewModel VS ViewModelProviderFactory

hi i checked both previous and new code and i have a question. as i see, you move all viewmodels to ViewModelProviderFactory and remove them from modules. Although you mention new OpenSourceViewModel(dataManager,schedulerProvider); and new BlogViewModel(dataManager,schedulerProvider); in ViewModelProviderFactory, you also provide them in OpenSourceFragmentModule and BlogFragmentModule. why did you do this ?
thanks

cannot find symbol class UI

i have problem until i use androidx .when i set data variable to layout xml i faced error: cannot find symbol class UI
error: package UI.MainPage does not exist

Room Persistence Library

Hello,

I have seen your MVVM example Good example,You have implemented Room Persistence Library code using dagger2 but i can't find any use of this code so can you please help me where you have used Room Persistence Library for insert,update,delete data into SQLite database.

Thank you

Unable to bind User model to View with Android Binding

Here, when the mUserLiveData is fetched, UI is not updated

public void fetchProfile(@NonNull int userId  ) {
        setIsLoading(true);
        getCompositeDisposable().add(getDataManager()
                .getUserApiCall( userId )
                .subscribeOn(getSchedulerProvider().io())
                .observeOn(getSchedulerProvider().ui())
                .subscribe(response -> {
                    if (response != null) {
                        mUserLiveData.setValue( response );
                    }
                    setIsLoading(false);
                }, throwable -> {
                    setIsLoading(false);
                    getNavigator().handleError(throwable);
                }));
    }

    public String getFirstName() {
        return mUserLiveData.getValue().getFirstName();
    }

    public String getLastName() {
        return mUserLiveData.getValue().getLastName();
    }

UI

                <android.support.design.widget.TextInputLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentEnd="true"
                    android:layout_alignTop="@+id/profile_thumbnail_circleimageview"
                    android:layout_toEndOf="@+id/profile_thumbnail_circleimageview">

                    <android.support.design.widget.TextInputEditText
                        android:id="@+id/profile_firstname_edittext"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/translate_firstname"
                        android:inputType="textCapSentences|textPersonName"
                        android:text="@={viewModel.firstName}"/>
                </android.support.design.widget.TextInputLayout>

                <!-- Name Label -->
                <android.support.design.widget.TextInputLayout
                    android:id="@+id/textInputLayout2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignBottom="@+id/profile_thumbnail_circleimageview"
                    android:layout_toEndOf="@+id/profile_thumbnail_circleimageview">

                    <android.support.design.widget.TextInputEditText
                        android:id="@+id/profile_lastname_edittext"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/translate_lastname"
                        android:inputType="textCapSentences|textPersonName"
                        android:text="@={viewModel.lastName}"/>
                </android.support.design.widget.TextInputLayout>

Data Binding Error

I clone the repository and this error is coming

  • What went wrong:
    Execution failed for task ':app:compileDebugJavaWithJavac'.

android.databinding.tool.util.LoggedErrorException: Found data binding errors.
****/ data binding error ****msg:Cannot find the setter for attribute 'app:adapter' with parameter type androidx.lifecycle.LiveData<java.util.List<com.mindorks.framework.mvvm.ui.feed.opensource.OpenSourceItemViewModel>> on androidx.recyclerview.widget.RecyclerView.
file:D:\development\WorkspaceProjects\android-mvvm-architecture2\app\src\main\res\layout\fragment_open_source.xml
loc:43:31 - 43:63
****\ data binding error ****
****/ data binding error ****msg:cannot find method get() in class ObservableBoolean
file:D:\development\WorkspaceProjects\android-mvvm-architecture2\app\src\main\res\layout\activity_login.xml
loc:170:34 - 170:79
****\ data binding error ****

DaggerAppComponent Not able to build

@amitshekhariitbhu

I am having Android app with MVVM architecture.

I need to have use RoomDatabase and i came to your repo and taken reference of it.

Setup everything as of your demo for Room Database and tried to build my Project.

But suddenly DaggerAppComponent no more able to build now. I crossed check everything same as of your demo and required setup is done.

Can you help me please.

error: cannot find symbol import com.iam.app.di.component.DaggerAppComponent;

Queries

Hey Amit,

I have few queries

  1. I need to call certain Api from a class which does not extend ViewModel class. How I can achieve this so that it access my AppDataManager and api is called effectively.

  2. I am using retrofit for networking calls. Could you suggest effect centralize decentralization of error response?

Can not set timeout for request

Hi @amitshekhariitbhu ,
First of all, i would like to thank your awesome lib and project.
But currently, i can't set time out for api requests.

There is my code.

`
//Constant file
public static final int FAN_CONNECT_TIME_OUT = 30; //30s
public static final int FAN_CONNECT_READ_OUT = 30; //30s
public static final int FAN_CONNECT_WRITE_OUT = 30; //30s

//App file

OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.connectTimeout(FAN_CONNECT_TIME_OUT, TimeUnit.SECONDS)
.readTimeout(FAN_CONNECT_READ_OUT, TimeUnit.SECONDS)
.writeTimeout(FAN_CONNECT_WRITE_OUT, TimeUnit.SECONDS)
.build();

AndroidNetworking.initialize(getApplicationContext(), okHttpClient);

`

Seem like no wrong, but it still wait ~120s for each request if server is down.

Could help me resolve this issues?

Inject Context into fragment

Hi Amit,
I follow your tutorials and it has helped me a lot to understand dagger MVP, MVVM architecture. Am following this example in one of my projects but for MVP architecture. Now, I need a small clarification am using a view pager with fragments and my fragment module needs activity context. As, per my understanding we can use Qualifier activity context in constructor and use it in Activity builder. Is this approach appropriate. Looking forward to your feedback.

How to make parallel api calls in a class using Rxjava

Hi @amitshekhariitbhu ,
I want to call 4 API's at a time. I'm having problem while calling multiple API's at a screen in parallel using Rxjava, could u please provide a syntax or a small demo for help. This is how I 'm making a single network call using Rx:

getCompositeDisposable().add(getDataManager().getUserInfo()
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.ui())
                .subscribe(userInfoResponse,throwable);
 public Single<ApiResponse> getUserInfo() {
            return Rx2AndroidNetworking.get(strUrl)
                    .addHeaders(mApiHeader)
                    .build()
                    .getObjectSingle(ApiResponse.class);
    }

why use viewmodel why not baseObservable

when I update the display value, the value does not change but when I enter the display variable into the extension class the Baseobservable value can change

ViewModel having different injection approach

I have observed that in some classes like SplashActivity and LoginActivity ViewModel is directly been injected without using ViewModelProviderFactory.class.
But in MainActivity class ViewModel is not directly injected, it is instantiated using ViewModelProviderFactory.class I do not get the purpose these two approach.

I believe this is done due to the fact that Login and Splash screen do not support saving state of the view when screen is rotated, but MainActivity does. Is it true?

Unable to get ViewModelProvider.Factory for each ViewModel

Hi,

I am following same app structure for my app as:

ActivityBuilder.java:
`@Module
public abstract class ActivityBuilder {

@ContributesAndroidInjector(modules = SplashActivityModule.class)
abstract SplashActivity bindSplashActivity();

@ContributesAndroidInjector(modules = {NavigationActivityModule.class,
                                       CatalogueFragmentProvider.class })
abstract NavigationActivity bindNavigationActivity();

}`

NavigationActivityModule.Java (NavigationActivity which draws Navigation View with NavigationViewModel):
`@Module
public class NavigationActivityModule {

@Provides
NavigationViewModel provideNavigationViewModel(Application application) {
    return new NavigationViewModel(application);
}

@provides
ViewModelProvider.Factory mainViewModelProvider(NavigationViewModel navigationViewModel) {
return new TraderViewModelFactory<>(navigationViewModel);
}
}`

CatalogueFragmentProvider.Java (CatalogueFragment which shows as the first fragment inside NavigationView container):
@module
public abstract class CatalogueFragmentProvider {
@ContributesAndroidInjector(modules = CataloguesFragmentModule.class)
abstract CataloguesFragment provideCataloguesFragment();
}

Lastly, CataloguesFragmentModule.Java (contain catalogue view such as RecyclerView inside CatalogueFragment):
@module
public class CataloguesFragmentModule {

@Provides
CatalogueFragmentViewModel provideAboutViewModel(CataloguesRepository cataloguesRepository, Application application) {
    return new CatalogueFragmentViewModel(cataloguesRepository, application);
}

@Provides
ViewModelProvider.Factory catalogueViewModelProvider(CatalogueFragmentViewModel catalogueFragmentViewModel) {
    return new TraderViewModelFactory<>(catalogueFragmentViewModel);
}

}

The problem is I am getting the same instance of NavigationViewModel inside the CatalogueViewModel. This throws error by ViewModelFactory since modelClass.isAssignableFrom returns false.

Please help. I stuck into this from last three days and couldn't find any solution by googling too.

Thanks.

How to achieve MVVM without Room

Hi

First off all thanks for the nice example for mvvm. Actually my project we don't want to use local database(Room). Can you help me how I can achieve the same using this project as reference.

Thanks in Advance.

RecyclerView Adapter form

I have reading the mvvm architecure, and I see the example but I wonder if in a RecyclerView instead of show elements from DB or Repository, I wanted to show say a Spinner and a EdditText and then recover the data from this UI Elements and save in the DB, how I can do this, since in the example you show that items to show in the RecyclerView and its viewmodel its not Injected and have no access to DataManager.

Proper way to inject data into viewModels

Hello,

I am using this example as template for my own application.
It helped me a great deal trying to understand Dagger2, but ran into a bit of an issue.
I wrote a new module for a client that i need to get data from a local ftp server and added it to the module to AppComponent

Now from wat i understand the ActivityBuilder (also added to AppComponent basicly functions the same as doing void inject(MainActivity activity); in our AppComponent.
Which will allow for data injection into all of the activity's listed in there.

But the client is used for data communication with a small ftp server, all the data get handled in my viewModels so i feel like it makes more sense to directly inject it into there, but i am not sure how or wat even the proper way of doing it would be.

So my question is, based on this application, wat is the proper way to inject something into a viewModel or do i have to pass it like your example shows with the dataManager?
or as last option should i inject it into the activity instead, and use getNavigator to access a get method that fetches the client from the activity ?

DaggerAppComponent

class not found

import com.mindorks.framework.mvvm.di.component.DaggerAppComponent;

unit test

hi, thanks for this project.
how to i write unit test for each code in project?
If possible, help me to this case.

Crash when orientation changes

Caused by kotlin.UninitializedPropertyAccessException: lateinit property androidInjector has not been initialized.
Solution : Move android injector before super.onCreate(savedInstanceState);

The problem when you have 2 layouts for one Fragment/Activity

Hi. There is one problem with associating layouts to e.g. fragment.
Let's say you have MainActivity and two layouts for it (activity_main_normal.xml, activity_main_small.xml). So if u want to choose which layout to inflate from
public int getLayoutId() { if(someCase){ return R.layout.activity_main_small; } else { return R.layout.activity_main_small; }
then you will get:
java.lang.ClassCastException: ActivityMainSmallBindingImpl cannot be cast to ActivityMainBinding

So, how would you resolve that kind of problem?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.