Java Code Examples for androidx.appcompat.app.AlertDialog#show()

The following examples show how to use androidx.appcompat.app.AlertDialog#show() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PostFragment.java    From hipda with GNU General Public License v2.0 6 votes vote down vote up
private void showImagesDialog() {
    final LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View viewlayout = inflater.inflate(R.layout.dialog_images, null);

    final GridView gridView = (GridView) viewlayout.findViewById(R.id.gv_images);

    gridView.setAdapter(mImageAdapter);

    final AlertDialog.Builder popDialog = new AlertDialog.Builder(getActivity());
    popDialog.setView(viewlayout);
    final AlertDialog dialog = popDialog.create();
    dialog.show();

    gridView.setOnItemClickListener(new OnViewItemSingleClickListener() {
        @Override
        public void onItemSingleClick(AdapterView<?> adapterView, View view, int position, long row) {
            if (view.getTag() != null)
                appendImage(view.getTag().toString());
            dialog.dismiss();
        }
    });

}
 
Example 2
Source File: FieldAdapter.java    From Field-Book with GNU General Public License v2.0 6 votes vote down vote up
private PopupMenu.OnMenuItemClickListener makeSelectMenuListener(final int position) {
    return new PopupMenu.OnMenuItemClickListener() {
        // Do it when selecting Delete or Statistics
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            final Activity thisActivity = FieldEditorActivity.thisActivity;
            final String strDel = thisActivity.getString(R.string.fields_delete);

            if (item.getTitle().equals(strDel)) {
                AlertDialog alert = createDeleteItemAlertDialog(position);
                alert.show();
                DialogUtils.styleDialogs(alert);
            }

            return false;
        }
    };
}
 
Example 3
Source File: MainActivity.java    From SimplicityBrowser with MIT License 6 votes vote down vote up
@Override
public boolean onJsConfirm(WebView view, final String url, final String message, final JsResult result) {
    if (!isDestroyed()) {
        AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
        builder1.setTitle(R.string.app_name);
        builder1.setMessage(message);
        builder1.setCancelable(true);
        builder1.setPositiveButton(R.string.ok, (dialog, id) -> {
            result.confirm();
            dialog.dismiss();
        });
        builder1.setNegativeButton(R.string.cancel, (dialog, id) -> {
            result.cancel();
            dialog.dismiss();
        });
        AlertDialog alert11 = builder1.create();
        alert11.show();
    }
    return true;

}
 
Example 4
Source File: UpdaterActivity.java    From Pix-Art-Messenger with GNU General Public License v3.0 6 votes vote down vote up
private void showCancelDialog() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(R.string.cancel_update)
            .setCancelable(false)
            .setPositiveButton(R.string.yes, (dialog, id) -> {
                if (downloadTask != null && !downloadTask.getStatus().equals(AsyncTask.Status.FINISHED)) {
                    downloadTask.cancel(true);
                }
                if (mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                }
                UpdaterActivity.this.finish();
            })
            .setNegativeButton(R.string.no, (dialog, id) -> dialog.cancel());
    final AlertDialog alert = builder.create();
    alert.show();
}
 
