Skip to main content

MVP Structure - Base Classes - PART I


public class AppController extends MultiDexApplication {
  private static AppController INSTANCE;
  private String baseDomain = "http://xxx.xxx.x.xxx:xxxx/";
  private String domainPathSegments = "xxxxx";
  private Typeface typeface;
  private ApiManager apiManager;
  /**
   * Get the Application Instance
   *
   * @return
   */
  public static AppController getInstance() {
      if (INSTANCE == null) {
          INSTANCE = new AppController();
      }
      return INSTANCE;
  }
  @Override
  public void onCreate() {
      super.onCreate();
      INSTANCE = this;
      FileLogger.getInstance().attachApplication(this);
  }
  public Typeface getTypeface() {
      return typeface;
  }
  public void setTypeface(Typeface typeface) {
      this.typeface = typeface;
  }
  public String getDomainPathSegments() {
      return domainPathSegments;
  }
  public String getBaseDomain() {
      return baseDomain;
  }
  /**
   * Get the API Manager for calling API
   *
   * @return apiManager instance
   */
  public ApiManager getApiManager() {
      if (apiManager == null) {
          apiManager = Utils.getRetrofit(baseDomain, this).create(ApiManager.class);
      }
      return apiManager;
  }
}
**********
public class BaseFragment extends Fragment {
  @Override
  public void onDestroyView() {
      super.onDestroyView();
  }
}
**********
public interface BasePresenter {
  /**
   * Called from View to start the first scenario
   */
  void start();
  /**
   * File Logger to save the log in file
   *
   * @param log
   */
  void fileLogger(String log);
  /**
   * Copy the saved log to file
   * Should call on onDestroy method
   */
  void flushLogger();
}
**********
public interface BaseView <T> {
  /**
   * Set the presenter for base view connection
   *
   * @param presenter
   */
  void setPresenter(T presenter);
}
**********

public class SessionManger {

  private static final String SHARED_PREFERENCE_FILE = "KEY";
  public static String LANGUAGE_LOCALE = "lang_locale";
  public static String LANGUAGE_COUNTRY = "lang_country";
  public static String LANGUAGE_FONT = "lang_font";
  private SharedPreferences mPreferences;
  /**
   * Initiate Session manager
   *
   * @param context current context
   */
  public SessionManger(Context context) {
      mPreferences = context.getSharedPreferences(SHARED_PREFERENCE_FILE, Context.MODE_PRIVATE);
  }
  /**
   * add/ update string value
   *
   * @param key   identification
   * @param value value for the key
   */
  public void setStringKey(String key, String value) {
      SharedPreferences.Editor editor = mPreferences.edit();
      editor.putString(key, value);
      editor.apply();
  }
  /**
   * Bulk Input string
   *
   * @param bulkUpdate bulk key- value pair
   */
  public void setStringKey(ArrayMap<String, String> bulkUpdate) {
      SharedPreferences.Editor editor = mPreferences.edit();
      Set<String> keys = bulkUpdate.keySet();
      Iterator<String> iterator = keys.iterator();
      while (iterator.hasNext()) {
          String key = iterator.next();
          editor.putString(key, bulkUpdate.get(key));
      }
      editor.apply();
  }
  /**
   * add/ update Boolean value
   *
   * @param key   identification
   * @param value value for the key
   */
  public void setBooleanKey(String key, boolean value) {
      SharedPreferences.Editor editor = mPreferences.edit();
      editor.putBoolean(key, value);
      editor.apply();
  }
  /**
   * add/ update Int value
   *
   * @param key   identification
   * @param value value for the key
   */
  public void setIntKey(String key, int value) {
      SharedPreferences.Editor editor = mPreferences.edit();
      editor.putInt(key, value);
      editor.apply();
  }
  /**
   * Store the Array of strings
   *
   * @param key         Name of the key to store
   * @param stringArray arrays to store
   */
  public void setStringArray(String key, ArrayList<String> stringArray) {
      if (stringArray == null || stringArray.size() == 0) {
          return;
      }
      SharedPreferences.Editor editor = mPreferences.edit();
      Set<String> strings = new HashSet<>(stringArray);
      editor.putStringSet(key, strings);
      editor.apply();
  }
/*      public void removeStringArray(String key, ArrayList<String> stringArray) {
      if (stringArray == null || stringArray.size() == 0) {
          return;
      }
      SharedPreferences.Editor editor = mPreferences.edit();
      Set<String> strings = new HashSet<>(stringArray);
      editor.putStringSet(key, strings);
      editor.remove(key);
  }
  */
  /**
   * get the array strings to corresponding key
   *
   * @param key key which you need it
   * @return @{@link ArrayList}
   */
  public ArrayList<String> getStringArray(String key) {
      return new ArrayList<String>(mPreferences.getStringSet(key, new HashSet<String>()));
  }
  /**
   * Get the session value (Int)
   *
   * @param key Required value
   * @return if key has value or 0 by default
   */
  public int getIntKey(String key) {
      return mPreferences.getInt(key, 0);
  }
  /**
   * Get the session value (Boolean)
   *
   * @param key Required value
   * @return if key has value or false by default
   */
  public boolean getBooleanKey(String key) {
      return mPreferences.getBoolean(key, false);
  }
  /**
   * Get the session value (String)
   *
   * @param key Required value
   * @return if key has value or empty by default
   */
  public String getStringKey(String key) {
      return mPreferences.getString(key, "");
  }
  /**
   * Clear the session <br/>
   * Expect LANGUAGE_COUNTRY,LANGUAGE_FONT,LANGUAGE_LOCALE
   */
  public void clearSession() {
      String fontName = getStringKey(LANGUAGE_FONT);
      String country = getStringKey(LANGUAGE_COUNTRY);
      String locale = getStringKey(LANGUAGE_LOCALE);
      mPreferences.edit().clear().apply();
      ArrayMap<String, String> bulkUpdate = new ArrayMap<>();
      bulkUpdate.put(LANGUAGE_FONT, fontName);
      bulkUpdate.put(LANGUAGE_COUNTRY, country);
      bulkUpdate.put(LANGUAGE_LOCALE, locale);
      setStringKey(bulkUpdate);
  }
}
***********
public class Utils {
public static Retrofit getRetrofit(String baseDomain, Context context) {
  HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
  // set your desired log level
  logging.setLevel(BuildConfig.isShowLog ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
  OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new NoConnectivityInterceptor(context)).addInterceptor(logging).connectTimeout(0, TimeUnit.MINUTES).readTimeout(0, TimeUnit.MINUTES).build();
  Gson gson = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
  return new Retrofit.Builder()
          .client(client)
          .addConverterFactory(GsonConverterFactory.create(gson))
          .baseUrl(baseDomain)
          .build();
}
/**
* To check network connection available or not
*
* @return true if available else no, not available
*/
public static boolean isNetworkAvailable(Context context) {
  ConnectivityManager cm =
          (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
  return activeNetwork != null &&
          activeNetwork.isConnectedOrConnecting();
}
}
**********

public interface CallBack<T> {
    /**     * Success     *     * @param objects - Model object     */    void success(T objects);

