Java tutorial
/* * Cos android client for Cozy Cloud * * Copyright (C) 2016 Hamza Abdelkebir * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package eu.codeplumbers.cosi.fragments; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.InputType; import android.util.Log; 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.widget.EditText; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.edwardvanraak.materialbarcodescanner.MaterialBarcodeScanner; import com.edwardvanraak.materialbarcodescanner.MaterialBarcodeScannerBuilder; import com.google.android.gms.vision.barcode.Barcode; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.Date; import java.util.List; import eu.codeplumbers.cosi.R; import eu.codeplumbers.cosi.activities.CozyActivity; import eu.codeplumbers.cosi.adapters.LoyaltyCardRecyclerViewAdapter; import eu.codeplumbers.cosi.db.models.Device; import eu.codeplumbers.cosi.db.models.LoyaltyCard; import eu.codeplumbers.cosi.listeners.OnListFragmentInteractionListener; import eu.codeplumbers.cosi.services.CosiLoyaltyCardService; import eu.codeplumbers.cosi.services.events.LoyaltyCardSyncEvent; import eu.codeplumbers.cosi.utils.DateUtils; import static eu.codeplumbers.cosi.utils.Constants.REFRESH; import static eu.codeplumbers.cosi.utils.Constants.SERVICE_ERROR; import static eu.codeplumbers.cosi.utils.Constants.SERVICE_NOT_RUNNING; import static eu.codeplumbers.cosi.utils.Constants.SERVICE_RUNNING; import static eu.codeplumbers.cosi.utils.Constants.SYNC_MESSAGE; import static eu.codeplumbers.cosi.utils.Constants.TAG; /** * Created by thor on 10/3/16. */ public class LoyaltyCardListFragment extends Fragment { private static final String ARG_COLUMN_COUNT = "column-count"; private int mColumnCount = 1; private OnListFragmentInteractionListener mListener; private RecyclerView recyclerView; private List<LoyaltyCard> allLoyaltyCards; private RelativeLayout progressLayout; private TextView progressMessage; private RelativeLayout emptyView; private boolean serviceRunning; private TextView txtEmptyMessage; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public LoyaltyCardListFragment() { } @SuppressWarnings("unused") public static LoyaltyCardListFragment newInstance(int columnCount) { LoyaltyCardListFragment fragment = new LoyaltyCardListFragment(); Bundle args = new Bundle(); args.putInt(ARG_COLUMN_COUNT, columnCount); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_loyaltycard_list, container, false); setHasOptionsMenu(true); serviceRunning = ((CozyActivity) getActivity()).isMyServiceRunning(); // Set the adapter Context context = view.getContext(); progressLayout = (RelativeLayout) view.findViewById(R.id.progress_layout); progressMessage = (TextView) view.findViewById(R.id.progress_message); txtEmptyMessage = (TextView) view.findViewById(R.id.txtEmptyMessage); emptyView = (RelativeLayout) view.findViewById(R.id.emptyView); recyclerView = (RecyclerView) view.findViewById(R.id.list); if (mColumnCount <= 1) { recyclerView.setLayoutManager(new LinearLayoutManager(context)); } else { recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount)); } return view; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_loyaltycard_list, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // handle item selection switch (item.getItemId()) { case R.id.action_refresh_loyaltycards: refreshLoyaltyCardsFromCozy(); return true; case R.id.action_create_loyaltycard: createNewLoyaltyCard(); return true; default: return super.onOptionsItemSelected(item); } } private void createNewLoyaltyCard() { MaterialBarcodeScanner materialBarcodeScanner = new MaterialBarcodeScannerBuilder() .withActivity(getActivity()).withEnableAutoFocus(true).withBleepEnabled(true).withBackfacingCamera() .withText("Scanning...").withResultListener(new MaterialBarcodeScanner.OnResultListener() { @Override public void onResult(Barcode barcode) { showLoyaltyCardDetailsDialog(barcode); } }).build(); materialBarcodeScanner.startScan(); } private void showLoyaltyCardDetailsDialog(final Barcode barcode) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(getString(R.string.lbl_loyalty_card_new)); // Set up the input final EditText cardName = new EditText(getActivity()); // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text cardName.setInputType(InputType.TYPE_CLASS_TEXT); builder.setView(cardName); // Set up the buttons builder.setPositiveButton(getString(R.string.SAVE), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String m_Text = cardName.getText().toString(); if (m_Text.isEmpty()) { cardName.setError(getString(R.string.lbl_loyalty_cards_name_empty)); } else { Log.d(TAG, barcode.rawValue); LoyaltyCard loyaltyCard = LoyaltyCard.getByRawValue(barcode.rawValue); if (loyaltyCard == null) { loyaltyCard = new LoyaltyCard(); loyaltyCard.setCode(barcode.format); loyaltyCard.setCreationDate(DateUtils.formatDate(new Date().getTime())); loyaltyCard.setLabel(m_Text); loyaltyCard.setRawValue(barcode.rawValue); loyaltyCard.setRemoteId(""); loyaltyCard.setDeviceId(Device.registeredDevice().getLogin()); loyaltyCard.save(); } } } }); builder.setNegativeButton(getString(R.string.CANCEL), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } private void refreshLoyaltyCardsFromCozy() { progressLayout.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.GONE); emptyView.setVisibility(View.GONE); getActivity().startService(new Intent(getActivity(), CosiLoyaltyCardService.class)); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); refreshList(); } public void refreshList() { allLoyaltyCards = LoyaltyCard.getAll(); recyclerView.setAdapter(new LoyaltyCardRecyclerViewAdapter(allLoyaltyCards, mListener, getActivity())); if (allLoyaltyCards.isEmpty()) { emptyView.setVisibility(View.VISIBLE); progressLayout.setVisibility(View.GONE); recyclerView.setVisibility(View.GONE); } else { recyclerView.setVisibility(View.VISIBLE); progressLayout.setVisibility(View.GONE); emptyView.setVisibility(View.GONE); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnListFragmentInteractionListener) { mListener = (OnListFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnListFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public void onSyncFailure(String errorMessage) { Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show(); if (errorMessage.contains("missing") && errorMessage.contains("view")) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage("You might need to update Cozy views (Go to Setup > Update Design Document)") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }).show(); } } @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(LoyaltyCardSyncEvent event) { Log.d(TAG, "Loyaltycard event: message=" + event.message + " details=" + event.details); if (event.message.equals(SERVICE_RUNNING)) { serviceRunning = true; } if (event.message.equals(SERVICE_NOT_RUNNING)) { serviceRunning = false; } if (event.message.equals(SERVICE_ERROR)) { emptyView.setVisibility(View.VISIBLE); progressLayout.setVisibility(View.GONE); recyclerView.setVisibility(View.GONE); txtEmptyMessage.setText(event.details); serviceRunning = false; } if (event.message.equals(REFRESH)) { refreshList(); serviceRunning = false; } if (event.message.equals(SYNC_MESSAGE)) { progressLayout.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.GONE); emptyView.setVisibility(View.GONE); progressMessage.setText(event.details); serviceRunning = true; } } @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onStop() { super.onStop(); EventBus.getDefault().unregister(this); } }