Example 5
Source File: MainActivity.java    From Rucky with GNU General Public License v3.0 6 votes vote down vote up
private void supportedFiles() {
    String pathDev = "/dev";
    File file1 = new File(pathDev,"hidg0");
    File file2 = new File(pathDev,"hidg1");
    if(!file1.exists() && !file2.exists()) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(getResources().getString(R.string.kernel_err));
        builder.setCancelable(false);
        builder.setPositiveButton(getResources().getString(R.string.btn_continue), ((dialog, which) -> dialog.cancel()));
        AlertDialog kernelExit = builder.create();
        Objects.requireNonNull(kernelExit.getWindow()).setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
        kernelExit.show();
    } else {
        try {
            dos.writeBytes("chmod 666 /dev/hidg0\n");
            dos.writeBytes("chmod 666 /dev/hidg1\n");
            dos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example 6
Source File: BrowserActivity.java    From GotoBrowser with GNU General Public License v3.0 6 votes vote down vote up
public void showRefreshDialog() {
    mContentView.pauseTimers();
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
            BrowserActivity.this);
    alertDialogBuilder.setTitle(getString(R.string.app_name));
    alertDialogBuilder
            .setCancelable(false)
            .setMessage(getString(R.string.refresh_msg))
            .setPositiveButton(R.string.action_ok,
                    (dialog, id) -> {
                        connector_info = WebViewManager.getDefaultPage(BrowserActivity.this, isKcBrowserMode);
                        if (manager != null && connector_info != null && connector_info.size() == 2) {
                            ((TextView) findViewById(R.id.kc_error_text)).setText("");
                            manager.openPage(mContentView, connector_info, isKcBrowserMode);
                        } else {
                            finish();
                        }
                    })
            .setNegativeButton(R.string.action_cancel,
                    (dialog, id) -> {
                        dialog.cancel();
                        mContentView.resumeTimers();
                    });
    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
}
 
Example 7
Source File: NetworkHelper.java    From YouTube-In-Background with MIT License 6 votes vote down vote up
public void createNetErrorDialog()
{
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setMessage("You need a network connection to use this application. Please turn on" +
            " mobile network or Wi-Fi in Settings.")
            .setTitle("Unable to connect")
            .setCancelable(false)
            .setPositiveButton("Settings",
                    (dialog, id) -> {
                        Intent i = new Intent(Settings.ACTION_SETTINGS);
                        activity.startActivity(i);
                    }
            )
            .setNegativeButton("Cancel",
                    (dialog, id) -> {
                        //activity.finish();
                    }
            );
    AlertDialog alert = builder.create();
    alert.show();
}
 
Example 8
Source File: MainActivity.java    From SimplicityBrowser with MIT License 6 votes vote down vote up
private void createFileName() {
    LayoutInflater inflater = getLayoutInflater();
    Bitmap resizedBitmap = Bitmap.createBitmap(favoriteIcon);
    @SuppressLint("InflateParams") View alertLayout = inflater.inflate(R.layout.layout_shortcut, null);
    shortcutNameEditText = alertLayout.findViewById(R.id.shortcut_name_edittext);
    AlertDialog alertDialog = createExitDialog();
    alertDialog.setTitle(R.string.add_home);
    alertDialog.setView(alertLayout);
    alertDialog.show();
    shortcutNameEditText.setHint(webViewTitle);
    ImageView imageShortcut = alertDialog.findViewById(R.id.fav_imageView);
    if (imageShortcut != null) {
        imageShortcut.setImageBitmap(StaticUtils.getCircleBitmap(resizedBitmap));
    }else{
        Log.d("Null", "");
    }
    alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(this, R.color.md_blue_600));
    alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(this, R.color.md_blue_600));
}
 
Example 9
Source File: GalleryPreviewsScene.java    From EhViewer with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onMenuItemClick(MenuItem item) {
    Context context = getContext2();
    if (null == context) {
        return false;
    }

    int id = item.getItemId();
    switch (id) {
        case R.id.action_go_to:
            if (mHelper == null) {
                return true;
            }
            int pages = mHelper.getPages();
            if (pages > 0 && mHelper.canGoTo()) {
                GoToDialogHelper helper = new GoToDialogHelper(pages, mHelper.getPageForTop());
                AlertDialog dialog = new AlertDialog.Builder(context).setTitle(R.string.go_to)
                        .setView(R.layout.dialog_go_to)
                        .setPositiveButton(android.R.string.ok, null)
                        .create();
                dialog.show();
                helper.setDialog(dialog);
            }
            return true;
    }
    return false;
}
 
