Test WS
[pullquote align="normal"]
[/pullquote]
https://files.fm/u/g3cqu9u7
https://drive.google.com/open?id=0B7RA37ZRQQXnWjhpS2I4Z1ZuT0U
https://drive.google.com/open?id=0B7RA37ZRQQXnOHphQ0NlYktBa2chttps://github.com/cstudioo/mvp-android
Step 1 : app build:
buildscript { repositories { maven { url 'https://maven.fabric.io/public' } } dependencies { classpath 'io.fabric.tools:gradle:1.+' } } apply plugin: 'com.android.application'apply plugin: 'io.fabric'apply plugin: 'com.google.gms.google-services' repositories { maven { url 'https://maven.fabric.io/public' } } android { compileSdkVersion 23 buildToolsVersion "23.0.1" defaultConfig { applicationId "com.app.scheurer4life" minSdkVersion 17 targetSdkVersion 23 versionCode 1 versionName "1.0" } packagingOptions { exclude 'META-INF/LICENSE.txt' } buildTypes { release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile 'com.android.support:appcompat-v7:23.0.1' compile 'com.android.support:cardview-v7:23.0.1' compile 'com.android.support:design:23.0.1' compile 'com.android.support:recyclerview-v7:23.0.1' compile 'com.squareup.okhttp3:okhttp:3.2.0' compile 'com.squareup.okhttp3:logging-interceptor:3.2.0' compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.4' compile 'com.google.android.gms:play-services-gcm:9.0.0' compile 'com.google.android.gms:play-services-analytics:9.0.0' compile 'com.jakewharton:butterknife:7.0.1' compile 'com.github.PhilJay:MPAndroidChart:v3.0.0-beta1' compile 'com.intuit.sdp:sdp-android:1.0.3' compile 'com.google.firebase:firebase-messaging:9.0.0' compile('com.crashlytics.sdk.android:crashlytics:2.6.5@aar') { transitive = true; } }-------Step 2----package com.app.scheurer4life.webservice; import android.content.Context; import android.text.TextUtils; import com.app.scheurer4life.R; import com.app.scheurer4life.util.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; /** * Web Service utility class to call web urls. And returns response. */public class WSUtil { private Context mContext; public String callServiceHttpPost(final Context mContext, final String url, final RequestBody requestBody) { this.mContext = mContext; Utils.writeLog(mContext, String.format("Request String : %s", requestBody.toString())); String responseString; try { final HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); final OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(logging) .connectTimeout(WsConstants.CONNECTION_TIMEOUT, TimeUnit.SECONDS) .readTimeout(WsConstants.CONNECTION_TIMEOUT, TimeUnit.SECONDS) .build(); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); final Response response = okHttpClient.newCall(request).execute(); responseString = response.body().string(); Utils.writeLog(mContext, "Response String : " + responseString); if (TextUtils.isEmpty(responseString) || !isJSONValid(responseString)) { responseString = getNetWorkError(); } } catch (IOException e) { e.printStackTrace(); responseString = getNetWorkError(); } return responseString; } public String callServiceHttpPost(final Context mContext, final String url, final RequestBody requestBody, String token) { this.mContext = mContext; Utils.writeLog(mContext, String.format("Request String : %s", requestBody.toString())); String responseString; try { final HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); final OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(logging) .connectTimeout(WsConstants.CONNECTION_TIMEOUT, TimeUnit.SECONDS) .readTimeout(WsConstants.CONNECTION_TIMEOUT, TimeUnit.SECONDS) .build(); Request request = new Request.Builder() .header("access_token", token) .url(url) .post(requestBody) .build(); final Response response = okHttpClient.newCall(request).execute(); responseString = response.body().string(); Utils.writeLog(mContext, "Response String : " + responseString); if (TextUtils.isEmpty(responseString) || !isJSONValid(responseString)) { responseString = getNetWorkError(); } } catch (IOException e) { e.printStackTrace(); responseString = getNetWorkError(); } return responseString; } public String callServiceHttpGet(final Context mContext, final String url) { this.mContext = mContext; String responseString; try { final HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); final OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(logging) .connectTimeout(WsConstants.CONNECTION_TIMEOUT, TimeUnit.SECONDS) .readTimeout(WsConstants.CONNECTION_TIMEOUT, TimeUnit.SECONDS) .build(); Request request = new Request.Builder() .url(url) .get() .build(); final Response response = okHttpClient.newCall(request).execute(); responseString = response.body().string(); Utils.writeLog(mContext, "Response String : " + responseString); if (TextUtils.isEmpty(responseString) || !isJSONValid(responseString)) { responseString = getNetWorkError(); } } catch (IOException e) { e.printStackTrace(); responseString = getNetWorkError(); } return responseString; } public String callServiceHttpGet(final Context mContext, final String url, String token) { this.mContext = mContext; Utils.writeLog(mContext, String.format("Request String : %s", url.toString())); String responseString; try { final HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); final OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(logging) .connectTimeout(WsConstants.CONNECTION_TIMEOUT, TimeUnit.SECONDS) .readTimeout(WsConstants.CONNECTION_TIMEOUT, TimeUnit.SECONDS) .build(); WsConstants wsConstants = new WsConstants(); Request request = new Request.Builder() .header("access_token", token) .url(url) .get() .build(); final Response response = okHttpClient.newCall(request).execute(); responseString = response.body().string(); Utils.writeLog(mContext, "Response String : " + responseString); if (TextUtils.isEmpty(responseString) || !isJSONValid(responseString)) { responseString = getNetWorkError(); } } catch (IOException e) { e.printStackTrace(); responseString = getNetWorkError(); } return responseString; } private String getNetWorkError() { final JSONObject jsonObject = new JSONObject(); try { final WsConstants wsConstants = new WsConstants(); jsonObject.put(wsConstants.PARAMS_STATUS, false); jsonObject.put(wsConstants.PARAMS_MESSAGE, mContext.getString(R.string.alert_network_error)); } catch (JSONException e) { e.printStackTrace(); } return jsonObject.toString(); } private boolean isJSONValid(String test) { try { new JSONObject(test); } catch (JSONException ex) { // edited, to include @Arthur's comment // e.g. in case JSONArray is valid as well... try { new JSONArray(test); } catch (JSONException ex1) { return false; } } return true; } }
---------------Step 3----------------------
package com.app.scheurer4life.webservice; import android.content.Context; import com.app.scheurer4life.model.LoginModel; import com.app.scheurer4life.model.UserInfoModel; import com.app.scheurer4life.util.Preference; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; /** * Created by scheurer4life on 20/09/16. * This class is makiing api call for user list webservice */public class WSGetUserList { private Context context; private String message; private boolean success; private int success_code; public WSGetUserList(final Context context) { this.context = context; } public boolean isSuccess() { return success; } public String getMessage() { return message; } public int getSuccess_code() { return success_code; } /** * Calls the api call for the getfruitveggie request to the application. * * @return {@link ArrayList<UserInfoModel>} that contain list of fruit and veggie that will be used in application */ public ArrayList<UserInfoModel> executeService(Context context) { final String url; url = WsConstants.BASE_URL + WsConstants.METHOD_USER_LIST; final String response = new WSUtil().callServiceHttpGet(context, url, Preference.getInstance().mSharedPreferences.getString(WsConstants.PARAMS_ACCESS_TOKEN, "")); return parseResponse(response); } /** * Parse the json response from {@link String} to {@link LoginModel}. * * @param response {@link String} response that is recived from the api request. * @return {@link LoginModel} that contain session variables for employer that will be used in application */ private ArrayList<UserInfoModel> parseResponse(final String response) { final ArrayList<UserInfoModel> userList = new ArrayList<>(10); if (response != null && response.trim().length() > 0) { try { final JSONObject jsonObject = new JSONObject(response); final WsConstants wsConstants = new WsConstants(); if (jsonObject.length() > 0) { success = jsonObject.optBoolean(wsConstants.PARAMS_STATUS); message = jsonObject.optString(wsConstants.PARAMS_MESSAGE); success_code = jsonObject.optInt(wsConstants.PARAMS_CODE); if (success) { final JSONArray jsonArrayData = jsonObject.optJSONArray(wsConstants.PARAMS_DATA); for (int i = 0; i < jsonArrayData.length(); i++) { final JSONObject jsonObjectData = jsonArrayData.optJSONObject(i); final UserInfoModel mUserInfoModel = new UserInfoModel(); mUserInfoModel.setId(jsonObjectData.optString("id")); mUserInfoModel.setEmail(jsonObjectData.optString("email")); mUserInfoModel.setFirstName(jsonObjectData.optString("first_name")); mUserInfoModel.setLastName(jsonObjectData.optString("last_name")); mUserInfoModel.setZipCode(jsonObjectData.optString("zip_code")); mUserInfoModel.setDob(jsonObjectData.optString("dob")); mUserInfoModel.setName(jsonObjectData.optString("name")); userList.add(mUserInfoModel); } return userList; } } } catch (Exception e) { e.printStackTrace(); } } return null; } }
------------Step 3 repeat for login --------------
package com.app.scheurer4life.webservice; import android.content.Context; import com.app.scheurer4life.model.LoginModel; import com.app.scheurer4life.util.Preference; import org.json.JSONObject; import okhttp3.FormBody; import okhttp3.RequestBody; /** * Created by scheurer4life on 20/09/16. * This class is makiing api call for user Login webservice */public class WSLogin { private Context context; private String message; private boolean success; private int success_code; public WSLogin(final Context context) { this.context = context; } public boolean isSuccess() { return success; } public String getMessage() { return message; } public int getSuccess_code() { return success_code; } /** * Calls the api call for the login request to the application. * * @param email {@link String} value for email address for the employer * @param password {@link String} value for email address for the employer * @return {@link LoginModel} that contain session variables for employer that will be used in application */ public LoginModel executeService(Context context, final String email, final String password) { final String url; url = WsConstants.BASE_URL + WsConstants.METHOD_USER_LOGIN; final String response = new WSUtil().callServiceHttpPost(context, url, generateLoginRequest(email, password)); return parseResponse(response); } /** * Parse the json response from {@link String} to {@link LoginModel}. * * @param response {@link String} response that is recived from the api request. * @return {@link LoginModel} that contain session variables for employer that will be used in application */ private LoginModel parseResponse(final String response) { if (response != null && response.trim().length() > 0) { try { final JSONObject jsonObject = new JSONObject(response); final WsConstants wsConstants = new WsConstants(); if (jsonObject.length() > 0) { success = jsonObject.optBoolean(wsConstants.PARAMS_STATUS); message = jsonObject.optString(wsConstants.PARAMS_MESSAGE); success_code = jsonObject.optInt(wsConstants.PARAMS_CODE); if (success) { final JSONObject jsonData = jsonObject.optJSONObject(wsConstants.PARAMS_DATA); final LoginModel loginModel = new LoginModel(); loginModel.setEmail(jsonData.optString("email")); loginModel.setAccess_token(jsonData.optString("access_token")); return loginModel; } } } catch (Exception e) { e.printStackTrace(); } } return null; } /** * Generates RequestBody for making api call for okhttp * * @param email {@link String} value for email address for the employer * @param password {@link String} value for email address for the employer * @return {@link RequestBody} that will store all the parameters to be passed to the server for execultion. */ private RequestBody generateLoginRequest(final String email, final String password) { final WsConstants wsConstants = new WsConstants(); final Preference preference = Preference.getInstance(); final FormBody.Builder formEncodingBuilder = new FormBody.Builder(); formEncodingBuilder.add(wsConstants.PARAMS_DEVICE_TOKEN, preference.mSharedPreferences.getString(preference.KEY_DEVICE_TOKEN, "")); formEncodingBuilder.add(wsConstants.PARAMS_EMAIL, email); formEncodingBuilder.add(wsConstants.PARAMS_PASSWORD, password); formEncodingBuilder.add(wsConstants.PARAMS_DEVICE_PLATFORM, wsConstants.DEVICE_PLATFORM); return formEncodingBuilder.build(); } }----------------login xml--------------<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <EditText android:id="@+id/activity_login_et_email" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="30dp" android:layout_marginRight="30dp" android:hint="Email"/> <EditText android:id="@+id/activity_login_et_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="30dp" android:layout_marginRight="30dp" android:layout_marginTop="10dp" android:inputType="textPassword" android:hint="Password"/> <Button android:id="@+id/activity_login_btn_login" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="Login"/> </LinearLayout>------------------recycle xml------------<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/fragment_sleeparticle_llContainer" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/bg_color" android:orientation="vertical"> <android.support.v7.widget.RecyclerView android:id="@+id/fragment_sleeparticle_rvProductList" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="@dimen/_5sdp" android:layout_weight="1" android:background="@color/bg_color"> </android.support.v7.widget.RecyclerView> <LinearLayout android:id="@+id/fragment_sleeparticle_llProgress" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:orientation="vertical" android:visibility="visible"> <ProgressBar android:id="@+id/progressBar1" style="?android:attr/progressBarStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginBottom="@dimen/_50sdp"/> </LinearLayout> <RelativeLayout android:id="@+id/fragment_rlEmpty" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white" android:visibility="gone"> <TextView android:id="@+id/tvEmptyMessage" android:layout_width="wrap_content" android:layout_height="wrap_content" style="@style/TextStyle.empty_title" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/no_sleeparticle_found" android:textAppearance="?android:attr/textAppearanceMedium" /> </RelativeLayout> </LinearLayout>----------------row file xml-----------<?xml version="1.0" encoding="utf-8"?><android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/row_sleeparticle_cvContainer" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="@dimen/_7sdp" android:background="@color/white" app:cardCornerRadius="@dimen/_3sdp" app:cardElevation="@dimen/_3sdp"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/ripple_custom" android:orientation="horizontal"> <FrameLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true"> <ImageView android:id="@+id/row_sleeparticle_ivProductImg" android:layout_width="@dimen/_110sdp" android:layout_height="@dimen/_120sdp" android:scaleType="fitXY" android:src="@drawable/ic_placeholder"/> </FrameLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginStart="@dimen/_3sdp" android:gravity="center_vertical" android:orientation="vertical"> <com.app.centuarymattresses.customecomponent.CustomTextView android:id="@+id/row_sleeparticle_tvTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" style="@style/TextStyle.row_mattresesscare.title" android:layout_alignParentStart="true" android:layout_alignParentTop="true" app:font_name="GothamHTF-Medium.otf"/> <com.app.centuarymattresses.customecomponent.CustomTextView android:id="@+id/row_sleeparticle_tvDescription" android:layout_width="wrap_content" android:layout_height="wrap_content" style="@style/TextStyle.row_mattresesscare.description" app:font_name="GothamHTF-Book.otf"/> <TextView android:layout_width="match_parent" android:layout_height="0.5dp" android:layout_marginBottom="@dimen/_6sdp" android:layout_marginStart="@dimen/_6sdp" android:layout_marginTop="@dimen/_6sdp" android:background="@color/collection_color"/> <com.app.centuarymattresses.customecomponent.CustomTextView android:id="@+id/row_sleeparticle_tvDate" android:layout_width="wrap_content" android:layout_height="wrap_content" style="@style/TextStyle.row_mattresesscare.date" app:font_name="GothamHTF-Medium.otf"/> </LinearLayout> </LinearLayout> </android.support.v7.widget.CardView> ---------Recycle fragment ----------package com.app.centuarymattresses.fragment; import android.animation.LayoutTransition; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.os.SystemClock; import android.support.v4.view.MenuItemCompat; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.text.TextUtils; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.app.centuarymattresses.R; import com.app.centuarymattresses.adapter.SleeparticleAdapter; import com.app.centuarymattresses.model.sleeparticle.SleeparticleModel; import com.app.centuarymattresses.util.ParamsConstans; import com.app.centuarymattresses.util.Utils; import com.app.centuarymattresses.view.MenuBarActivity; import com.app.centuarymattresses.webservice.WSGetSleepArticleData; import java.util.ArrayList; public class SleeparticleFragment extends BaseFragment implements SleeparticleAdapter.OnItemClickListener { //Declaration private LinearLayout llContainer; private LinearLayout llProgress; private RecyclerView rvSleeptipsList; private LinearLayoutManager linearLayoutManager; private RelativeLayout rlEmpty; private SearchView searchView; private String searchKeyWord; private boolean isFromSearch = false; private boolean isDataLoadingFromServer = false; private GetSleepArticleAsyncTask getSleepArticleAsyncTask; private ArrayList<SleeparticleModel> sleeparticleModelArrayList = new ArrayList<>(); private SleeparticleAdapter sleeparticleAdapter; private static int MAX_CLICK_INTERVAL = 1500; private long mLastClickTime = 0; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.fragment_sleeparticle, container, false); initToolbar(); initComponents(rootView); setHasOptionsMenu(true); return rootView; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void initComponents(View rootView) { llContainer = (LinearLayout) rootView.findViewById(R.id.fragment_sleeparticle_llContainer); rvSleeptipsList = (RecyclerView) rootView.findViewById(R.id.fragment_sleeparticle_rvProductList); rlEmpty = (RelativeLayout) rootView.findViewById(R.id.fragment_rlEmpty); llProgress = (LinearLayout) rootView.findViewById(R.id.fragment_sleeparticle_llProgress); linearLayoutManager = new LinearLayoutManager(getActivity()); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); rvSleeptipsList.setLayoutManager(linearLayoutManager); getSleepArticleList(); } public void initToolbar() { ((MenuBarActivity) getActivity()).setUpToolbar(getString(R.string.menu_sleep_article), false); } public void getSleepArticleList() { if (Utils.isOnline(getActivity(), true)) { if (getSleepArticleAsyncTask != null && getSleepArticleAsyncTask.getStatus() == AsyncTask.Status.PENDING) { getSleepArticleAsyncTask.execute(); } else if (getSleepArticleAsyncTask == null || getSleepArticleAsyncTask.getStatus() == AsyncTask.Status.FINISHED) { getSleepArticleAsyncTask = new GetSleepArticleAsyncTask(); getSleepArticleAsyncTask.execute(); } } else { llProgress.setVisibility(View.GONE); emptyView(); Utils.snackbar(llContainer, "" + getString(R.string.check_connection), true, getActivity()); } } @Override public void onItemClick(View view, SleeparticleModel viewModel) { /** * Logic to Prevent the Launch of the Fragment Twice if User makes * the Tap(Click) very Fast. */ if (SystemClock.elapsedRealtime() - mLastClickTime < MAX_CLICK_INTERVAL) { return; } mLastClickTime = SystemClock.elapsedRealtime(); Utils.hideKeyboard(getActivity()); DetailsVideoPdfWebviewImgFragment detailsVideoPdfWebviewImgFragment = new DetailsVideoPdfWebviewImgFragment(); detailsVideoPdfWebviewImgFragment.setTargetFragment(SleeparticleFragment.this,0); Bundle bundle=new Bundle(); bundle.putString(getString(R.string.type),viewModel.getContent_type()); bundle.putString(getString(R.string.value),viewModel.getContent_type().equals(getString(R.string.lbl_html)) ? viewModel.getContent_description() : viewModel.getImage()); bundle.putString(getString(R.string.title_val),viewModel.getTitle()); detailsVideoPdfWebviewImgFragment.setArguments(bundle); Utils.addNextFragment(getActivity(), detailsVideoPdfWebviewImgFragment, SleeparticleFragment.this, false); } private void emptyView() { rlEmpty.setVisibility(View.VISIBLE); rvSleeptipsList.setVisibility(View.GONE); } private void setUpAdapater(ArrayList<SleeparticleModel> arrayList) { rlEmpty.setVisibility(View.GONE); rvSleeptipsList.setVisibility(View.VISIBLE); sleeparticleAdapter = new SleeparticleAdapter(SleeparticleFragment.this, getActivity(), arrayList); sleeparticleAdapter.setOnItemClickListener(this); rvSleeptipsList.setAdapter(sleeparticleAdapter); } /** * Option menu for Searchview * * @param menu * @param inflater */ @Override public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); menu.clear(); inflater.inflate(R.menu.menu_search, menu); final MenuItem menuItem = menu.findItem(R.id.menu_search); searchView = (SearchView) menuItem.getActionView(); searchView.setMaxWidth(Integer.MAX_VALUE); searchView.setQueryHint(getString(R.string.actionbar_search_hint)); searchView.setGravity(Gravity.END); final LinearLayout searchBar = (LinearLayout) searchView.findViewById(R.id.search_bar); LayoutTransition layoutTransition = new LayoutTransition(); layoutTransition.setStartDelay(LayoutTransition.APPEARING, 100); searchBar.setLayoutTransition(layoutTransition); searchView.setOnCloseListener(new SearchView.OnCloseListener() { @Override public boolean onClose() { searchKeyWord = ""; return true; } }); MenuItemCompat.setOnActionExpandListener(menuItem, new MenuItemCompat.OnActionExpandListener() { @Override public boolean onMenuItemActionCollapse(MenuItem item) { searchKeyWord = ""; isFromSearch = false; if (Utils.isNetworkAvailable(getActivity())) { getSleepArticleList(); } else { Utils.snackbar(llContainer, "" + getString(R.string.check_connection), true, getActivity()); } return true; } @Override public boolean onMenuItemActionExpand(MenuItem item) { // Do something when expanded return true; // Return true to expand action view } }); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { if (!isDataLoadingFromServer) { isFromSearch = true; searchKeyWord = query; //Clear list data before search getSleepArticleList(); return false; } return false; } @Override public boolean onQueryTextChange(String newText) { return false; } }); if (isFromSearch) { menuItem.expandActionView(); if (!TextUtils.isEmpty(searchKeyWord)) searchView.setQuery(searchKeyWord, false); } } @Override public void onClick(View v) { } @Override public void onDestroy() { super.onDestroy(); if (getSleepArticleAsyncTask != null && getSleepArticleAsyncTask.getStatus() == AsyncTask.Status.RUNNING) { getSleepArticleAsyncTask.cancel(true); } } /** * Called when coming back from next screen */ @Override public void onHiddenChanged(boolean hidden) { super.onHiddenChanged(hidden); if (!hidden) { setHasOptionsMenu(true); initToolbar(); } } private class GetSleepArticleAsyncTask extends AsyncTask<Void, Void, Void> { private WSGetSleepArticleData wsGetSleepArticleData; @Override protected void onPreExecute() { super.onPreExecute(); llProgress.setVisibility(View.VISIBLE); if (searchView != null) { searchView.postDelayed(new Runnable() { @Override public void run() { InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0); } }, 300); } } @Override protected Void doInBackground(Void... params) { try { isDataLoadingFromServer = true; wsGetSleepArticleData = new WSGetSleepArticleData(getActivity()); sleeparticleModelArrayList = wsGetSleepArticleData.executeService(getActivity(), getBundel()); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { isDataLoadingFromServer = false; if (wsGetSleepArticleData.isSuccess()) { if (sleeparticleModelArrayList != null && sleeparticleModelArrayList.size() > 0) { setUpAdapater(sleeparticleModelArrayList); llProgress.setVisibility(View.GONE); } else { llProgress.setVisibility(View.GONE); Utils.snackbar(llContainer, "" + getString(R.string.no_sleeparticle_found), true, getActivity()); emptyView(); } } else { llProgress.setVisibility(View.GONE); Utils.snackbar(llContainer, "" + wsGetSleepArticleData.getMessage(), true, getActivity()); emptyView(); } } } private Bundle getBundel() { Bundle bundle=new Bundle(); bundle.putString(ParamsConstans.PARAM_SEARCH,searchKeyWord); return bundle; } }
------------------call adapter----package com.app.centuarymattresses.adapter; import android.content.Context; import android.os.Handler; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import com.app.centuarymattresses.R; import com.app.centuarymattresses.customecomponent.CustomTextView; import com.app.centuarymattresses.fragment.SleeparticleFragment; import com.app.centuarymattresses.model.sleeparticle.SleeparticleModel; import com.bumptech.glide.Glide; import java.util.List; public class SleeparticleAdapter extends RecyclerView.Adapter<SleeparticleAdapter.ViewHolder> implements View.OnClickListener { private List<SleeparticleModel> items; private OnItemClickListener onItemClickListener; private Context mContext; private SleeparticleFragment sleeparticleFragment; private int lastPosition = -1; public SleeparticleAdapter(SleeparticleFragment sleeparticleFragment, Context context, List<SleeparticleModel> items) { this.items = items; this.sleeparticleFragment = sleeparticleFragment; this.mContext = context; } public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_sleeparticlelist, parent, false); v.setOnClickListener(this); return new ViewHolder(v); } @Override public void onBindViewHolder(ViewHolder holder, int position) { if (position > lastPosition) { Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.up_from_bottom ); holder.itemView.startAnimation(animation); } lastPosition = position; final SleeparticleModel item = items.get(position); holder.tvTitle.setText("" + item.getTitle()); holder.tvDes.setText(Html.fromHtml(item.getDescription())); holder.productDate.setText(item.getDate()); if (item.getImage_front() != null) { final String url = item.getImage_front(); Glide.with(mContext).load(url) .placeholder(R.drawable.ic_placeholder) .error(R.drawable.ic_placeholder) .into(holder.ivProductImg); } holder.itemView.setTag(item); } @Override public int getItemCount() { return items.size(); } @Override public void onClick(final View v) { // Give some time to the ripple to finish the effect if (onItemClickListener != null) { new Handler().postDelayed(new Runnable() { @Override public void run() { onItemClickListener.onItemClick(v, (SleeparticleModel) v.getTag()); } }, 200); } } public interface OnItemClickListener { void onItemClick(View view, SleeparticleModel viewModel); } protected static class ViewHolder extends RecyclerView.ViewHolder { private CardView cvContainer; private ImageView ivProductImg; private CustomTextView tvTitle; private CustomTextView tvDes; private CustomTextView productDate; public ViewHolder(View itemView) { super(itemView); cvContainer = (CardView) itemView.findViewById(R.id.row_sleeparticle_cvContainer); ivProductImg = (ImageView) itemView.findViewById(R.id.row_sleeparticle_ivProductImg); tvTitle = (CustomTextView) itemView.findViewById(R.id.row_sleeparticle_tvTitle); tvDes = (CustomTextView) itemView.findViewById(R.id.row_sleeparticle_tvDescription); productDate = (CustomTextView) itemView.findViewById(R.id.row_sleeparticle_tvDate); } } @Override public void onViewDetachedFromWindow(final SleeparticleAdapter.ViewHolder holder) { holder.itemView.clearAnimation(); } }
--------Base Fragment-----
package com.app.centuarymattresses.fragment; import android.app.Fragment; import android.os.Bundle; import android.os.SystemClock; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import com.app.centuarymattresses.R; import com.app.centuarymattresses.util.Utils; public abstract class BaseFragment extends Fragment implements View.OnClickListener { private static int MAX_CLICK_INTERVAL = 3000; private long mLastClickTime = 0; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.fragment_product, container, false); return rootView; } public abstract void initComponents(View rootView); @Override public void onClick(View v) { /** * Logic to Prevent the Launch of the Fragment Twice if User makes * the Tap(Click) very Fast. */ if (SystemClock.elapsedRealtime() - mLastClickTime < MAX_CLICK_INTERVAL) { return; } mLastClickTime = SystemClock.elapsedRealtime(); } public void validateField(View container, EditText etFielde, String errMsg) { Utils.snackbar(container, errMsg, true, getActivity()); etFielde.requestFocus(); //requestFocus(etFielde); } public void handleDoubleClick() { /** * Logic to Prevent the Launch of the Fragment Twice if User makes * the Tap(Click) very Fast. */ if (SystemClock.elapsedRealtime() - mLastClickTime < MAX_CLICK_INTERVAL) { return; } mLastClickTime = SystemClock.elapsedRealtime(); } }--------for Login--------package com.app.scheurer4life.activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import com.app.scheurer4life.R; import com.app.scheurer4life.Scheurer4lifeAplication; import com.app.scheurer4life.comman.DialogForgotPassword; import com.app.scheurer4life.model.LoginModel; import com.app.scheurer4life.util.Constant; import com.app.scheurer4life.util.Preference; import com.app.scheurer4life.util.Utils; import com.app.scheurer4life.webservice.WSLogin; import com.app.scheurer4life.webservice.WsConstants; import com.google.firebase.iid.FirebaseInstanceId; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; /** * ************************************************************************* * LoginActivity * Class is user for login into application through valid credentials. * <p/> * ************************************************************************* */public class LoginActivity extends BaseActivity { public String TAG = "LoginActivity"; @Bind(R.id.activity_login_tvSignUp) TextView tvSignUp; @Nullable @Bind(R.id.activity_login_tvDate) TextView tvDate; @Nullable @Bind(R.id.activity_login_tvForgotPassword) TextView tvForgotPassword; @Nullable @Bind(R.id.activity_login_etEmail) EditText etEmail; @Nullable @Bind(R.id.activity_login_etPassword) EditText etPassword; @Nullable @Bind(R.id.activity_login_ll_main) LinearLayout llMainLayout; private LoginTask loginTask; @Nullable @Bind(R.id.activity_login_btnLogin) Button btnLogin; //Google Sign private static final int GOOGLE_REQ = 9001; private ProgressDialog mProgressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ButterKnife.bind(this); initComponents(); // private String android_id = Secure.getString(getContext().getContentResolver(),// Secure.ANDROID_ID); if (FirebaseInstanceId.getInstance() != null && FirebaseInstanceId.getInstance().getToken() != null && !FirebaseInstanceId.getInstance().getToken().isEmpty()) { Preference.getInstance().savePreferenceData(Preference.getInstance().KEY_DEVICE_TOKEN, FirebaseInstanceId.getInstance().getToken()); Log.e("LoginActivity","FCM Token :" + FirebaseInstanceId.getInstance().getToken()); } else { Preference.getInstance().savePreferenceData(Preference.getInstance().KEY_DEVICE_TOKEN, Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID)); Log.e("LoginActivity","Device Token :" + Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID)); } String signUpMsg = getIntent().getStringExtra(Constant.PASS_MSG_TO_LOGIN); if (signUpMsg != null && !signUpMsg.isEmpty()) { Utils.showMessage(LoginActivity.this, llMainLayout, signUpMsg, false); } Scheurer4lifeAplication.getmInstance().trackScreenView(getString(R.string.ga_screen_login)); } @Override public void initComponents() { addComponents(); } @Override public void addComponents() { setCommonData(); } /** * open forgot password */ @OnClick(R.id.activity_login_tvForgotPassword) protected void openForgotPassword() { Utils.hideKeyboard(LoginActivity.this); if (Utils.isOnline(LoginActivity.this, true)) { DialogForgotPassword openForgotPasswordDialog = new DialogForgotPassword(LoginActivity.this, new DialogForgotPassword.ForgotPasswordEventListener() { @Override public void forgotPasswordOk() { } @Override public void showMsg(String errMsg) { Utils.showMessage(LoginActivity.this, llMainLayout, errMsg, true); } }); openForgotPasswordDialog.show(); } } /** * open signup form */ @OnClick(R.id.activity_login_tvSignUp) protected void openSignup() { Utils.hideKeyboard(LoginActivity.this); if (Utils.isOnline(LoginActivity.this, true)) { Intent mHomeIntentSign = new Intent(LoginActivity.this, SignUpActivity.class); startActivity(mHomeIntentSign); overridePendingTransition(R.anim.anim_right_in, R.anim.anim_left_out); finish(); } } /** * Validating form */ @OnClick(R.id.activity_login_btnLogin) protected void submitForm() { Utils.hideKeyboard(LoginActivity.this); if (!validateField(etEmail, getString(R.string.err_msg_email))) { return; } else if (!validateEmail()) { return; } else if (!validateField(etPassword, getString(R.string.err_msg_password))) { return; } else { callLogin(); } } private void setCommonData() { if (tvDate != null) { Utils.setDate(tvDate); } } private void callLogin() { Utils.hideKeyboard(this); if (Utils.isOnline(this, true)) { if (loginTask != null && loginTask.getStatus() == AsyncTask.Status.PENDING) { loginTask.execute(); } else if (loginTask == null || loginTask.getStatus() == AsyncTask.Status.FINISHED) { loginTask = new LoginTask(); loginTask.execute(etEmail.getText().toString(), etPassword.getText().toString()); } } } private boolean validateEmail() { String email = etEmail.getText().toString().trim(); if (!isValidEmail(email)) { Utils.showMessage(LoginActivity.this, llMainLayout, getString(R.string.err_msg_invalid_email), true); requestFocus(etEmail); return false; } return true; } private boolean validateField(EditText etFielde, String errMsg) { String password = etFielde.getText().toString().trim(); if (password.isEmpty()) { Utils.showMessage(LoginActivity.this, llMainLayout, errMsg, true); requestFocus(etFielde); return false; } return true; } private static boolean isValidEmail(String email) { return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches(); } private void requestFocus(View view) { if (view.requestFocus()) { getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } } /** * This class is used to make employer login api call. * It will extends AsyncTask and will recieve {@link String} variables as input parameters and return {@link LoginModel} */ private class LoginTask extends AsyncTask<String, Void, LoginModel> { private WSLogin wsLogin; @Override protected void onPreExecute() { super.onPreExecute(); Utils.showProgressDialog(LoginActivity.this, getString(R.string.please_wait), false); } @Override protected LoginModel doInBackground(String... params) { wsLogin = new WSLogin(LoginActivity.this); return wsLogin.executeService(LoginActivity.this, params[0], params[1]); } @Override protected void onPostExecute(LoginModel loginModel) { super.onPostExecute(loginModel); Utils.dismissProgressDialog(); WsConstants wsConstants = new WsConstants(); if (wsLogin.isSuccess()) { if (loginModel != null) { Utils.writeLog(LoginActivity.this, loginModel.toString()); Preference.getInstance().savePreferenceData(wsConstants.PREFISLOGIN, true); Preference.getInstance().savePreferenceData(wsConstants.PREFACCESSTOKEN, loginModel.getAccess_token()); startActivity(new Intent(LoginActivity.this, MenuBarActivity.class)); overridePendingTransition(R.anim.anim_right_in, R.anim.anim_left_out); finish(); } } else { Utils.displayDialog(LoginActivity.this, getString(R.string.app_name), wsLogin.getMessage(), getString(R.string.ok), "", false, false); } } } @Override protected void onDestroy() { super.onDestroy(); if (loginTask != null && loginTask.getStatus() == AsyncTask.Status.RUNNING) { loginTask.cancel(true); } } }--------WSConstant------package com.app.centuarymattresses.util; public class WsConstants { //public final static String BASE_URL = "http://p.configure.it/centuary_mattresses28323/WS/"; public final static String BASE_URL ="http://php54.indianic.com/centuary_mattress/WS/"; public final static int CONNECTION_TIMEOUT = 30; public final static int SUCCESS_1 = 1; public final static String PARAMS_ACCESS_TOKEN = "access_token"; /** * API name for web service implementation */ public final static String METHOD_QUESTIONNAIRE_LIST = "questionnaire_list"; public final static String METHOD_SEARCH_PRODUCT_LIST = "searched_product"; public final static String METHOD_COLLECTION_LIST = "product_collection_listing"; public final static String METHOD_SLEEPTIPS_LIST = "show_sleep_tips_listing"; public final static String METHOD_MATTRESSCARE_LIST = "mattress_care_listing"; public final static String METHOD_SLEEPARTICLE_LIST = "sleep_article_listing"; public final static String METHOD_CLAIM_LIST = "claim_listing"; public final static String METHOD_ADD_CLAIM = "create_claim"; public final static String METHOD_ADD_CUSTOMER = "add_customer"; public final static String METHOD_NEAREST_STORE = "view_nearest_store"; public final static String METHOD_NEAREST_STORE_DETAILS = "store_details"; public final static String METHOD_REQUEST_FOR_DEMO = "request_to_demo"; public final static String METHOD_PRODUCT_DETAILS = "product_details"; public final static String METHOD_SEND_MESSAGE = "send_meassage"; public final static String METHOD_CLAIM_DETAILS = "claim_details"; // Base params public final String PARAMS_SETTING = "settings"; public final String PARAMS_DATA = "data"; public final String PARAMS_CLAIM_DETAILS = "get_claim_details"; public final String PARAMS_SUCCESS = "success"; public final String DEVICE_PLATFORM = "Android"; public final String PARAMS_MESSAGE = "message"; /** * common parameter name for webservice calling */ public WsConstants() { } }---------Util----------package com.app.centuarymattresses.util; import android.animation.Animator; import android.annotation.TargetApi; import android.app.Activity; import android.app.ActivityManager; import android.app.AlertDialog; import android.app.Fragment; import android.app.FragmentTransaction; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.Environment; import android.provider.Settings.Secure; import android.support.design.widget.Snackbar; import android.telephony.TelephonyManager; import android.transition.TransitionInflater; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewAnimationUtils; import android.view.inputmethod.InputMethodManager; import android.widget.TextView; import android.widget.Toast; import com.app.centuarymattresses.R; /** * @purpose commonly used functions * @purpose */public class Utils { public static final int MEDIA_TYPE_IMAGE = 1; public static final int MEDIA_TYPE_FILE = 2; /** * @param context * @param message * @return * @description use to check internet network connection if network * connection not available than alert for open network * settings */ public static boolean isOnline(final Activity context, boolean message) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo(); if (netInfo != null) { if (netInfo.isConnectedOrConnecting()) { return true; } } if (message) { final AlertDialog.Builder dialog = new AlertDialog.Builder(context); dialog.setTitle(context.getString(R.string.app_name)); dialog.setCancelable(false); dialog.setMessage(context.getString(R.string.check_connection)); dialog.setPositiveButton(context.getString(R.string.settings), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); context.startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS)); } }); dialog.setNegativeButton(context.getString(android.R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); dialog.show(); return false; } return false; } /** * Method is used for checking network availability. * * @param context * @return isNetAvailable: boolean true for Internet availability, false otherwise */ public static boolean isNetworkAvailable(Context context) { boolean isNetAvailable = false; if (context != null) { final ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (mConnectivityManager != null) { boolean mobileNetwork = false; boolean wifiNetwork = false; boolean mobileNetworkConnecetd = false; boolean wifiNetworkConnecetd = false; final NetworkInfo mobileInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); final NetworkInfo wifiInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (mobileInfo != null) { mobileNetwork = mobileInfo.isAvailable(); } if (wifiInfo != null) { wifiNetwork = wifiInfo.isAvailable(); } if (wifiNetwork || mobileNetwork) { if (mobileInfo != null) mobileNetworkConnecetd = mobileInfo.isConnectedOrConnecting(); wifiNetworkConnecetd = wifiInfo.isConnectedOrConnecting(); } isNetAvailable = (mobileNetworkConnecetd || wifiNetworkConnecetd); } } return isNetAvailable; } /** * @param context * @param title * @param msg * @param strPositiveText * @param strNegativeText * @param isNagativeBtn * @param isFinish * @purpose dialog which show positive and optional negative button */ public static void displayDialog(final Activity context, final String title, final String msg, final String strPositiveText, final String strNegativeText, final boolean isNagativeBtn, final boolean isFinish) { final AlertDialog.Builder dialog = new AlertDialog.Builder(context); dialog.setTitle(title); dialog.setCancelable(false); dialog.setMessage(msg); dialog.setPositiveButton(strPositiveText, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); if (isFinish) { context.getFragmentManager().popBackStack(); } } }); if (isNagativeBtn) { dialog.setNegativeButton(strNegativeText, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); } dialog.show(); } /** * Method is used for displaying dialog and finishing activity on dialog button click id isFinish is true * * @param title * @param msg * @param context * @param isFinish */ public static void displayDialog(String title, String msg, final Context context, final boolean isFinish) { // final AlertDialog.Builder alertDialog = new // AlertDialog.Builder(context); final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context); alertDialog.setTitle(title); alertDialog.setCancelable(false); alertDialog.setMessage(msg); alertDialog.setNeutralButton(context.getString(android.R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (isFinish) ((Activity) context).finish(); } }); final AlertDialog dialog = alertDialog.create(); if (!((Activity) context).isFinishing()) { if (!dialog.isShowing()) { alertDialog.show(); } } } /** * @param mActivity * @param message * @param isCancelable * @return * @purpose show progress dialog */ public static ProgressDialog showProgressDialog1(final Activity mActivity, final String message, boolean isCancelable) { final ProgressDialog mDialog = new ProgressDialog(mActivity); mDialog.show(); mDialog.setCancelable(isCancelable); mDialog.setCanceledOnTouchOutside(false); mDialog.setMessage(message); return mDialog; } public static final void dismissProgressDialog(ProgressDialog progressDialog) { if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } } public final static boolean isValidPassword(final String password) { // pattern = Pattern.compile(PASSWORD_PATTERN); // matcher = pattern.matcher(password); // return matcher.matches(); if (password.length() < 6) { return false; } else { return true; } } /** * @param inputEmail * @return * @purpose validate email */ public final static boolean isValidEmail(CharSequence inputEmail) { if (inputEmail == null) { return false; } else { return android.util.Patterns.EMAIL_ADDRESS.matcher(inputEmail).matches(); } } /** * @param activity * @return * @purpose check the device has calling functionality or not */ public final static boolean isCalling(Activity activity) { if (((TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE)).getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) { // no phone return false; } return true; } /** * @param context * @return * @purpose get the device ID */ public final static String getDeviceID(Context context) { return Secure.getString(context.getContentResolver(), Secure.ANDROID_ID); } /** * Hide KeyBoard Using CurrentFocus * * @return */ public static void hideKeyboard(Context mContext) { InputMethodManager inputManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); View focus = ((Activity) mContext).getCurrentFocus(); if (focus != null) { inputManager.hideSoftInputFromWindow(focus.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } /** * Hide KeyBoard Using CurrentFocus when FragmentDialog * * @return */ public static void hideKeyboardWithDialog(Context mContext) { InputMethodManager inputManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); View focus = ((Activity) mContext).getCurrentFocus(); if (focus != null) { inputManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); } } /** * @param activity * @purpose hide softkey board */ public static void hideSoftKeyboardWhenNeeded(Activity activity) { final InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); if (inputMethodManager.isActive()) { if (activity.getCurrentFocus() != null) { inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } } /** * @param context * @param detail * @purpose for writing the log */ public static void writeLog(final Context context, String detail) { if (true) { Log.i(context.getClass().getSimpleName(), detail); } } /** * @return isPresnet * @purpose check the sd card available or not */ public final static Boolean checkSDCardAvalibility() { Boolean isSDPresent = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); return isSDPresent; } public static void snackbar(final View view, final String msg, boolean isSnakbar, Context mContext) { try { if (isSnakbar) { Snackbar snack = Snackbar.make(view, msg, Snackbar.LENGTH_LONG); snack.getView().setBackgroundColor(Color.parseColor("#FF014571")); View viewNew = snack.getView(); TextView tv = (TextView) viewNew.findViewById(android.support.design.R.id.snackbar_text); tv.setGravity(Gravity.CENTER_HORIZONTAL); snack.show(); } else { Toast.makeText(mContext, "" + msg, Toast.LENGTH_LONG).show(); } } catch (Exception e) { e.printStackTrace(); } } /** * @param mActivity * @param targetedFragment * @param shooterFragment * @purpose for call targeted fragment from current fragment */ public static void addNextFragment(Activity mActivity, Fragment targetedFragment, Fragment shooterFragment, boolean isDownToUp) { final FragmentTransaction transaction = mActivity.getFragmentManager().beginTransaction(); if (isDownToUp) { transaction.setCustomAnimations(R.animator.slide_fragment_vertical_right_in, R.animator.slide_fragment_vertical_left_out, R.animator.slide_fragment_vertical_left_in, R.animator.slide_fragment_vertical_right_out); //FragmentTransactionExtended fragmentTransactionExtended = new FragmentTransactionExtended(mActivity, transaction, shooterFragment, targetedFragment, R.id.activity_menubar_containers); //fragmentTransactionExtended.addTransition(FragmentTransactionExtended.SLIDE_VERTICAL); } else { transaction.setCustomAnimations(R.animator.slide_fragment_horizontal_right_in, R.animator.slide_fragment_horizontal_left_out, R.animator.slide_fragment_horizontal_left_in, R.animator.slide_fragment_horizontal_right_out); //FragmentTransactionExtended fragmentTransactionExtended = new FragmentTransactionExtended(mActivity, transaction, shooterFragment, targetedFragment, R.id.activity_menubar_containers); //fragmentTransactionExtended.addTransition(FragmentTransactionExtended.SLIDE_HORIZONTAL); } transaction.add(R.id.activity_menubar_containers, targetedFragment, targetedFragment.getClass().getSimpleName()); //curFragment = targetedFragment; transaction.hide(shooterFragment); transaction.addToBackStack(targetedFragment.getClass().getSimpleName()); transaction.commit(); } public static ProgressDialog showProgressDialog(final Context mActivity, final String message, boolean isCancelable) { final ProgressDialog mDialog = new ProgressDialog(mActivity, R.style.customeDialog); mDialog.show(); mDialog.setCancelable(false); mDialog.setCanceledOnTouchOutside(false); //mDialog.setMessage(message); //mDialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small); return mDialog; } /** * @param mActivity * @param targetedFragment * @param shooterFragment * @purpose for call targeted fragment from current fragment */ public static void addNextFragmentWithoutAnimation(Activity mActivity, Fragment targetedFragment, Fragment shooterFragment) { final FragmentTransaction transaction = mActivity.getFragmentManager().beginTransaction(); transaction.add(R.id.activity_menubar_containers, targetedFragment, targetedFragment.getClass().getSimpleName()); //curFragment = targetedFragment; transaction.hide(shooterFragment); transaction.addToBackStack(targetedFragment.getClass().getSimpleName()); transaction.commit(); } public static void addNextFragmentLolipopWithShareElement(Activity mActivity, Fragment targetedFragment, Fragment shooterFragment, View mView, String textTransitionName, String textTransitionImg, View imageView) { final FragmentTransaction transaction = mActivity.getFragmentManager().beginTransaction(); transaction.add(R.id.activity_menubar_containers, targetedFragment, targetedFragment.getClass().getSimpleName()); //curFragment = targetedFragment; transaction.addToBackStack(targetedFragment.getClass().getSimpleName()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //shooterFragment.setSharedElementReturnTransition(TransitionInflater.from(mActivity).inflateTransition(R.transition.change_image_trans)); shooterFragment.setExitTransition(TransitionInflater.from(mActivity).inflateTransition(android.R.transition.fade)); targetedFragment.setSharedElementEnterTransition(TransitionInflater.from(mActivity).inflateTransition(R.transition.change_image_trans)); targetedFragment.setEnterTransition(TransitionInflater.from(mActivity).inflateTransition(android.R.transition.fade)); transaction.addSharedElement(mView, textTransitionName); transaction.addSharedElement(imageView, textTransitionImg); } transaction.hide(shooterFragment); transaction.commit(); } // To reveal a previously invisible view using this effect: @TargetApi(Build.VERSION_CODES.LOLLIPOP) public static void show(final View view) { // get the center for the clipping circle int cx = (view.getLeft() + view.getRight()) / 2; int cy = (view.getTop() + view.getBottom()) / 2; // get the final radius for the clipping circle int finalRadius = Math.max(view.getWidth(), view.getHeight()); // create the animator for this view (the start radius is zero) Animator anim = ViewAnimationUtils.createCircularReveal(view, cx, cy, 0, finalRadius); anim.setDuration(1000); // make the view visible and start the animation view.setVisibility(View.VISIBLE); anim.start(); } public static boolean isGPSOn(final Context context) { final LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); boolean gps_enabled = false; boolean network_enabled = false; try { gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch (Exception ex) { ex.printStackTrace(); } try { network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch (Exception ex) { ex.printStackTrace(); } return gps_enabled || network_enabled; } public static boolean isMyServiceRunning(Class<?> serviceClass, Context ctx) { final ActivityManager manager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } public static boolean isNumeric(String strToCheck) { if (strToCheck == null) return false; return strToCheck.matches(Constans.REGEX_IS_NUMERIC); } }-------param constant---package com.app.centuarymattresses.util; /** * Created by on 30/05/15. */ public class ParamsConstans { public static String PARAM_SEARCH = "search"; public static String PARAM_STORE_ID = "store_id"; public static String PARAM_DESCRIPTION = "description"; public static String PARAM_DEVICE_TOKEN = "device_token"; public static String PARAM_UNIQUE_ID = "android_unique_id"; //CLAIM public static String PARAM_SUBJECT = "title"; public static String PARAM_CLAIM_NAME = "name"; public static String PARAM_CLAIM_MOBILE = "mobile_number"; public static String PARAM_CLAIM_EMAIL = "email"; public static String PARAM_CLAIM_PLACE_OF_PURCHASE = "purchase_place"; public static String PARAM_CLAIM_DATE_OF_PURCHASE = "purchase_date"; public static String PARAM_CLAIM_PRODUCT_NAME = "product_name"; public static String PARAM_CLAIM_NATURE_OF_COMPLAIN = "description"; public static String PARAM_CUSTOMER_ID = "customer_id"; public static String PARAM_MESSAGE = "message"; public static String PARAM_CLAIMS_ID = "claims_id"; //PRODUCT public static String PARAM_PRODUCT_CATEGORY_ID = "product_category_id"; public static String PARAM_PRODUCT_ID = "product_id"; //NEARS STORE LOCATOR public static String PARAM_LATITUTE = "latitude"; public static String PARAM_LONGITUTE = "longitude"; //REQUEST FOR DEMO public static String PARAM_NAME = "name"; public static String PARAM_EMAIL = "email"; public static String PARAM_PHONE_NUMBER = "phone_number"; //Search Product Category params public static String PARAM_FIRM_ID = "elm_firm_id"; public static String PARAM_MATTRESS_TYPE_ID = "elm_mattresstype_id"; public static String PARAM_COLLECTION_ID = "elm_collection_id"; public static String PARAM_THICKNESS_ID = "elm_thickness_id"; }
Comments
Post a Comment
Welcome To Android