I am showing my own AlertDialog. It works and shows fine in most cases but in when I call from the following activity it does not show on UI. The code executes completely with no exceptions, I have even checked my logs and with breakpoints, Did not find any issue. But the dialog does not appear on UI. Can anyone tell me what the problem might be?
This is the method in my activity that calls the dialog.
private void showCustomDialog(final int messageType,
final String titleString,
final String msgString,
final String specificMsgString,
final int positiveButtonString,
final int negativeButtonString,
final Runnable positiveButtonClickHandler,
final Runnable negativeButtonClickHandler) {
if (mDialog != null && mDialog.isShowing()) {
Log.d(TAG, "showCustomDialog: cannot display two dialogs at once.");
return;
}
runOnUiThread(() -> mDialog = DialogUtil.showDialog(this, mAlertDialogBuilder, 0, messageType, titleString, msgString,
specificMsgString, positiveButtonString, negativeButtonString, positiveButtonClickHandler, negativeButtonClickHandler));
}
DialogUtil.showDialog method:
public static AlertDialog showDialog(
Activity activity,
AlertDialog.Builder builder,
final int borderTopColorRes,
final int iconRes,
final String titleString,
final String msgString,
final String specificMsgString,
final int positiveButtonString,
final int negativeButtonString,
final Runnable positiveButtonClickHandler,
final Runnable negativeButtonClickHandler) {
final DialogCustomViewBinding binding = DataBindingUtil.inflate(LayoutInflater.from(activity), R.layout.dialog_custom_view, null, false);
binding.textSpecificMessage.setVisibility(View.GONE);
if (borderTopColorRes != 0) {
binding.viewBorderTop.setBackgroundColor(borderTopColorRes);
} else {
binding.viewBorderTop.setVisibility(View.GONE);
}
if (iconRes != 0) {
binding.imageCustomDialogMessageType.setImageResource(iconRes);
}
if (titleString != null) {
binding.textCustomDialogTitle.setText(titleString);
binding.textCustomDialogTitle.setVisibility(View.VISIBLE);
} else {
binding.textCustomDialogTitle.setText("");
binding.textCustomDialogTitle.setVisibility(View.GONE);
}
if (msgString != null) {
binding.textDialogMessage.setText(msgString);
binding.textDialogMessage.setVisibility(View.VISIBLE);
} else {
binding.textDialogMessage.setText("");
binding.textDialogMessage.setVisibility(View.GONE);
}
binding.textSpecificMessage.setVisibility(View.GONE);
if (specificMsgString != null) {
binding.textSpecificMessage.setText(specificMsgString);
binding.textDialogMessage.setOnClickListener(v -> {
if (binding.textSpecificMessage.getVisibility() == View.VISIBLE) {
binding.textSpecificMessage.setVisibility(View.GONE);
} else {
binding.textSpecificMessage.setVisibility(View.VISIBLE);
}
});
}
if (positiveButtonClickHandler != null) {
binding.buttonPositive.setText(positiveButtonString);
binding.buttonPositive.setOnClickListener(v -> positiveButtonClickHandler.run());
} else {
binding.buttonPositive.setVisibility(View.GONE);
}
if (negativeButtonClickHandler != null) {
binding.buttonNegative.setText(negativeButtonString);
binding.buttonNegative.setOnClickListener(v -> negativeButtonClickHandler.run());
} else {
binding.buttonNegative.setVisibility(View.GONE);
}
builder.setView(binding.getRoot());
AlertDialog dialog = builder.create();
try {
dialog.show();
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
return dialog;
} catch (Exception e) {
Log.e(TAG, "showDialog: Exception=" + e.getMessage());
e.printStackTrace();
}
return null;
}
Related
I have gone through many tutorials with API.AI But didn't get the exact solution. My requirement is simply:- user will send some command using voice or text and get that commands in my application and execute some method.
API.AI
Actions on Google
Tutorial of Google Assistant
First of all you need to train your model on API.AI to respond upon some text given to the model.
Some code with API.AI FYI:
//Initialize Service
private void initService(final LanguageConfig selectedLanguage) {
try {
final AIConfiguration.SupportedLanguages lang = AIConfiguration.SupportedLanguages.fromLanguageTag(selectedLanguage.getLanguageCode());
final AIConfiguration config = new AIConfiguration(selectedLanguage.getAccessToken(),
lang,
AIConfiguration.RecognitionEngine.System);
aiDataService = new AIDataService(this, config);
} catch (Exception e) {
e.printStackTrace();
}
}
//Send request method where you can put user typed text to get the result from API.AI
private void sendRequest(final String textToSend, final int flag) {
Log.w(TAG, "Sending" + textToSend);
final AsyncTask<String, Void, AIResponse> task = new AsyncTask<String, Void, AIResponse>() {
private AIError aiError;
#Override
protected void onPreExecute() {
super.onPreExecute();
showHideProgressBar(true);
if (mVoiceRecorder != null) {
mVoiceRecorder.pauseRecording();
}
}
#Override
protected AIResponse doInBackground(final String... params) {
final AIRequest request = new AIRequest();
String query = params[0];
String event = params[1];
if (!TextUtils.isEmpty(query))
request.setQuery(query);
if (!TextUtils.isEmpty(event)) {
request.setEvent(new AIEvent(event));
}
final String contextString = params[2];
RequestExtras requestExtras = null;
if (!TextUtils.isEmpty(contextString)) {
final List<AIContext> contexts = Collections.singletonList(new AIContext(contextString));
requestExtras = new RequestExtras(contexts, null);
}
try {
Log.i("API AI Request", "" + request.toString());
return aiDataService.request(request, requestExtras);
} catch (final AIServiceException e) {
aiError = new AIError(e);
return null;
}
}
#Override
protected void onPostExecute(final AIResponse response) {
showHideProgressBar(false);
speechSentStatus = false;
okSentStatus = false;
if (response != null) {
onResult(response, flag, textToSend);
} else {
onError(aiError);
}
}
};
if (flag == OPEN_COMPLAIN_CODE) {
task.execute("", Config.Events[0], Config.Events[0]);
} else if (flag == OPEN_DIAGNOSIS_CODE) {
task.execute("", Config.Events[1], Config.Events[1]);
} else if (flag == Constants.OPEN_MEDICATION_CODE) {
task.execute("", Config.Events[2], Config.Events[2]);
} else if (flag == Constants.OPEN_LABTEST_CODE) {
task.execute("", Config.Events[3], Config.Events[3]);
} else if (flag == Constants.COMPLAINTS_ADDED) {
task.execute("", Config.Events[0], Config.Events[0]);
} else if (flag == Constants.DIAGNOSIS_ADDED) {
task.execute("", Config.Events[1], Config.Events[1]);
} else {
task.execute(textToSend, null, "");
}
}
//Based on result you can handle the business logic
private void onResult(final AIResponse response, final int flag, final String textToSend) {
runOnUiThread(new Runnable() {
#Override
public void run() {
apiAiResponseCounter = apiAiResponseCounter + 1;
isLast = false;
final Result result = response.getResult();
Log.w(TAG, "" + result.getFulfillment().getSpeech());
if (flag == Constants.COMPLAINTS_ADDED) {
//method you want to execute on receiving certain text from model
send(textToSend.toLowerCase(), DONTTEXT);
} else if (flag == Constants.DIAGNOSIS_ADDED) {
send(textToSend.toLowerCase(), DONTTEXT);
} else {
String error = "";
final String speech = result.getFulfillment().getSpeech();
if (speech.contains("?")) {
if (!result.getAction().equalsIgnoreCase("input.unknown")) {
if (result.getAction().equalsIgnoreCase(Config.Actions[5]) && result.isActionIncomplete() == false) {
//DONOTHING
} else {
digiMessage(speech, YESNO);
}
} else {
digiMessage(speech, ChatMessageAdapter.OTHER_MESSAGE);
}
} else {
if (speech.equalsIgnoreCase("Please help me the intake duration of the medication")) {
digiMessage(speech, ChatMessageAdapter.DURATION);
} else if (speech.equalsIgnoreCase("Please provide the daily routine for the medication intake")) {
digiMessage(speech, ChatMessageAdapter.FREQUENCY);
} else {
digiMessage(speech, ChatMessageAdapter.OTHER_MESSAGE);
}
}
if (result.getAction().equalsIgnoreCase(Config.Actions[4]) || result.getAction().equalsIgnoreCase(Config.Actions[5])) {
if (result.isActionIncomplete() == true) {
playSpeech(speech);
} else {
speechBuffer = "";
speechBuffer = speech;
}
} else {
if (result.getAction().equalsIgnoreCase(Config.Actions[11])) {
isLast = true;
if (mVoiceRecorder != null) {
stopVoiceRecording();
}
} else {
playSpeech(speech);
}
}
}
}
});
if (flag == Constants.COMPLAINTS_ADDED || flag == Constants.DIAGNOSIS_ADDED) {
Log.w(TAG, "Skipped");
} else {
inflateUI(response.getResult());
}
}
I am working on a media player app. I'm using ExoPlayer library. I have a playlist of videos, and I want to download videos simultaneously. I done it by using available demo app of exoplayer library on GitHub. I want to show progress of each downloading in the UI. For this job I get help from DownloadNotificationUtil.buildProgressNotification method.
#Override
protected Notification getForegroundNotification(TaskState[] taskStates) {
float totalPercentage = 0;
int downloadTaskCount = 0;
boolean allDownloadPercentagesUnknown = true;
boolean haveDownloadedBytes = false;
boolean haveDownloadTasks = false;
boolean haveRemoveTasks = false;
Log.e(TAG,"size task state: "+taskStates.length);
for (TaskState taskState : taskStates) {
Log.e(TAG,"taskId= "+taskState.taskId);
if (taskState.state != TaskState.STATE_STARTED
&& taskState.state != TaskState.STATE_COMPLETED) {
continue;
}
if (taskState.action.isRemoveAction) {
haveRemoveTasks = true;
continue;
}
haveDownloadTasks = true;
if (taskState.downloadPercentage != C.PERCENTAGE_UNSET) {
allDownloadPercentagesUnknown = false;
totalPercentage += taskState.downloadPercentage;
}
haveDownloadedBytes |= taskState.downloadedBytes > 0;
downloadTaskCount++;
}
int progress = 0;
boolean indeterminate = true;
if (haveDownloadTasks) {
progress = (int) (totalPercentage / downloadTaskCount);
indeterminate = allDownloadPercentagesUnknown && haveDownloadedBytes;
Log.e(TAG,"notifi "+progress);
}
return DownloadNotificationUtil.buildProgressNotification(
this,
R.drawable.exo_icon_play,
DOWNLOAD_CHANNEL_ID,
null,
null,
taskStates);
}
Now,I can track the progress downloading. But I still have a problem. I can't understand which item is downloading to update it's progress bar in the UI. Is there a Identical id of each download to recognize it? For example Android Download Manager has a download ID for each downloading file. But I don't know , how to handle this problem.
This is MediaDownloadService:
public class MediaDownloadService extends DownloadService {
public static String TAG="MediaDownloadService";
private static final int FOREGROUND_NOTIFICATION_ID = 1;
public MediaDownloadService() {
super(
DOWNLOAD_NOTIFICATION_ID,
DEFAULT_FOREGROUND_NOTIFICATION_UPDATE_INTERVAL,
DOWNLOAD_CHANNEL_ID,
R.string.download_channel_name);
}
#Override
protected DownloadManager getDownloadManager() {
return ((MyApplication) getApplication()).getDownloadManager();
}
#Nullable
#Override
protected Scheduler getScheduler() {
return null;
}
#Override
protected Notification getForegroundNotification(TaskState[] taskStates) {
float totalPercentage = 0;
int downloadTaskCount = 0;
boolean allDownloadPercentagesUnknown = true;
boolean haveDownloadedBytes = false;
boolean haveDownloadTasks = false;
boolean haveRemoveTasks = false;
for (TaskState taskState : taskStates) {
if (taskState.state != TaskState.STATE_STARTED
&& taskState.state != TaskState.STATE_COMPLETED) {
continue;
}
if (taskState.action.isRemoveAction) {
haveRemoveTasks = true;
continue;
}
haveDownloadTasks = true;
if (taskState.downloadPercentage != C.PERCENTAGE_UNSET) {
allDownloadPercentagesUnknown = false;
totalPercentage += taskState.downloadPercentage;
}
haveDownloadedBytes |= taskState.downloadedBytes > 0;
downloadTaskCount++;
}
int progress = 0;
boolean indeterminate = true;
if (haveDownloadTasks) {
progress = (int) (totalPercentage / downloadTaskCount);
indeterminate = allDownloadPercentagesUnknown && haveDownloadedBytes;
Log.e(TAG,"notifi "+progress);
sendIntent(progress);
}
return DownloadNotificationUtil.buildProgressNotification(
this,
R.drawable.exo_icon_play,
DOWNLOAD_CHANNEL_ID,
null,
null,
taskStates);
}
private void sendIntent(int progress){
Intent intent = new Intent(ConstantUtil.MESSAGE_PROGRESS);
intent.putExtra("progress",progress);
LocalBroadcastManager.getInstance(MediaDownloadService.this).sendBroadcast(intent);
}
#Override
protected void onTaskStateChanged(TaskState taskState) {
if (taskState.action.isRemoveAction) {
return;
}
Notification notification = null;
if (taskState.state == TaskState.STATE_COMPLETED) {
Log.e(TAG,"STATE_COMPLETED");
notification =
DownloadNotificationUtil.buildDownloadCompletedNotification(
/* context= */ this,
R.drawable.exo_controls_play,
DOWNLOAD_CHANNEL_ID,
/* contentIntent= */ null,
Util.fromUtf8Bytes(taskState.action.data));
} else if (taskState.state == TaskState.STATE_FAILED) {
Log.e(TAG,"STATE_FAILED");
notification =
DownloadNotificationUtil.buildDownloadFailedNotification(
/* context= */ this,
R.drawable.exo_controls_play,
DOWNLOAD_CHANNEL_ID,
/* contentIntent= */ null,
Util.fromUtf8Bytes(taskState.action.data));
}
int notificationId = FOREGROUND_NOTIFICATION_ID + 1 + taskState.taskId;
NotificationUtil.setNotification(this, notificationId, notification);
}
}
This is DownloadTracker class:
public class DownloadTracker implements DownloadManager.Listener {
/** Listens for changes in the tracked downloads. */
public interface Listener {
/** Called when the tracked downloads changed. */
void onDownloadsChanged();
}
private static final String TAG = "DownloadTracker";
private final Context context;
private final DataSource.Factory dataSourceFactory;
private final TrackNameProvider trackNameProvider;
private final CopyOnWriteArraySet<Listener> listeners;
private Listener onDownloadsChanged;
private final HashMap<Uri, DownloadAction> trackedDownloadStates;
private final ActionFile actionFile;
private final Handler actionFileWriteHandler;
public DownloadTracker(
Context context,
DataSource.Factory dataSourceFactory,
File actionFile,
DownloadAction.Deserializer... deserializers) {
this.context = context.getApplicationContext();
this.dataSourceFactory = dataSourceFactory;
this.actionFile = new ActionFile(actionFile);
trackNameProvider = new DefaultTrackNameProvider(context.getResources());
listeners = new CopyOnWriteArraySet<>();
trackedDownloadStates = new HashMap<>();
HandlerThread actionFileWriteThread = new HandlerThread("DownloadTracker");
actionFileWriteThread.start();
actionFileWriteHandler = new Handler(actionFileWriteThread.getLooper());
loadTrackedActions(
deserializers.length > 0 ? deserializers : DownloadAction.getDefaultDeserializers());
}
public void addListener(Listener listener) {
listeners.add(listener);
}
public void removeListener(Listener listener) {
listeners.remove(listener);
}
public boolean isDownloaded(Uri uri) {
return trackedDownloadStates.containsKey(uri);
}
#SuppressWarnings("unchecked")
public List<StreamKey> getOfflineStreamKeys(Uri uri) {
if (!trackedDownloadStates.containsKey(uri)) {
return Collections.emptyList();
}
return trackedDownloadStates.get(uri).getKeys();
}
public int toggleDownload(Activity activity, String name, Uri uri, String extension) {
if (isDownloaded(uri)) {
Log.e(TAG,"isDownloaded");
DownloadAction removeAction =
getDownloadHelper(uri, extension).getRemoveAction(Util.getUtf8Bytes(name));
startServiceWithAction(removeAction);
return -1;
} else {
StartDownloadDialogHelper helper =
new StartDownloadDialogHelper(activity, getDownloadHelper(uri, extension), name);
helper.prepare();
return helper.getTaskId();
}
}
#Override
public void onInitialized(DownloadManager downloadManager) {
// Do nothing.
}
#Override
public void onTaskStateChanged(DownloadManager downloadManager, TaskState taskState) {
DownloadAction action = taskState.action;
Uri uri = action.uri;
if ((action.isRemoveAction && taskState.state == TaskState.STATE_COMPLETED)
|| (!action.isRemoveAction && taskState.state == TaskState.STATE_FAILED)) {
// A download has been removed, or has failed. Stop tracking it.
if (trackedDownloadStates.remove(uri) != null) {
handleTrackedDownloadStatesChanged();
}
}
}
#Override
public void onIdle(DownloadManager downloadManager) {
// Do nothing.
}
// Internal methods
private void loadTrackedActions(DownloadAction.Deserializer[] deserializers) {
try {
DownloadAction[] allActions = actionFile.load(deserializers);
for (DownloadAction action : allActions) {
trackedDownloadStates.put(action.uri, action);
}
} catch (IOException e) {
Log.e(TAG, "Failed to load tracked actions", e);
}
}
private void handleTrackedDownloadStatesChanged() {
for (Listener listener : listeners) {
listener.onDownloadsChanged();
}
final DownloadAction[] actions = trackedDownloadStates.values().toArray(new DownloadAction[0]);
Log.e(TAG,"actions: "+actions.toString());
actionFileWriteHandler.post(
() -> {
try {
actionFile.store(actions);
} catch (IOException e) {
Log.e(TAG, "Failed to store tracked actions", e);
}
});
}
private void startDownload(DownloadAction action) {
if (trackedDownloadStates.containsKey(action.uri)) {
// This content is already being downloaded. Do nothing.
Log.e(TAG,"download already exsit");
return;
}
trackedDownloadStates.put(action.uri, action);
handleTrackedDownloadStatesChanged();
startServiceWithAction(action);
}
private void startServiceWithAction(DownloadAction action) {
DownloadService.startWithAction(context, MediaDownloadService.class, action, false);
}
private DownloadHelper getDownloadHelper(Uri uri, String extension) {
int type = Util.inferContentType(uri, extension);
switch (type) {
case C.TYPE_DASH:
return new DashDownloadHelper(uri, dataSourceFactory);
case C.TYPE_SS:
return new SsDownloadHelper(uri, dataSourceFactory);
case C.TYPE_HLS:
return new HlsDownloadHelper(uri, dataSourceFactory);
case C.TYPE_OTHER:
return new ProgressiveDownloadHelper(uri);
default:
throw new IllegalStateException("Unsupported type: " + type);
}
}
private final class StartDownloadDialogHelper
implements DownloadHelper.Callback, DialogInterface.OnClickListener {
private final DownloadHelper downloadHelper;
private final String name;
private final AlertDialog.Builder builder;
private final View dialogView;
private final List<TrackKey> trackKeys;
private final ArrayAdapter<String> trackTitles;
private final ListView representationList;
private int taskId;
public StartDownloadDialogHelper(
Activity activity, DownloadHelper downloadHelper, String name) {
this.downloadHelper = downloadHelper;
this.name = name;
builder =
new AlertDialog.Builder(activity)
.setTitle(R.string.exo_download_description)
.setPositiveButton(android.R.string.ok, this)
.setNegativeButton(android.R.string.cancel, null);
// Inflate with the builder's context to ensure the correct style is used.
LayoutInflater dialogInflater = LayoutInflater.from(builder.getContext());
dialogView = dialogInflater.inflate(R.layout.start_download_dialog, null);
trackKeys = new ArrayList<>();
trackTitles =
new ArrayAdapter<>(
builder.getContext(), android.R.layout.simple_list_item_multiple_choice);
representationList = dialogView.findViewById(R.id.representation_list);
representationList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
representationList.setAdapter(trackTitles);
}
public void prepare() {
downloadHelper.prepare(this);
}
#Override
public void onPrepared(DownloadHelper helper) {
for (int i = 0; i < downloadHelper.getPeriodCount(); i++) {
TrackGroupArray trackGroups = downloadHelper.getTrackGroups(i);
for (int j = 0; j < trackGroups.length; j++) {
TrackGroup trackGroup = trackGroups.get(j);
for (int k = 0; k < trackGroup.length; k++) {
trackKeys.add(new TrackKey(i, j, k));
trackTitles.add(trackNameProvider.getTrackName(trackGroup.getFormat(k)));
}
}
}
if (!trackKeys.isEmpty()) {
builder.setView(dialogView);
}
builder.create().show();
}
#Override
public void onPrepareError(DownloadHelper helper, IOException e) {
Toast.makeText(
context.getApplicationContext(), R.string.download_start_error, Toast.LENGTH_LONG)
.show();
Log.e(TAG, "Failed to start download", e);
}
#Override
public void onClick(DialogInterface dialog, int which) {
ArrayList<TrackKey> selectedTrackKeys = new ArrayList<>();
for (int i = 0; i < representationList.getChildCount(); i++) {
if (representationList.isItemChecked(i)) {
selectedTrackKeys.add(trackKeys.get(i));
}
}
if (!selectedTrackKeys.isEmpty() || trackKeys.isEmpty()) {
// We have selected keys, or we're dealing with single stream content.
DownloadAction downloadAction =
downloadHelper.getDownloadAction(Util.getUtf8Bytes(name), selectedTrackKeys);
taskId=MyApplication.getInstance().getDownloadManager().handleAction(downloadAction);
startDownload(downloadAction);
}
}
}
}
In my Fragment/Activity:
/* this method will be called when user click on download button of each item */
#Override
public void onDownloadClick(LectureList lecture) {
Log.e(TAG,"onClickDownload");
downloadTracker.toggleDownload(this,lecture.getTitle_lecture(),
Uri.parse(lecture.getUrlPath()),lecture.getExtension());
}
And here is my broadcast receiver:
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG,"onRecive download");
if(intent.getAction().equals(MESSAGE_PROGRESS)){
int progress=intent.getLongExtra("progress",0);
}
}
};
In the getForegroundNotification() method, you will get list of TaskState objects, which has a members downloadPercentage and your download Uri taskState.action.uri which is unique for each download task. Store these variables into a map and broadcast the map.
override fun getForegroundNotification(taskStates: Array<TaskState>): Notification {
var totalPercentage = 0f
var downloadTaskCount = 0
var progressMap : HashMap<Uri, Int> = HashMap()
for (taskState in taskStates) {
if (taskState.state != TaskState.STATE_STARTED && taskState.state != TaskState.STATE_COMPLETED) {
continue
}
if (taskState.action.isRemoveAction) {
continue
}
if (taskState.downloadPercentage != C.PERCENTAGE_UNSET.toFloat()) {
totalPercentage += taskState.downloadPercentage
progressMap.put(taskState.action.uri, taskState.downloadPercentage.toInt())
}
downloadTaskCount++
}
var progress = 0
progress = (totalPercentage / downloadTaskCount).toInt()
broadcastIndividualProgress(progressMap)
return buildProgressNotification(progress)
}
Im taking presets fields from the database and display them in ListView using PresetsListAdapter.
Coded as below:
public class BasicAcActivity extends Activity implements OnCheckedChangeListener {
private static final String TAG = BasicAcActivity.class.getName();
public static volatile PresetsListAdapter presetsListAdapter;
public static volatile SwitchCompat basicEQToggle;
private ListView mListView;
private FlipBeatsDataManager mDataManager;
private PresetsManager mPrstManager;
private SharedPreferences mShrdPrefs;
private SharedPreferences mShrdPrefPresets;
private TextView tvPresets;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_eq_settings);
initialize();
String text = Utilities.getResourceValue(this, R.string.equalizer_presets);
tvPresets.setText(text);
// Get presets
List<Preset> presets = generatePresets();
if (presets != null && presets.size() > 0)
{
for (Preset preset : presets)
{
mDataManager.createPreset(preset);
}
}
List<Preset> dbPresets = mDataManager.getMandotoryPresets();
presetsListAdapter = new PresetsListAdapter(this, dbPresets);
basicEQToggle.setChecked(true);
mListView.setAdapter(presetsListAdapter);
String onOrOff = mShrdPrefPresets.getString("Presets", "on");
if (onOrOff.equalsIgnoreCase("on"))
{
basicEQToggle.setChecked(true);
}
else
{
basicEQToggle.setChecked(false);
}
basicEQToggle.setOnCheckedChangeListener(this);
}
private void initialize()
{
tvPresets = (TextView) findViewById(R.id.lbl_presets);
mListView = (ListView) findViewById(R.id.presets_list);
basicEQToggle = (SwitchCompat) findViewById(R.id.basic_eq_toggle);
tvPresets.setTypeface(CommonUtils.getTfRobotoRegFont());
mPrstManager = PresetsManager.getInstance(getApplicationContext());
mDataManager = FlipBeatsDataManager.getInstance(getApplicationContext());
mShrdPrefs = getApplicationContext().getSharedPreferences("Prefs", Context.MODE_PRIVATE);
mShrdPrefPresets = getApplicationContext().getSharedPreferences("Preset", Context.MODE_PRIVATE);
}
private List<Preset> generatePresets()
{
// Default value is set if 'equalizer' is null
short bands = 5;
if (PlayerService.sEqualizer != null)
{
try
{
bands = PlayerService.sEqualizer.getNumberOfBands();
}
catch (Exception | Error e)
{
Log.w(TAG, "-- createPresets " + e.getMessage());
}
}
// Create Preset Based on the Bands Level
return mPrstManager.createPresets(bands);
}
#Override
protected void onResume()
{
super.onResume();
setLastUsedType();
boolean isSelected = mDataManager.findMandatoryPresetSelected();
if (!isSelected)
{
int preselect = mDataManager.getLastSelectedPresetId();
mDataManager.updateSelectedToPro1(preselect);
}
presetsListAdapter.notifyDataSetChanged();
Activity actv = getParent();
if (actv != null && actv instanceof AudioConfigurationActivity)
{
AudioConfigurationActivity parent = (AudioConfigurationActivity) actv;
// Sets default advance settings.
parent.setDefaultAdvanceSettings();
parent.setThroughBasicActivity();
}
setDefaultAdvancedSettings();
}
#Override
public boolean onKeyUp(int keyCode, #NonNull KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
{
if (SoundHealth.getSoundHealth(this))
{
Message.alertMsg(this, Utilities.getResourceValue(this, R.string.sound_health),
Utilities.getResourceValue(this, R.string.sound_health_msg));
}
return true;
}
return super.onKeyUp(keyCode, event);
}
#Override
public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked)
{
if (isChecked)
{
basicEQToggle.setSelected(true);
if (PlayerService.sEqualizer != null)
{
try
{
PlayerService.sEqualizer.setEnabled(true);
}
catch (Exception | Error e)
{
Log.w(TAG, "-- onCheckedChanged " + e.getMessage());
}
}
getApplicationContext();
mShrdPrefPresets.edit().putString("Presets", "on").apply();
if (BasicAcActivity.presetsListAdapter != null)
{
BasicAcActivity.presetsListAdapter.mPresets = mDataManager.getMandotoryPresets();
}
presetsListAdapter.notifyDataSetChanged();
}
else
{
basicEQToggle.setSelected(false);
if (PlayerService.sEqualizer != null)
{
try
{
PlayerService.sEqualizer.setEnabled(false);
}
catch (Exception | Error e)
{
Log.w(TAG, "-- onCheckedChanged " + e.getMessage());
}
}
if (BasicAcActivity.presetsListAdapter != null)
{
BasicAcActivity.presetsListAdapter.setPreset(14);
}
mShrdPrefPresets.edit().putString("Presets", "off").commit();
if (BasicAcActivity.presetsListAdapter != null)
{
BasicAcActivity.presetsListAdapter.mPresets = mDataManager.getMandotoryPresets();
}
presetsListAdapter.notifyDataSetChanged();
}
}
private void setLastUsedType()
{
mShrdPrefs.edit().putString(AudioConfigurationActivity.AU_SET_TYPE_KEY,
AudioConfigurationActivity.AU_SET_TYPE_BASIC);
}
/*
* Sets default advanced sound settings
*/
private void setDefaultAdvancedSettings()
{
try
{
if (PlayerService.sAudioDefaultValues != null)
{
AudioDefaultValues def = PlayerService.sAudioDefaultValues;
PlayerService.sBaseBooster.setStrength(def.getBassBoost());
PlayerService.sSurroundSound.setStrength(def.getSurroundSound());
PlayerService.sPresetReverb.setPreset(def.getRoomSize());
/** EnvironmentalReverb attributes */
PlayerService.sEnvironmentalReverb.setDecayHFRatio(def.getDecayHfRatio());
PlayerService.sEnvironmentalReverb.setDecayTime(def.getDecayTime());
PlayerService.sEnvironmentalReverb.setDensity(def.getDensity());
PlayerService.sEnvironmentalReverb.setDiffusion(def.getDiffusion());
PlayerService.sEnvironmentalReverb.setReflectionsDelay(def.getReflectionsDelay());
PlayerService.sEnvironmentalReverb.setReflectionsLevel(def.getReflectionsLevel());
PlayerService.sEnvironmentalReverb.setReverbDelay(def.getReverbDelay());
PlayerService.sEnvironmentalReverb.setReverbLevel(def.getReverbLevel());
PlayerService.sEnvironmentalReverb.setRoomHFLevel(def.getRoomHfLevel());
PlayerService.sEnvironmentalReverb.setRoomLevel(def.getRoomLevel());
}
}
catch (Exception e)
{
Log.w(TAG, "--- setDefaultAdvancedSettings, " + e.getMessage());
}
}
}
Adapter class :
abstract class BeatsBaseAdapter extends BaseAdapter {
final ThemeManager mThemeManager;
Context mContext;
Activity mActivity;
ImageLoader mImageLoader;
int mCategory;
FlipBeatsDataManager mDataManager;
int txtColorNumber;
int colorPrimaryText;
int colorSecondaryText;
int colorListBg;
int seperatorBg;
int listDrawbleBg;
int flipCardBg;
int dashboardCardBg;
/**
* Base Constructor
*
* #param context Application Context
*/
FlipBeatsBaseAdapter(Context context) {
mContext = context;
mDataManager = FlipBeatsDataManager.getInstance(mContext);
int sysThemeId = ThemeUtils.getTheme(mContext);
mThemeManager = ThemeManager.getInstance(mContext, sysThemeId);
}
/**
* Base Constructor
*
* #param activity Current Activity
*/
FlipBeatsBaseAdapter(Activity activity) {
if (activity != null) {
mContext = activity.getApplicationContext();
mActivity = activity;
mDataManager = FlipBeatsDataManager.getInstance(mContext);
int sysThemeId = ThemeUtils.getTheme(mContext);
mThemeManager = ThemeManager.getInstance(mContext, sysThemeId);
if (FlipBeatsGlobals.isBlackEditionActive) {
txtColorNumber = mContext.getResources().getColor(R.color.color_app_txt_numbers_dark);
colorPrimaryText = mContext.getResources().getColor(R.color.color_app_text_color_dark);
colorSecondaryText = mContext.getResources().getColor(R.color.color_app_secondary_text_color_dark);
colorListBg = mContext.getResources().getColor(R.color.color_black);
seperatorBg = mContext.getResources().getColor(R.color.color_app_disable_color_dark);
listDrawbleBg = R.drawable.list_front_bg_dark;
flipCardBg = mContext.getResources().getColor(R.color.color_frame_menu_dark);
dashboardCardBg = mContext.getResources().getColor(R.color.color_app_txt_disable_dark);
} else {
txtColorNumber = mContext.getResources().getColor(R.color.color_app_txt_numbers);
colorPrimaryText = mContext.getResources().getColor(R.color.color_app_text_color);
colorSecondaryText = mContext.getResources().getColor(R.color.color_app_secondary_text_color);
colorListBg = mContext.getResources().getColor(R.color.color_white);
seperatorBg = mContext.getResources().getColor(R.color.color_app_disable_color);
listDrawbleBg = R.drawable.list_front_bg;
flipCardBg = mContext.getResources().getColor(R.color.color_frame_menu);
dashboardCardBg = mContext.getResources().getColor(R.color.color_app_txt_disable);
}
} else {
mThemeManager = null;
}
}
}
This works fine until API level 25 but for Android Oreo version the ListView is not displayed, each item is only displayed when it is selected. What is possibly gone wrong here?
Thanks in advance.
Edit: actually the colorListBg is not setting for those devices. that's why the list is not displayed as the text color is set to white color
Sorry I know this question has been asked several time and has lots of answer but none of them solved my problem.
I'm calling web service and showing dialog, which is working ok. But I'm unable to dismiss the progressDialog. Although the same method is working inside fragment but this time I'm using it in Activity. Please point me where I'm making the mistake.
public void signupServiceResponse(String phNum,String password){
progressDialog = createProgressDialog(this, false);
//progressDialog.show();
final ContentServiceCall request = ServiceGenerator.createService(ContentServiceCall.class, "Empty");
final Call<UserServiceResponse> call = request.signUp(Constants.WS_VERSION,Constants.LOCAL_EN,Constants.PLATFORM, phNum,password);
call.enqueue(new Callback<UserServiceResponse>() {
#Override
public void onResponse(Call<UserServiceResponse> call, final Response<UserServiceResponse> response) {
if(response!=null && response.isSuccessful())
{
if(response.body()!=null && response.body().getResponse()!=null)
{
if(response.body().getResponse().getResponseCode()== Constants.RESPONSE_CODE_SUCCESS) {
if(response.body().getUser() != null && response.body().getUserSubscription()!= null && response.body().getUserSubscription() !=null) {
userEntity = response.body().getUser();
userProfileEntity = response.body().getUserProfile();
userSubscriptionEntity = response.body().getUserSubscription();
//insert in user table
int tableCode = 1; //table code 1 for user table
dbHelper.insertUserRegistration(userEntity, userProfileEntity, userSubscriptionEntity, tableCode);
dbHelper.close();
progressDialog.dismiss();
Intent i = new Intent(RegistrationActivity.this, ActivateAccountActivity.class);
startActivity(i);
}
} else if((response.body().getResponse().getResponseCode()== Constants.USERAlREADYEXIST_RESPONSE_CODE_SUCCESS)) {
// in case user data is cleared or app is reinstalled
boolean userCount = dbHelper.getUserCount();
if (userCount) {
Intent i = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(i);
} else if(!userCount){
// if user exist and data is cleared
userEntity = response.body().getUser();
userProfileEntity = response.body().getUserProfile();
userSubscriptionEntity = response.body().getUserSubscription();
int tableCode = 1;
dbHelper.insertUserRegistration(userEntity, userProfileEntity, userSubscriptionEntity, tableCode);
dbHelper.close();
}
} else if((response.body().getResponse().getResponseCode()== Constants.RESPONSE_CODE_PASSWORD_INCORRECT)){
Toast.makeText(RegistrationActivity.this,"Password incorrect",Toast.LENGTH_LONG).show();
btnForgetPassword.setVisibility(View.VISIBLE);
progressDialog.dismiss();
}
else {
}
}
else {
// leave it
}
}
else
{
// Display proper message
//Toast.makeText(getActivity(),getString(R.string.error_webservice_response),Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
#Override
public void onFailure(Call<UserServiceResponse> call, Throwable t) {
Log.e("Fail", "Failure");
Log.e("ERROR", t.getMessage());
progressDialog.dismiss();
Toast.makeText(RegistrationActivity.this,getString(R.string.error_internet_connectivity),Toast.LENGTH_LONG).show();
}
});
}
public ProgressDialog createProgressDialog(Context mContext, Boolean cancelable) {
final ProgressDialog dialog = new ProgressDialog(mContext);
try {
dialog.show();
} catch (WindowManager.BadTokenException e) {
}
dialog.setCancelable(cancelable);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog);
return dialog;
}
Make your dialog a global variable and initialize it in the onCreate() (If you're inside an Activity).
dialog = new ProgressDialog(mContext);
Add this method.
public ProgressDialog dismiss() {
if(dialog != null) {
dialog.dismiss();
}
}
Finally, instead of calling progressDialog.dismiss() simply call dismiss().
You have to check /write like this.
if(progressDialog!=null &&
progressDialog.isshowing){
progressDialog.dismiss();
}
I am using and it is working.
I know that the purpose of the AsyncTask is to run asynchronously with other tasks of the app and finish in the background, but apparently I need to do this, I need to start an activity from AsyncTask and since I cant extend an activity in this class I can not use startactivityforresult, so how can I wait till my activity finishes?
Here is my code:
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
public AsyncResponse delegate = null;
private static final String TAG = "ListSpdFiles: ";
Context applicationContext;
ContentResolver spdappliationcontext;
public final CountDownLatch setSignal= new CountDownLatch(1);
private final ReentrantLock lock = new ReentrantLock();
String username = "";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private boolean createbutt;
private boolean deletebutt;
private String initiator;
private String path;
private String pass;
private String url;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private String CurrentURL = null;
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(boolean createbutt, boolean deletebutt, String url, String pass, Context context, String initiator, String path, AsyncResponse asyncResponse) {
this.initiator = initiator;
this.path = path;
this.pass= pass;
this.url= url;
this.createbutt= createbutt;
this.deletebutt=deletebutt;
applicationContext = context.getApplicationContext();
spdappliationcontext = context.getContentResolver();
delegate = asyncResponse;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(applicationContext, pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
CurrentURL = getLastAccessedBrowserPage();
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
}
term();
delegate.processFinish(username);
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
boolean crtbut = createbutt;
boolean dlbut= deletebutt;
ArrayList<String> mylist = new ArrayList<String>();
final Global globalVariable = (Global) applicationContext;
if (crtbut==false && dlbut == false){
if ( globalVariable.getPasswordButt()==false ) {
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
Log.i(TAG, "current url: " + CurrentURL);
if (Arrays.toString(result.getValue().toArray(new String[0])).contains(CurrentURL)) {
String sharareh = Arrays.toString(result.getValue().toArray(new String[0]));
String[] items = sharareh.split(", ");
for (String item : items) {
String trimmed;
if (item.startsWith("[" + CurrentURL + ".")) {
trimmed = item.replace("[" + CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
} else if (item.startsWith(CurrentURL + ".")) {
trimmed = item.replace(CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
}
}
}
globalVariable.setPopupdone(false);
Intent i = new Intent(applicationContext, PopUp.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("EXTRA_SESSION_ID", mylist);
applicationContext.startActivity(i);
username = globalVariable.getUsername();
}
else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = spdappliationcontext.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
My Activity class:
public class PopUp extends Activity {
private static final String TAG = "PopUp";
ArrayList<String> value = null;
ArrayList<String> usernames;
#Override
protected void onCreate(Bundle savedInstanceState) {
final Global globalVariable = (Global) getApplicationContext();
globalVariable.setUsername("");
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getStringArrayList("EXTRA_SESSION_ID");
}
usernames = value;
super.onCreate(savedInstanceState);
setContentView(R.layout.popupactivity);
final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button btnSelect = (Button) popupView.findViewById(R.id.select);
Spinner popupSpinner = (Spinner) popupView.findViewById(R.id.popupspinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PopUp.this, android.R.layout.simple_spinner_item, usernames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
popupSpinner.setAdapter(adapter);
popupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
globalVariable.setUsername(usernames.get(arg2));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnSelect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
globalVariable.setPopupdone(true);
popupWindow.dismiss();
finish();
}
}
);
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.poupup_menu, menu);
return true;
}}