Example 10
Source File: PostFragment.java    From hipda with GNU General Public License v2.0 5 votes vote down vote up
private void showRestoreContentDialog() {
    final Content[] contents = ContentDao.getSavedContents(mSessionId);

    if (contents == null || contents.length == 0) {
        UIUtils.toast("没有之前输入的内容");
        return;
    }

    final LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View viewlayout = inflater.inflate(R.layout.dialog_restore_content, null);
    final ListView listView = (ListView) viewlayout.findViewById(R.id.lv_contents);

    listView.setAdapter(new SavedContentsAdapter(getActivity(), 0, contents));

    final AlertDialog.Builder popDialog = new AlertDialog.Builder(getActivity());
    popDialog.setView(viewlayout);
    final AlertDialog dialog = popDialog.create();
    dialog.show();

    listView.setOnItemClickListener(new OnViewItemSingleClickListener() {
        @Override
        public void onItemSingleClick(AdapterView<?> adapterView, View view, int position, long row) {
            if (!TextUtils.isEmpty(mEtContent.getText()) && !mEtContent.getText().toString().endsWith("\n"))
                mEtContent.append("\n");
            mEtContent.append(contents[position].getContent());
            mEtContent.requestFocus();
            mEtContent.setSelection(mEtContent.getText().length());
            dialog.dismiss();
        }
    });

}
 
Example 11
Source File: AppAlertDialog.java    From hash-checker with Apache License 2.0 5 votes vote down vote up
public static void show(
        @NonNull Context context,
        int titleResId,
        int messageResId,
        int positiveButtonTextResId,
        @Nullable DialogInterface.OnClickListener positiveClickListener
) {
    AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AppAlertDialog)
            .setTitle(titleResId)
            .setMessage(messageResId)
            .setPositiveButton(
                    positiveButtonTextResId,
                    positiveClickListener
            )
            .setNegativeButton(
                    R.string.common_cancel,
                    (dialog, which) -> dialog.cancel()
            )
            .create();
    alertDialog.setOnShowListener(dialog -> {
        AlertDialog currentDialog = ((AlertDialog) dialog);

        int textColor = UIUtils.getAccentColor(context);
        currentDialog.getButton(
                DialogInterface.BUTTON_POSITIVE
        ).setTextColor(textColor);
        currentDialog.getButton(
                DialogInterface.BUTTON_NEGATIVE
        ).setTextColor(textColor);
    });
    alertDialog.show();
}
 
Example 12
Source File: DhikrFragment.java    From prayer-times-android with Apache License 2.0 5 votes vote down vote up
private void deleteDhikr() {
    AlertDialog dialog = new AlertDialog.Builder(getActivity()).create();
    dialog.setTitle(R.string.delete);
    dialog.setMessage(getString(R.string.delConfirmDhikr, mDhikrs.get(0).getTitle()));
    dialog.setCancelable(false);
    dialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.yes), (dialogInterface, i) -> mViewModel.deleteDhikr(mDhikrs.get(0)));
    dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.no), (dialogInterface, i) -> {
    });
    dialog.show();
}
 
Example 13
Source File: QiscusBaseChatActivity.java    From qiscus-sdk-android with Apache License 2.0 5 votes vote down vote up
protected void deleteComments(List<QiscusComment> selectedComments) {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this)
            .setMessage(getResources().getQuantityString(R.plurals.qiscus_delete_comments_confirmation,
                    selectedComments.size(), selectedComments.size()))
            .setNegativeButton(R.string.qiscus_cancel, (dialog, which) -> dialog.dismiss())
            .setCancelable(true);

    boolean ableToDeleteForEveryone = allMyComments(selectedComments);
    if (ableToDeleteForEveryone) {
        alertDialogBuilder.setNeutralButton(R.string.qiscus_delete_for_everyone, (dialog, which) -> {
            QiscusBaseChatFragment fragment = (QiscusBaseChatFragment) getSupportFragmentManager()
                    .findFragmentByTag(QiscusBaseChatFragment.class.getName());
            if (fragment != null) {
                fragment.deleteCommentsForEveryone(selectedComments);
            }
            dialog.dismiss();
        });
    }

    AlertDialog alertDialog = alertDialogBuilder.create();

    alertDialog.setOnShowListener(dialog -> {
        QiscusDeleteCommentConfig deleteConfig = chatConfig.getDeleteCommentConfig();
        alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(deleteConfig.getCancelButtonColor());
        if (ableToDeleteForEveryone) {
            alertDialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(deleteConfig.getDeleteForEveryoneButtonColor());
        }
    });

    alertDialog.show();
}
 
