Giter Site home page Giter Site logo

benoitletondor / android-studio-mvp-template Goto Github PK

View Code? Open in Web Editor NEW
627.0 34.0 121.0 922 KB

Android MVP template for Android Studio

License: Apache License 2.0

FreeMarker 98.54% Shell 1.46%
android mvp-boilerplate mvp mvp-android boilerplate android-studio-template android-studio

android-studio-mvp-template's Introduction

Android Studio MVP Template

This is an Android Studio template for MVP.

It is inspired by u2020-mvp-android-studio-template and follows Antonio Leiva's MVP implementation guide for Android. It also implements presenter surviving orientation changes following Antonio Gutierrez's article.

If you are looking for the first version, without presenter survival, please download the first release. Note that version 2 (current one) is not compatible with version 1.

Here's the hierarchy it follows:

com.company.app
    +-- injection
    |   - ActivityScope
    |   - AppComponent
    |   - AppModule
    |   - FragmentScope
    |   - MainViewComponent
    |   - MainViewModule
    +-- interactor
    |   +-- impl
    |       - MainViewInteractorImpl
    |   - BaseInteractor
    |   - MainViewInteractor
    +-- presenter
    |   +-- impl
    |       - BasePresenterImpl
    |       - MainViewPresenterImpl
    |   - BasePresenter
    |   - MainViewPresenter
    +-- view
    |   +-- impl
    |       - BaseActivity
    |       - BaseFragment
    |       - MainActivity
    |   - MainView
    | - YourApp

Prerequisites

You must use Dagger 2 for dependency injection and AppCompat for annotations and base classes.

Installation

For Mac:

  • If you have a standard Android Studio installation:

Just run the install script at the root of this repository:

./install.sh
  • Manual installation:

Just copy all 3 directories MVPFragment, MVPActivity and MVPBoilerplate to $ANDROID_STUDIO_FOLDER$/Contents/plugins/android/lib/templates/activities/

For Windows:

Just copy all 3 directories MVPFragment, MVPActivity and MVPBoilerplate to $ANDROID_STUDIO_FOLDER$\plugins\android\lib\templates\activities\

How to use

1. Generate base boilerplate

First of all, create the base hierarchy and classes using MVP Boilerplate from the root package folder. This needs to be done only once per project:

Create MVP Boilerplate

It will generate an App class that you should use as your Application, an ActivityScope, FragmentScope, AppModule and AppComponent for injection, a BaseActivity, BaseFragment, BasePresenter, BasePresenterImpl and BaseInteractor. It also generates the common classes for presenter persistancy (PresenterFactory and PresenterLoader).

Be sure to use the generated App as your Application into your manifest!

2. Create your first activity

Then you can create a new MVP Activity. It will create:

  • An Activity
  • A layout for your Activity
  • A Component and a Module for Dagger 2 injection
  • A View interface for your Activity
  • A Presenter interface and default implementation class
  • An Interactor interface and default implementation class for your model

It's important that you create it from the root package, otherwise it will re-create the whole MVP hierarchy under your subpackage which is not what you want.

Presenter lifecycle (Important!)

Your presenter will be kept across activity re-creation on orientation changes using a Loader. For more details about how its done, read Antonio Gutierrez's article.

It means that:

  • You want to be sure to update your view state on each onStart call of your presenter since your view may have been destroyed and re-created since last stop.
  • You should use the viewCreated parameter of the onStart method to know if the view has been created or re-created (e.g. following a screen rotation). This boolean will be true only if the view has just been created so if it's true you should update your view according to the presenter's state.
  • You should not stop your background operations on the onStop method (things like HTTP calls or database connection) since your view may still be available (on the next onStart call).
  • You must stop all background operation on the onPresenterDestroyed method. When this method is reached, it means that your view is completely destroyed and will not be re-created later.

You should also be very careful about:

  • Since the presenter is loaded asynchronously by a Loader, it means that it's not available before the view actually started. So the mPresenter variable can (and will probably) be null when your activity or fragment starts (you should not call your presenter directly into onCreate, onStart or onResume methods).
  • To avoid leaks, your presenter will not keep a reference on your view when this view is stopped. It means that your view is guaranteed to be available from the onStart method to the onStop. It also means it will be null outside of this scope.

To ensure those last 2 points, mView and mPresenter are annotated with @Nullable, to enforce the check by the linter. It's a good idea to surround all calls with !=null.

Contributors

License

Copyright 2019 Benoit LETONDOR

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.

android-studio-mvp-template's People

Contributors

benoitletondor avatar bstrandjev avatar martynhaigh avatar namhvcntt 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

android-studio-mvp-template's Issues

Fragment generate can not build

I add MVP Fragment like with MVP Activity but it cannot build "DaggerCustomViewComponent" in CustomFragment.java
It is better if you add a sample clean project for both Activity and Fragment, example only say "Hello World" text.

