Scopes Modules Components and Subcomponent in Dagger 2

Scopes

ApplicationScope.java

import javax.inject.Scope;
@Scope
public @interface ApplicationScope {
}

ActivityScope.java

import javax.inject.Scope;
@Scope
public @interface ActivityScope {
}

Modules

MyAppModule.java

@Module
public class MyAppModule {
    private final Context mAppContext;

    public MyAppModule(Application application) {
        mAppContext = application;
    }

    @Provides
    @ApplicationScope
    Context providesMyAppContext() {
        return mAppContext;
    }
}

PersistentModule.java

@Module
public class PersistentModule {
    @Provides
    @ApplicationScope
    SharedPreferences providesSharedPreferences(Context myAppContext) {
        return PreferenceManager.getDefaultSharedPreferences(myAppContext);
    }
}

ActivityModule.java

@Module
public class ActivityModule {
    private Activity activity;

    public ActivityModule(Activity activity) {
        this.activity = activity;
    }

    @Provides
    Activity activity() {
        return activity;
    }
}

Components

MyAppComponent.java

@ApplicationScope
@Component(modules = {MyAppModule.class, PersistentModule.class})
public interface MyAppComponent {
    ActivityComponent addChild(ActivityModule activityModule);
    void inject(MyApp myApp);
}

ActivityComponent.java

@ActivityScope
@Subcomponent(modules = {ActivityModule.class})
public interface ActivityComponent {
    void inject(MainActivity mainActivity);
}

Usages

MyApp.java

public class MyApp extends Application {

    private MyAppComponent mMyAppComponent;

    @Override
    public void onCreate() {
        super.onCreate();

        mMyAppComponent = DaggerMyAppComponent.builder()
                .myAppModule(new MyAppModule(this))
                .persistentModule(new PersistentModule())
                .webServiceModule(new WebServiceModule(Constants.BASE_URL))
                .build();
        mMyAppComponent.inject(this);
    }

    public MyAppComponent getMyAppComponent() {
        return mMyAppComponent;
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Inject SharedPreferences sharedPreferences;

    private static final String TEXT_KEY = "text_key";

    private EditText edText;
    private TextView tvDisplay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ((MyApp) getApplication()).getMyAppComponent()
                .addChild(new ActivityModule(this))
                .inject(this);

        edText = (EditText) findViewById(R.id.ed_text);
        tvDisplay = (TextView) findViewById(R.id.tv_display);
    }

    public void save(View v) {
        String text = edText.getText().toString();
        SharedPreferences.Editor ed = sharedPreferences.edit();
        ed.putString(TEXT_KEY, text);
        boolean isSaved  = ed.commit();
        Snackbar.make(v, (isSaved) ? "Text Saved!" : "Failed to save the text!", Snackbar.LENGTH_SHORT).setAction("Action", null).show();
    }

    public void retrieve(View v) {
        String savedText = sharedPreferences.getString(TEXT_KEY, "");
        tvDisplay.setText(savedText);
    }

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="50dp"
    android:paddingRight="50dp"
    tools:context="com.example.dagger2example.views.MainActivity">

    <EditText
        android:id="@+id/ed_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter some text"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAllCaps="false"
            android:text="Save"
            android:onClick="save"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAllCaps="false"
            android:text="Retrieve"
            android:onClick="retrieve"/>
    </LinearLayout>

    <TextView
        android:id="@+id/tv_display"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:gravity="center"/>
</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.dagger2example">

    <application
        android:name=".MyApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".views.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Search within Codexpedia

Custom Search

Search the entire web

Custom Search