Example 14
Source File: PrivacyFragment.java    From zephyr with MIT License 5 votes vote down vote up
@Override
public void onDismiss(DialogInterface dialogInterface) {
    super.onDismiss(dialogInterface);

    if (privacyManager.havePrivacySettingsChanged() && getContext() != null) {
        AlertDialog alertDialog = new MaterialAlertDialogBuilder(getContext())
                .setTitle(R.string.menu_privacy_restart_app_title)
                .setMessage(getContext().getString(R.string.menu_privacy_restart_app_body))
                .setCancelable(false)
                .setPositiveButton(R.string.menu_privacy_restart_app_btn, (dialog, which) -> ApplicationUtils.restartApp(ZephyrApplication.getInstance()))
                .create();
        alertDialog.show();
    }
}
 
Example 15
Source File: MainActivity.java    From live-app-android with MIT License 5 votes vote down vote up
private void networkNotConnected() {
    AlertDialog alertDialog = new AlertDialog.Builder(this)
            .setNegativeButton(R.string.app_settings, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                    startActivity(intent);
                }
            })
            .setTitle(R.string.valid_publishable_key_required)
            .setMessage(R.string.check_your_network_connection)
            .create();
    alertDialog.show();
}
 
Example 16
Source File: BackupDialog.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
public static void showEnableBackupDialog(@NonNull Context context, @NonNull SwitchPreferenceCompat preference) {
  String[]    password = BackupUtil.generateBackupPassphrase();
  AlertDialog dialog   = new AlertDialog.Builder(context)
                                        .setTitle(R.string.BackupDialog_enable_local_backups)
                                        .setView(R.layout.backup_enable_dialog)
                                        .setPositiveButton(R.string.BackupDialog_enable_backups, null)
                                        .setNegativeButton(android.R.string.cancel, null)
                                        .create();

  dialog.setOnShowListener(created -> {
    Button button = ((AlertDialog) created).getButton(AlertDialog.BUTTON_POSITIVE);
    button.setOnClickListener(v -> {
      CheckBox confirmationCheckBox = dialog.findViewById(R.id.confirmation_check);
      if (confirmationCheckBox.isChecked()) {
        BackupPassphrase.set(context, Util.join(password, " "));
        TextSecurePreferences.setBackupEnabled(context, true);
        LocalBackupListener.schedule(context);

        preference.setChecked(true);
        created.dismiss();
      } else {
        Toast.makeText(context, R.string.BackupDialog_please_acknowledge_your_understanding_by_marking_the_confirmation_check_box, Toast.LENGTH_LONG).show();
      }
    });
  });

  dialog.show();

  CheckBox checkBox = dialog.findViewById(R.id.confirmation_check);
  TextView textView = dialog.findViewById(R.id.confirmation_text);

  ((TextView)dialog.findViewById(R.id.code_first)).setText(password[0]);
  ((TextView)dialog.findViewById(R.id.code_second)).setText(password[1]);
  ((TextView)dialog.findViewById(R.id.code_third)).setText(password[2]);

  ((TextView)dialog.findViewById(R.id.code_fourth)).setText(password[3]);
  ((TextView)dialog.findViewById(R.id.code_fifth)).setText(password[4]);
  ((TextView)dialog.findViewById(R.id.code_sixth)).setText(password[5]);

  textView.setOnClickListener(v -> checkBox.toggle());

  dialog.findViewById(R.id.number_table).setOnClickListener(v -> {
    ((ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE)).setPrimaryClip(ClipData.newPlainText("text", Util.join(password, " ")));
    Toast.makeText(context, R.string.BackupDialog_copied_to_clipboard, Toast.LENGTH_LONG).show();
  });


}
 