    void responseFailure(T objects);

    void connectionFailure(Throwable errorThrowable);
}
**********

public interface ApiManager {
    String segments = "/{path}/index/";
    
   /* @POST(segments + "?xxxx.json")
    Call<apiMethodResponse> calledAPIMethod(@Path("path") String path, 
  @Body apiMethodRequest model, @Query("lang") String lang);
    */
}
**********
Inside of app build.gradle


dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'    })
    compile 'com.android.support:appcompat-v7:26.+'    compile 'com.android.support.constraint:constraint-layout:1.0.2'    compile 'com.squareup.retrofit2:retrofit:2.3.0'    compile 'com.squareup.retrofit2:converter-gson:2.3.0'    compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'    compile 'com.android.support:multidex:1.0.1'    testCompile 'junit:junit:4.12'}


Comments

Popular posts from this blog

SearchView using CursorAdapter

Here  MYFRAGMENT is nothing but name of  a Fragment @Override public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {     inflater.inflate(R.menu.popup, menu);     final SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);     final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();     searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));     searchView.setSubmitButtonEnabled(false);     searchView.setIconifiedByDefault(true);     //       searchView.setOnCloseListener(this);     SearchView. OnQueryTextListener textChangeListener = new SearchView. OnQueryTextListener () {         @Override         public boolean onQueryTextSubmit(String query) {             cartAdapt...

Fragment

To enable/disable menu items in Different fragments in same Activity: @Override public void onCreate(@Nullable Bundle savedInstanceState)  {     super.onCreate(savedInstanceState);     setHasOptionsMenu(true);  } @Override public void onPrepareOptionsMenu(Menu menu) {     //Disable the SearchView which is enabled in Product Chart     menu.findItem(R.id.action_search).setVisible(false);   // true to enable } ====================================================

To make a ListView to be scrolled inside of ScrollView

To make a ListView to be scrolled inside of ScrollView: lv . setOnTouchListener ( new ListView . OnTouchListener () { @Override public boolean onTouch ( View v , MotionEvent event ) { int action = event . getAction (); switch ( action ) { case MotionEvent . ACTION_DOWN : // Disallow ScrollView to intercept touch events. v . getParent (). requestDisallowInterceptTouchEvent ( true ); break ; case MotionEvent . ACTION_UP : // Allow ScrollView to intercept touch events. v . getParent (). requestDisallowInterceptTouchEvent ( false ); break ; } // Handle ListView touch events. v . onTouchEvent ( event ); return true ; } }); Refer: http://stackoverflow.com/questions/6210895/listview-inside-scrollview-is-not-scrolling-on-android