Course Content
Expense Manager App – Login
0/1
Expense Manager App – Product
0/1
Expense Manager Android App
    About Lesson

    Here’s a detailed guide to implementing Preferences, ApiRequestHelper, and ApiService classes in an Expense Manager Android application. These classes are typically used in Android projects to manage session data, handle API requests, and provide a structured way to interact with network services.

     

    1. Session Management in Android (api/Preferences)

    The Preferences class is used to manage user session data, such as login status, user details, and other persistent data throughout the application lifecycle. A common approach is to use SharedPreferences to store session data.

    Session Class Implementation

    Here’s an example implementation of the Preferences class in Java:


    public class Preferences {

    private Context context;
    SharedPreferences pref;
    SharedPreferences.Editor editor;
    private final int PRIVATE_MODE = 0;
    private static final String PREF_NAME = "EXPENSE_MANAGER_APP";
    private static final String EXPENSE_MANAGER_LOGIN = "expense_manager_login";
    public Preferences(Context context) {
    this.context = context;
    pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
    }

    public void setString(String key, String val) {
    SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    SharedPreferences.Editor e = prefs.edit();
    e.putString(key, val);
    e.apply();
    }

    public String getString(String key, String def) {
    SharedPreferences prefs = getSharedPreferences();
    return prefs.getString(key, def);
    }

    protected SharedPreferences getSharedPreferences() {
    return context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    }

    }

     


    2. api/ApiRequestHelper

    The ApiRequestHelper class serves as a utility for preparing and executing API requests. It often manages common configurations, headers, and parameters required for HTTP requests.

    ApiRequestHelper Implementation

    Here’s an example implementation using Retrofit for network requests:

    public class ApiRequestHelper {

    public static String WEB_URL = "#";
    public static String BASE_URL = "https://infovistar.in/demo/expensemanager/api/v1/";
    public static Retrofit retrofit = null;
    public static Context context;


    public static Retrofit getUnsafeApiClient(Context ctx) {
    context = ctx;
    return new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(getUnsafeOkHttpClient().build())
    .build();
    }

    public static OkHttpClient.Builder getUnsafeOkHttpClient() {
    try {
    // Create a trust manager that does not validate certificate chains
    @SuppressLint("CustomX509TrustManager")
    final TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {
    @SuppressLint("TrustAllX509TrustManager")
    @Override
    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
    }

    @SuppressLint("TrustAllX509TrustManager")
    @Override
    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
    }

    @Override
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
    return new java.security.cert.X509Certificate[]{};
    }
    }
    };

    // Install the all-trusting trust manager
    final SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    // Create an ssl socket factory with our all-trusting manager
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
    builder.hostnameVerifier((hostname, session) -> true);
    builder.readTimeout(240, TimeUnit.SECONDS);
    builder.connectTimeout(240, TimeUnit.SECONDS);
    return builder;
    } catch (Exception e) {
    throw new RuntimeException(e);
    }
    }

    }

     


    3. api/ApiService Interface

    ApiService is an interface where you define all your API endpoints using Retrofit annotations. This keeps your API requests organized and easy to manage.

    ApiService Implementation

    Here’s an example of the ApiService interface:

    public interface ApiService {

    @FormUrlEncoded
    @POST("login")
    Call<LoginModel> getLogin(@FieldMap HashMap<String, Object> hashMap);

    }

     


    4. ExpenseManagerApp

    The ExpenseManagerApp class acts as the main entry point of your application, initializing necessary components like dependency injection frameworks, setting up global configurations, and managing application-wide resources.

    The ExpenseManagerApp class extends the Android Application class, which serves as the base class for maintaining the global application state. By extendingApplication  you can centralize and manage configurations, initialize critical components, and set up libraries that need to be initialized once when the app starts.

    public class ExpenseManagerApp extends Application {

    private static ExpenseManagerApp instance;
    private Preferences preferences;
    private ApiService apiService;

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

    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
    init();
    instance = this;

    }

    public void init() {
    preferences = new Preferences(this);
    apiService = ApiRequestHelper.getUnsafeApiClient(this).create(ApiService.class);
    }


    public Preferences getPreferences() {
    return preferences;
    }

    public ApiService getApiService() {
    return apiService;
    }
    }

     


    5. Usage of ExpenseManagerApp in AndroidManifest.xml

    To ensure that ExpenseManagerApp is used as the application class, you need to declare it in your AndroidManifest.xml:


    <application
    android:name=".ExpenseManagerApp"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    </application>

     

    This approach ensures that your Android application is robust, scalable, and well-structured for future enhancements. Let me know if you need further details or adjustments!