Example 17
Source File: QrReaderFragment.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void promtForEventWORegistrationMoreQr() {

    // IDENTIFICATION
    String message = getString(R.string.qr_id) + ":\n";
    if (eventUid != null) {
        message = message + eventUid + "\n\n";
    } else {
        message = message + getString(R.string.qr_no_data) + "\n\n";
    }

    // ATTRIBUTES
    message = message + getString(R.string.qr_data_values) + ":\n";

    if (eventData != null && !eventData.isEmpty()) {
        for (Trio<TrackedEntityDataValue, String, Boolean> attribute : eventData) {
            message = message + attribute.val1() + ":\n" + attribute.val0().value() + "\n\n";
        }
        message = message + "\n";
    } else {
        message = message + getString(R.string.qr_no_data) + "\n\n";
    }


    // READ MORE
    message = message + "\n\n" + getString(R.string.read_more_qr);

    AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.CustomDialog)
            .setTitle(getString(R.string.QR_SCANNER))
            .setMessage(message)
            .setPositiveButton(getString(R.string.action_accept), (dialog, which) -> {
                dialog.dismiss();
                mScannerView.resumeCameraPreview(this);
            })
            .setNegativeButton(getString(R.string.save_qr), (dialog, which) -> {
                presenter.downloadEventWORegistration();
                dialog.dismiss();
            });
    AlertDialog alertDialog = builder.create();
    alertDialog.setOnShowListener(dialogInterface -> {
        alertDialog.getButton(Dialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.colorPrimary));
        alertDialog.getButton(Dialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.colorPrimary));
    });
    alertDialog.show();
}
 
Example 18
Source File: MainActivity.java    From YouTube-In-Background with MIT License 4 votes vote down vote up
/**
 * Handles selected item from action bar
 *
 * @param item the selected item from the action bar
 * @return boolean
 */
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    Locale locale = getResources().getConfiguration().locale;

    //noinspection SimplifiableIfStatement
    switch (id) {
        case R.id.action_about:
            DateFormat monthFormat = new SimpleDateFormat("MMMM", locale);
            DateFormat yearFormat = new SimpleDateFormat("yyyy", locale);
            Date date = new Date();

            AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
            alertDialog.setTitle("Teocci");
            alertDialog.setIcon(R.mipmap.ic_launcher);
            alertDialog.setMessage(
                    "Dedicated to the person who gives me a reason to smile even on the dullest of days." + ".\n" +
                    "누리 고마워~ Thanks for been in my life." + "\n\n" +
                    "YiB v" + BuildConfig.VERSION_NAME + "\n\[email protected]\n\n" +
                            monthFormat.format(date) + " " + yearFormat.format(date) + ".\n"
            );
            alertDialog.setButton(
                    AlertDialog.BUTTON_NEUTRAL,
                    "OK",
                    (dialog, which) -> dialog.dismiss()
            );
            alertDialog.show();

            return true;
        case R.id.action_clear_list:
            YouTubeSqlDb.getInstance()
                    .videos(YouTubeSqlDb.VIDEOS_TYPE.RECENTLY_WATCHED)
                    .deleteAll();
            recentlyPlayedFragment.clearRecentlyPlayedList();
            return true;
        case R.id.action_remove_account:
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
            String chosenAccountName = sp.getString(ACCOUNT_NAME, null);

            if (chosenAccountName != null) {
                sp.edit().remove(ACCOUNT_NAME).apply();
            }
            return true;
        case R.id.action_search:
            item.expandActionView();
            return true;
    }

    return super.onOptionsItemSelected(item);
}
 