Use along with RxAndroid

Hi
I want call APIs in my code but i confused where i should use RxAndroid and where i should unsubscribe subscriptions.

Right way to access presenter

Hi.
Thank for great work.
In generated Activity code you write "Your presenter is available using the mPresenter variable" but i confused what is mPresenterFactory for?
I should mPresenterFactory.create() or mPresenter?

mPresenter is null in onStart

Hi
Thank you for your awesome contribution!!

We have a couple of activities where we get crash reports of the mPresenter being null in the onStart.

We cannot reproduce the crash but we get it in the logs

Any ideas why ?

@Override public void onStart() { super.onStart(); if (mFirstStart) { mPresenter.setStartIndex(mStartIndex); mPresenter.performSearch(); mFirstStart = false; } }

Fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.abc.def/com.abc.view.impl.PhoneSearchResultsActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'void com.abc.presenter.ISearchResultsPresenter.setStartIndex(int)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4077) at android.app.ActivityThread.-wrap15(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1350) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by java.lang.NullPointerException: Attempt to invoke interface method 'void com.abc.presenter.ISearchResultsPresenter.setStartIndex(int)' on a null object reference at com.abc.view.impl.SearchResultsFragment.onStart(SearchResultsFragment.java:85) at android.support.v4.app.Fragment.performStart(Fragment.java:2218) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1340) at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595) at android.support.v4.app.FragmentManagerImpl.dispatchStart(FragmentManager.java:2907) at android.support.v4.app.FragmentController.dispatchStart(FragmentController.java:212) at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:613) at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178) at com.abc.view.impl.BaseActivity.onStart(BaseActivity.java:50) at com.abc.view.impl.PhoneSearchResultsActivity.onStart(PhoneSearchResultsActivity.java:81) at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237) at android.app.Activity.performStart(Activity.java:6268) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4077) at android.app.ActivityThread.-wrap15(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1350) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

DialogFragment

hi
how can i make a DialogFragment extend BaseFragment?

How to pass an extra from activity to presenter?

(Sorry if this is not the best place to ask questions)

I'm working on an application that has two screens:

  • a list of pokemons (using a recyclerview)
  • pokemon details

In the first screen, I configure the view in MainActivity.onCreate(), and then, inside MainPresenterImpl, I do:

@Override
public void onStart(boolean firstStart) {
    super.onStart(firstStart);

    // Your code here. Your view is available using mView and will not be null until next onStop()

    if (firstStart) {
        getPokemonNames(); // this method belongs to MainPresenter
    }
}

This works ok.

But, for the second screen, in order to call the server I need the id of the pokemon, so when I select a pokemon from the recyclerview, I start DetailsActivity and pass an EXTRA_POKEMON_ID in the intent.

Now, here is the problem: I do not have access to that id inside the presenter, so I'm not able to follow the same approach as before:

@Override
public void onStart(boolean firstStart) {
    super.onStart(firstStart);

    // Your code here. Your view is available using mView and will not be null until next onStop()

    if (firstStart) {
        // getPokemonDetails(id); // I do not have the id here
    } else {
        if (mInteractor.networkRequestInProgress()) {
            mView.showLoadingIndicator();
        }
        mView.showPokemonDetails(mPokemon);
    }
}

I tried to call the presenter inside DetailsActivity.onStart(), but doing that, the presenter is called each time the "configuration change" (like rotate the phone) and that is not ideal.

What's the proper way to handle a case like this?

Need an Example Usage

Hello,
Could you make an example to implement this amazing library? :)
Thanks! :)

Is @Inject really needed in *InteractorImpl & *PresenterImpl constructors?

I've seen that @Inject is used in both Interactor & Presenter implementations:

@Inject
public MainPresenterImpl(@NonNull MainInteractor interactor) {
    mInteractor = interactor;
}

@Inject
public MainInteractorImpl(PokemonAPI pokemonAPI) {
    mPokemonAPI = pokemonAPI;
}

are those @Inject really necessary? why? both instances are already provided by *Module (in this case, MainModule)

@Provides
@ActivityScope
public MainInteractor provideInteractor(PokemonAPI pokemonAPI) {
    return new MainInteractorImpl(pokemonAPI);
}

@Provides
@ActivityScope
public PresenterFactory<MainPresenter> providePresenterFactory(@NonNull final MainInteractor interactor) {
    return new PresenterFactory<MainPresenter>() {
        @NonNull
        @Override
        public MainPresenter create() {
            return new MainPresenterImpl(interactor);
        }
    };
}

Crash on Support library 27.1.0

In new Support library 27.1.0 was made some changed with loaders, this led to some issues with this approach. For example, presenter is null in Activity in onStart() method.

MVP template not working in android 3.0

Following the instructions, you have on the homepage. When I copied the MVP activities to the android studio directory the Android Studio Application got damaged. However, when I followed the same instruction on android 2.3 everything went well.

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.