Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.zenisoft.dishcontroller.ui.home;
- import static android.content.ContentValues.TAG;
- import static android.content.Context.MODE_PRIVATE;
- import androidx.appcompat.app.ActionBar;
- import androidx.appcompat.app.AppCompatActivity;
- import androidx.appcompat.widget.AppCompatTextView;
- import androidx.collection.CircularArray;
- import androidx.fragment.app.Fragment;
- import androidx.fragment.app.FragmentActivity;
- import androidx.lifecycle.ViewModelProvider;
- import android.annotation.SuppressLint;
- import android.app.Activity;
- import android.app.AlertDialog;
- import android.content.Context;
- import android.content.DialogInterface;
- import android.content.Intent;
- import android.content.SharedPreferences;
- import android.os.Bundle;
- import androidx.annotation.NonNull;
- import androidx.annotation.Nullable;
- import android.telecom.Call;
- 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.Button;
- import android.widget.TextView;
- import android.widget.Toast;
- import com.android.billingclient.api.AcknowledgePurchaseParams;
- import com.android.billingclient.api.AcknowledgePurchaseResponseListener;
- import com.android.billingclient.api.BillingClient;
- import com.android.billingclient.api.BillingClientStateListener;
- import com.android.billingclient.api.BillingFlowParams;
- import com.android.billingclient.api.BillingResult;
- import com.android.billingclient.api.ConsumeParams;
- import com.android.billingclient.api.ConsumeResponseListener;
- import com.android.billingclient.api.ProductDetails;
- import com.android.billingclient.api.ProductDetailsResponseListener;
- import com.android.billingclient.api.Purchase;
- import com.android.billingclient.api.PurchasesResponseListener;
- import com.android.billingclient.api.PurchasesUpdatedListener;
- import com.android.billingclient.api.QueryProductDetailsParams;
- import com.android.billingclient.api.QueryPurchasesParams;
- import com.android.billingclient.api.SkuDetails;
- import com.android.billingclient.api.SkuDetailsParams;
- import com.android.billingclient.api.SkuDetailsResponseListener;
- import com.anjlab.android.iab.v3.BillingProcessor;
- import com.anjlab.android.iab.v3.PurchaseInfo;
- import com.anjlab.android.iab.v3.PurchaseState;
- import com.google.common.collect.ImmutableList;
- import com.zenisoft.dishcontroller.BuildConfig;
- import com.zenisoft.dishcontroller.Constants;
- import com.zenisoft.dishcontroller.DetailActivity;
- import com.zenisoft.dishcontroller.MainActivity;
- import com.zenisoft.dishcontroller.MyDatabaseHelper;
- import com.zenisoft.dishcontroller.R;
- import org.json.JSONException;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Objects;
- public class HomeFragment extends Fragment {
- private HomeViewModel mViewModel;
- public static HomeFragment newInstance() {
- return new HomeFragment();
- }
- TextView breakfastTextView, lunchTextView, dinnerTextView;
- Button breakfastButton, lunchButton, dinnerButton, generateButton;
- MyDatabaseHelper myDatabaseHelper;
- BillingClient billingClient;
- // BillingProcessor bp; //!
- private boolean readyToPurchase = false;
- int breakfast, lunch, dinner;
- @Override
- public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
- @Nullable Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.navigation_home, container, false);
- Objects.requireNonNull(((AppCompatActivity) requireActivity()).getSupportActionBar()).setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
- Objects.requireNonNull(((AppCompatActivity) requireActivity()).getSupportActionBar()).setCustomView(R.layout.action_bar_layout);
- AppCompatTextView title = requireActivity().findViewById(R.id.titleTextApp);
- title.setText(R.string.app_name);
- setHasOptionsMenu(true);
- // Подключится к Google Play
- // bp = BillingProcessor.newBillingProcessor(requireContext(), base64Key, this);
- // bp.initialize(); // binds
- // Can't create handler inside thread Thread[PlayBillingLibrary-4,5,main] that has not called Looper.prepare() ! Как решить?
- billingClient = BillingClient.newBuilder(requireContext())
- .setListener(new PurchasesUpdatedListener() {
- @Override
- public void onPurchasesUpdated(@NonNull BillingResult billingResult, @Nullable List<Purchase> purchases) {
- if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && purchases != null) {
- for (Purchase purchase : purchases) {
- verifyPayment(purchase);
- }
- } else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.USER_CANCELED) {
- // Handle an error caused by a user cancelling the purchase flow.
- } else {
- // Handle any other error codes.
- }
- }
- })
- .enablePendingPurchases()
- .build();
- // call connectGooglePlayBilling()
- connectGooglePlayBilling();
- // if(!BillingProcessor.isIabServiceAvailable(requireContext())) {
- // Toast.makeText(getContext(), "In-app billing service is unavailable, please upgrade Android Market/Play to version >= 3.9.16", Toast.LENGTH_LONG).show();
- // }
- Log.d(TAG, "onCreateView: " + getArguments());
- breakfastTextView = view.findViewById(R.id.randomBreakfastText);
- lunchTextView = view.findViewById(R.id.randomLunchText);
- dinnerTextView = view.findViewById(R.id.randomDinnerText);
- breakfastButton = view.findViewById(R.id.regenBreakfastButton);
- lunchButton = view.findViewById(R.id.regenLunchButton);
- dinnerButton = view.findViewById(R.id.regenDinnerButton);
- generateButton = view.findViewById(R.id.generateButton);
- myDatabaseHelper = new MyDatabaseHelper(getContext());
- generateButton.setOnClickListener(v -> {
- breakfast = myDatabaseHelper.getRandomDish("breakfast");
- lunch = myDatabaseHelper.getRandomDish("lunch");
- dinner = myDatabaseHelper.getRandomDish("dinner");
- String breakfastName = myDatabaseHelper.getDishNameById(breakfast);
- String lunchName = myDatabaseHelper.getDishNameById(lunch);
- String dinnerName = myDatabaseHelper.getDishNameById(dinner);
- breakfastTextView.setText(breakfastName);
- lunchTextView.setText(lunchName);
- dinnerTextView.setText(dinnerName);
- System.out.println("Breakfast: " + breakfast);
- if (breakfast != -1)
- {
- breakfastTextView.setOnClickListener(v1 -> {
- int id = breakfast;
- Intent intent = new Intent(getContext(), DetailActivity.class);
- intent.putExtra("id", id);
- startActivity(intent);
- });
- }
- System.out.println("Lunch: " + lunch);
- if (lunch != -1)
- {
- lunchTextView.setOnClickListener(v2 -> {
- int id = lunch;
- Intent intent = new Intent(getContext(), DetailActivity.class);
- intent.putExtra("id", id);
- startActivity(intent);
- });
- }
- System.out.println("Dinner: " + dinner);
- if (dinner != -1)
- {
- dinnerTextView.setOnClickListener(v3 -> {
- int id = dinner;
- Intent intent = new Intent(getContext(), DetailActivity.class);
- intent.putExtra("id", id);
- startActivity(intent);
- });
- }
- // Save instance state
- // setArguments(bundle);
- });
- breakfastButton.setOnClickListener(v -> {
- // Генерируем рандомное блюдо для завтрака
- breakfast = myDatabaseHelper.getRandomDish("breakfast");
- // Получаем имя блюда по его id
- String breakfastName = myDatabaseHelper.getDishNameById(breakfast);
- // Выводим имя блюда на экран
- breakfastTextView.setText(breakfastName);
- // Сохраняем информацию в Bundle для передачи в другой фрагмент
- // bundle.putInt("breakfast", breakfast);
- // setArguments(bundle);
- if (breakfast != -1)
- {
- breakfastTextView.setOnClickListener(v1 -> {
- int id = breakfast;
- Intent intent = new Intent(getContext(), DetailActivity.class);
- intent.putExtra("id", id);
- startActivity(intent);
- });
- }
- });
- lunchButton.setOnClickListener(v -> {
- lunch = myDatabaseHelper.getRandomDish("lunch");
- String lunchName = myDatabaseHelper.getDishNameById(lunch);
- lunchTextView.setText(lunchName);
- // bundle.putInt("lunch", lunch);
- // setArguments(bundle);
- if (lunch != -1)
- {
- lunchTextView.setOnClickListener(v2 -> {
- int id = lunch;
- Intent intent = new Intent(getContext(), DetailActivity.class);
- intent.putExtra("id", id);
- startActivity(intent);
- });
- }
- });
- dinnerButton.setOnClickListener(v -> {
- dinner = myDatabaseHelper.getRandomDish("dinner");
- String dinnerName = myDatabaseHelper.getDishNameById(dinner);
- dinnerTextView.setText(dinnerName);
- // bundle.putInt("dinner", dinner);
- // setArguments(bundle);
- if (dinner != -1)
- {
- dinnerTextView.setOnClickListener(v3 -> {
- int id = dinner;
- Intent intent = new Intent(getContext(), DetailActivity.class);
- intent.putExtra("id", id);
- startActivity(intent);
- });
- }
- });
- restoreDataFromSharedPreferences();
- return view;
- }
- void connectGooglePlayBilling() {
- billingClient.startConnection(new BillingClientStateListener() {
- @Override
- public void onBillingServiceDisconnected() {
- readyToPurchase = false;
- connectGooglePlayBilling();
- }
- @Override
- public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
- if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
- Log.d(TAG, "Connected " + 0);
- readyToPurchase = true;
- }
- }
- });
- }
- void buyProduct(String id) {
- List<String> skuList = new ArrayList<>();
- //replace these with your product IDs from google play console
- skuList.add(id);
- SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
- params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP);
- billingClient.querySkuDetailsAsync(params.build(),
- new SkuDetailsResponseListener() {
- @SuppressLint("SetTextI18n")
- @Override
- public void onSkuDetailsResponse(BillingResult billingResult,
- List<SkuDetails> skuDetailsList) {
- // Process the result.
- if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && skuDetailsList != null) {
- for (SkuDetails skuDetails : skuDetailsList) {
- if (skuDetails.getSku().equals(id)) {
- BillingFlowParams flowParams = BillingFlowParams.newBuilder()
- .setSkuDetails(skuDetails)
- .build();
- billingClient.launchBillingFlow(getActivity(), flowParams);
- }
- }
- }
- }
- });
- }
- void donateWindow()
- {
- Context context = getContext();
- AlertDialog.Builder builder = new AlertDialog.Builder(context);
- builder.setTitle(R.string.donate_title);
- // builder.setMessage(R.string.donate_desc);
- builder.setItems(new CharSequence[]
- {getString(R.string.donate_one), getString(R.string.donate_two), getString(R.string.donate_five), getString(R.string.donate_ten)},
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- if (!readyToPurchase) {
- Toast.makeText(context, R.string.donate_not_ready, Toast.LENGTH_SHORT).show();
- return;
- }
- // The 'which' argument contains the index position
- // of the selected item
- switch (which) {
- case 0:
- dialog.dismiss();
- // Купить товар donate_one
- // bp.purchase(getActivity(), donate_one);
- buyProduct(Constants.donate_one);
- break;
- case 1:
- dialog.dismiss();
- // bp.purchase(getActivity(), donate_two);
- buyProduct(Constants.donate_two);
- break;
- case 2:
- dialog.dismiss();
- // bp.purchase(getActivity(), donate_five);
- buyProduct(Constants.donate_five);
- break;
- case 3:
- dialog.dismiss();
- // bp.purchase(getActivity(), donate_ten);
- buyProduct(Constants.donate_ten);
- break;
- }
- }
- });
- builder.create().show();
- }
- void verifyPayment(Purchase purchase) {
- ConsumeParams consumeParams = ConsumeParams.newBuilder()
- .setPurchaseToken(purchase.getPurchaseToken())
- .build();
- ConsumeResponseListener listener = new ConsumeResponseListener() {
- @Override
- public void onConsumeResponse(@NonNull BillingResult billingResult, @NonNull String s) {
- if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
- Log.d(TAG, purchase.getSkus().get(0) + " sku");
- CallThanksDialog();
- }
- }
- };
- billingClient.consumeAsync(consumeParams, listener);
- }
- @Override
- public void onDestroy() {
- // if (bp != null) {
- // bp.release();
- // }
- super.onDestroy();
- }
- public void CallThanksDialog()
- {
- Context context = getContext();
- AlertDialog.Builder builder = new AlertDialog.Builder(context);
- builder.setTitle(R.string.thank_you_title);
- // builder.setMessage(R.string.donate_desc);
- builder.setMessage(R.string.thank_you_desc);
- builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- });
- builder.create().show();
- }
- //endregion
- //region Other
- @Override
- public void onPause()
- {
- super.onPause();
- SharedPreferences preferences = requireActivity().getPreferences(MODE_PRIVATE);
- @SuppressLint("CommitPrefEdits") SharedPreferences.Editor editor = preferences.edit(); // Put the values from the UI
- editor.putInt("breakfast", breakfast);
- editor.putInt("lunch", lunch);
- editor.putInt("dinner", dinner);
- editor.apply();
- }
- void restoreDataFromBundle(Bundle bundle)
- {
- if (bundle != null) {
- if (myDatabaseHelper.hasObject(String.valueOf(bundle.getInt("breakfast", -1))))
- {
- breakfast = bundle.getInt("breakfast", -1);
- String breakfastName = myDatabaseHelper.getDishNameById(breakfast);
- breakfastTextView.setText(breakfastName);
- breakfastTextView.setOnClickListener(v1 -> {
- int id = breakfast;
- Intent intent = new Intent(getContext(), DetailActivity.class);
- intent.putExtra("id", id);
- startActivity(intent);
- });
- }
- if (myDatabaseHelper.hasObject(String.valueOf(bundle.getInt("lunch", -1))))
- {
- lunch = bundle.getInt("lunch", -1);
- String lunchName = myDatabaseHelper.getDishNameById(lunch);
- lunchTextView.setText(lunchName);
- lunchTextView.setOnClickListener(v2 -> {
- int id = lunch;
- Intent intent = new Intent(getContext(), DetailActivity.class);
- intent.putExtra("id", id);
- startActivity(intent);
- });
- }
- if (myDatabaseHelper.hasObject(String.valueOf(bundle.getInt("dinner", -1))))
- {
- dinner = bundle.getInt("dinner", -1);
- String dinnerName = myDatabaseHelper.getDishNameById(dinner);
- dinnerTextView.setText(dinnerName);
- dinnerTextView.setOnClickListener(v3 -> {
- int id = dinner;
- Intent intent = new Intent(getContext(), DetailActivity.class);
- intent.putExtra("id", id);
- startActivity(intent);
- });
- }
- }
- Log.d(TAG, "restoreDataFromBundle: " + bundle);
- }
- void restoreDataFromSharedPreferences()
- {
- SharedPreferences sharedPref = requireActivity().getPreferences(Context.MODE_PRIVATE);
- if (sharedPref != null)
- {
- if (myDatabaseHelper.hasObject(String.valueOf(sharedPref.getInt("breakfast", -1))))
- {
- breakfast = sharedPref.getInt("breakfast", -1);
- String breakfastName = myDatabaseHelper.getDishNameById(breakfast);
- breakfastTextView.setText(breakfastName);
- breakfastTextView.setOnClickListener(v1 -> {
- int id = breakfast;
- Intent intent = new Intent(getContext(), DetailActivity.class);
- intent.putExtra("id", id);
- startActivity(intent);
- });
- }
- if (myDatabaseHelper.hasObject(String.valueOf(sharedPref.getInt("lunch", -1))))
- {
- lunch = sharedPref.getInt("lunch", -1);
- String lunchName = myDatabaseHelper.getDishNameById(lunch);
- lunchTextView.setText(lunchName);
- lunchTextView.setOnClickListener(v2 -> {
- int id = lunch;
- Intent intent = new Intent(getContext(), DetailActivity.class);
- intent.putExtra("id", id);
- startActivity(intent);
- });
- }
- if (myDatabaseHelper.hasObject(String.valueOf(sharedPref.getInt("dinner", -1))))
- {
- dinner = sharedPref.getInt("dinner", -1);
- String dinnerName = myDatabaseHelper.getDishNameById(dinner);
- dinnerTextView.setText(dinnerName);
- dinnerTextView.setOnClickListener(v3 -> {
- int id = dinner;
- Intent intent = new Intent(getContext(), DetailActivity.class);
- intent.putExtra("id", id);
- startActivity(intent);
- });
- }
- }
- }
- @Override
- public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
- super.onViewStateRestored(savedInstanceState);
- Log.d(TAG, "onViewStateRestored: " + savedInstanceState);
- restoreDataFromBundle(savedInstanceState);
- }
- @Override
- public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
- MenuInflater menuInflater = requireActivity().getMenuInflater();
- menuInflater.inflate(R.menu.home, menu);
- super.onCreateOptionsMenu(menu, inflater);
- }
- @Override
- public boolean onOptionsItemSelected(@NonNull MenuItem item) {
- if (item.getItemId() == R.id.donate_btn)
- {
- donateWindow();
- }
- return super.onOptionsItemSelected(item);
- }
- @Override
- public void onActivityCreated(@Nullable Bundle savedInstanceState) {
- super.onActivityCreated(savedInstanceState);
- mViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
- // TODO: Use the ViewModel
- // restoreDataFromBundle(savedInstanceState);
- // restoreDataFromBundle(getArguments());
- }
- /*@Override
- public void onProductPurchased(@NonNull String productId, @Nullable PurchaseInfo details) {
- if (productId.equals(donate_one) || productId.equals(donate_two) || productId.equals(donate_five) || productId.equals(donate_ten))
- {
- assert details != null;
- if (details.purchaseData.purchaseState.equals(PurchaseState.PurchasedSuccessfully))
- {
- CallThanksDialog();
- }
- }
- assert details != null;
- Log.d(TAG, "onProductPurchased: " + details.purchaseData.purchaseState);
- }
- @Override
- public void onPurchaseHistoryRestored() {
- Log.d(TAG, "onPurchaseHistoryRestored: ");
- }
- @Override
- public void onBillingError(int errorCode, @Nullable Throwable error) {
- AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
- builder.setTitle("Error");
- builder.setMessage("Error code: " + errorCode);
- builder.setPositiveButton("OK", (dialog, which) -> dialog.dismiss());
- builder.show();
- }
- @Override
- public void onBillingInitialized() {
- Log.d(TAG, "onBillingInitialized: " + "Billing initialized");
- readyToPurchase = true;
- }*/
- }
Add Comment
Please, Sign In to add comment