Example 19
Source File: DetailActionUtil.java    From geopackage-mapcache-android with MIT License 4 votes vote down vote up
/**
     * Open a copy GeoPackage dialog view
     * @param context Context for opening dialog
     * @param gpName GeoPackage name
     * @param listener Click listener to callback to the mapfragment
     */
    public void openCopyDialog(Context context, String gpName,
                                 final OnDialogButtonClickListener listener){
        // Create Alert window with basic input text layout
        LayoutInflater inflater = LayoutInflater.from(context);
        View alertView = inflater.inflate(R.layout.basic_edit_alert, null);
        // Logo and title
        ImageView alertLogo = (ImageView) alertView.findViewById(R.id.alert_logo);
        alertLogo.setBackgroundResource(R.drawable.material_copy);
        TextView titleText = (TextView) alertView.findViewById(R.id.alert_title);
        titleText.setText("Copy GeoPackage");

        final TextInputEditText inputName = (TextInputEditText) alertView.findViewById(R.id.edit_text_input);
        inputName.setText(gpName + context.getString(R.string.geopackage_copy_suffix));
        inputName.setHint("GeoPackage Name");

        AlertDialog.Builder copyDialogBuilder = new AlertDialog.Builder(context, R.style.AppCompatAlertDialogStyle)
                .setView(alertView)
                .setPositiveButton("Copy", (dialog, which)->{
                            String newName = inputName.getText().toString();
                            if (newName != null && !newName.isEmpty()
                                    && !newName.equals(gpName)) {
                                dialog.dismiss();
                                listener.onCopyGP(gpName, newName);
                            }
                })

                .setNegativeButton(context.getString(R.string.button_cancel_label),
                        (dialog, which)->{
                            dialog.dismiss();
                });
        AlertDialog alertDialog = copyDialogBuilder.create();

//        // Validate the input before allowing the rename to happen
//        inputName.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
//            @Override
//            public void afterTextChanged(Editable editable) {}
//
//            @Override
//            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//                String givenName = inputName.getText().toString();
//                alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
//
//                if(givenName.isEmpty()){
//                    inputName.setError("Name is required");
//                    alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
//                } else {
//                    boolean allowed = Pattern.matches("[a-zA-Z_0-9]+", givenName);
//                    if (!allowed) {
//                        inputName.setError("Names must be alphanumeric only");
//                        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
//                    }
//                }
//            }
//        });
        alertDialog.show();
    }
 
Example 20
Source File: MainActivity.java    From prayer-times-android with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    String lang = LocaleUtils.getLanguage("en", "de", "tr");
    final String file = lang + "/hadis.db";
    final String url = App.API_URL + "/files/hadis." + lang + ".db";
    File f = new File(App.get().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), file);
    
    
    if (f.exists()) {
        try {
            if (SqliteHelper.get().getCount() == 0) {
                SqliteHelper.get().close();
                ((Object) null).toString();
            }
        } catch (Exception e) {
            if (f.exists() && !f.delete()) {
                Log.e("BaseActivity", "could not delete " + f.getAbsolutePath());
            }
            finish();
        }
        setDefaultFragment(new HadithFragment());
        moveToFrag(getDefaultFragment());
    } else if (!App.isOnline()) {
        Toast.makeText(this, R.string.no_internet, Toast.LENGTH_SHORT).show();
    } else {
        AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setTitle(R.string.hadith);
        dialog.setMessage(getString(R.string.dlHadith));
        dialog.setCancelable(false);
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.yes), (dialogInterface, i) -> {

            File f1 = new File(App.get().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), file);


            if (!f1.getParentFile().mkdirs()) {
                Log.e("BaseActivity", "could not mkdirs " + f1.getParent());
            }
            final ProgressDialog dlg = new ProgressDialog(MainActivity.this);
            dlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dlg.setCancelable(false);
            dlg.setCanceledOnTouchOutside(false);
            dlg.show();
            Ion.with(MainActivity.this).load(url).progressDialog(dlg).write(f1).setCallback((e, result) -> {

                dlg.dismiss();
                if (e != null) {
                    e.printStackTrace();
                    Crashlytics.logException(e);
                    Toast.makeText(MainActivity.this, R.string.error, Toast.LENGTH_LONG).show();
                    finish();
                } else if (result.exists()) {
                    openHadithFrag();
                }
            });
        });
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.no), (dialogInterface, i) -> dialogInterface.cancel());
        dialog.show();
    }
    
}