Variable that is never used - java

I have this block of code where my app, supposedly, when the user inserts a right password and a right email, goes to the main activity, although when I used the run method, it says that the variable is never used.
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
public void run() {
startActivity(new Intent(getBaseContext(), Second.class));
finish();
}
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}

It is because you have incorrect code in your method. Take a look at the following code:
#Override
protected void onPostExecute(final Boolean success) {
...
if (success) {
public void run() {
...
}
finish();
} else {
...
}
}
You have a block of method named run() which is incorrect. So, you need to remove it. Your code should be something like this then:
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
startActivity(new Intent(getBaseContext(), Second.class));
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}

Related

setOnUtteranceProgressListener not at all working for Text To Speech for API > 21

I want setOnUtteranceProgressListener should notify a Toast after the speech is completed.It seems not working.
I have used setOnUtteranceProgressListener and on the speak function i have mentioned the paramaters as follows..
Bundle params = new Bundle();
params.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, MainActivity.this.getPackageName());
I have given a "UniqueId" while calling speak function as follows.
myTTS.speak(message,TextToSpeech.QUEUE_FLUSH,params,"UniqueId");
In My program after the text to speech engine finishes speaking it should run a Toast notifying that it has finished speaking.But the setOnUtteranceProgressListner seems not working.
myTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(String utteranceId) {
Toast.makeText(MainActivity.this,"Finished speaking.",Toast.LENGTH_LONG).show();
}
#Override
public void onError(String utteranceId) {
}
});
The all Code is as follows..
public class MainActivity extends AppCompatActivity {
String message;
private TextToSpeech myTTS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(myTTS.getEngines().size() == 0){
Toast.makeText(MainActivity.this,"No Engines Installed",Toast.LENGTH_LONG).show();
}else{
myTTS.setLanguage(Locale.US);
if (status == TextToSpeech.SUCCESS){
//Toast.makeText(MainActivity.this,"Status working.",Toast.LENGTH_LONG).show();
message = "How may i help you.";
}
}
}
});
myTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(String utteranceId) {
Toast.makeText(MainActivity.this,"onDone working.",Toast.LENGTH_LONG).show();
}
#Override
public void onError(String utteranceId) {
}
});
}
Please give a solution for this.
The main problems are:
1) Setting the progress listener before the tts is initialized.
2) Trying to make a Toast from a background thread.
I also have some other suggested changes but they are not required:
public class MainActivity extends AppCompatActivity {
String message = "How may I help you?";
String mostRecentUtteranceID;
private TextToSpeech myTTS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(myTTS.getEngines().size() == 0){
Toast.makeText(MainActivity.this,"No Engines Installed",Toast.LENGTH_LONG).show();
}else{
if (status == TextToSpeech.SUCCESS){
ttsInitialized();
}
}
}
});
}
private void ttsInitialized() {
// *** set UtteranceProgressListener AFTER tts is initialized ***
myTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
// this method will always called from a background thread.
public void onDone(String utteranceId) {
// only respond to the most recent utterance
if (!utteranceId.equals(mostRecentUtteranceID)) {
Log.i("XXX", "onDone() blocked: utterance ID mismatch.");
return;
} // else continue...
boolean wasCalledFromBackgroundThread = (Thread.currentThread().getId() != 1);
Log.i("XXX", "was onDone() called on a background thread? : " + wasCalledFromBackgroundThread);
Log.i("XXX", "onDone working.");
// for demonstration only... avoid references to
// MainActivity (unless you use a WeakReference)
// inside the onDone() method, as it
// can cause a memory leak.
runOnUiThread(new Runnable() {
#Override
public void run() {
// *** toast will not work if called from a background thread ***
Toast.makeText(MainActivity.this,"onDone working.",Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onError(String utteranceId) {
}
});
// set Language
myTTS.setLanguage(Locale.US);
// set unique utterance ID for each utterance
mostRecentUtteranceID = (new Random().nextInt() % 9999999) + ""; // "" is String force
// set params
// *** this method will work for more devices: API 19+ ***
HashMap<String, String> params = new HashMap<>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, mostRecentUtteranceID);
myTTS.speak(message,TextToSpeech.QUEUE_FLUSH,params);
}
}
If you want to add the call back OnUtteranceProgressListener you have to implement the speak method like this:
myTTS.speak(message,TextToSpeech.QUEUE_FLUSH, null , TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID);
Then it will call the methods that you've already implemented (onStart, onDone, etc)

Stop/start mediaplayer from another activity

i'm trying to play stream radio using Mediaplayer with MP1 as variable of Mediaplayer i want to play it in all Fragments app,expect one activity (ActivityOne) which is contains another Mediaplayer MP2 to play,so i want to stop MP1 when i'm in (ActivityOne) activity, and play MP2 , and when i return from (ActivityOne) i want to resume MP1, my big problem is the (ActivityOne) called when i click button which is exist in fragment
my code below works only in one direction :
when i return from (ActivityOne) activity, the music stops.
structure of the app : MainAcitivty > Fragment > ActivityOne
MainActivity.java
MediaPlayer MP1;
boolean prepared = false;
boolean started = false;
PlayerTask playerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = new MediaPlayer();
playerTask = new PlayerTask();
playerTask.execute(stream);
/**/
MusicButton = findViewById(R.id.toggleButton);
MusicButton.setVisibility(View.INVISIBLE);
MusicButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (started && MusicButton.isChecked()) {
started = false;
MP1.pause();
MusicButton.setChecked(true);
} else {
started = true;
MP1.start();
MusicButton.setChecked(false);
}
}
});
}
#SuppressLint("StaticFieldLeak")
public class PlayerTask extends AsyncTask<String, Void, Boolean> {
ProgressBar loadingRL = findViewById(R.id.progressBar);
#Override
protected void onPreExecute() {
super.onPreExecute();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attribs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
MP1.setAudioAttributes(attribs);
} else {
MP1.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
loadingRL.setVisibility(View.VISIBLE);
}
#Override
protected Boolean doInBackground(String... strings) {
try {
MP1.setDataSource(strings[0]);
MP1.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
MP1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer MP1) {
MP1.start();
}
});
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
MusicButton.setVisibility(View.VISIBLE);
MusicButton.setChecked(true);
loadingRL.setVisibility(View.VISIBLE);
}
ActivityOne.java
MediaPlayer MP2;
boolean prepared = false;
boolean started = false;
ToggleButton music;
PlayerTask playerTask = null;
CoordinatorLayout coordinatorLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop_for_ringtone);
coordinatorLayout = findViewById(R.id.coord);
MP2 = new MediaPlayer();
playerTask = new PlayerTask();
playerTask.execute(url);
}
#SuppressLint("StaticFieldLeak")
public class PlayerTask extends AsyncTask<String, Void, Boolean> {
ProgressBar pb = findViewById(R.id.progress);
#Override
protected void onPreExecute() {
super.onPreExecute();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attribs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
MP2.setAudioAttributes(attribs);
} else {
MP2.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
}
#Override
protected Boolean doInBackground(String... strings) {
if (!isCancelled()) {
try {
MP2.setDataSource(strings[0]);
MP2.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
MP2.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer MP2) {
MP2.start();
}
});
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
music.setEnabled(true);
music.setVisibility(View.VISIBLE);
music.setChecked(true);
all.setVisibility(View.VISIBLE);
}
#Override
protected void onCancelled(Boolean aBoolean) {
if (isCancelled() && MP2.isPlaying()) {
MP2.stop();
}
}
}
#Override
public void onBackPressed() {
if (playerTask != null && playerTask.getStatus() == AsyncTask.Status.FINISHED) {
if (MP2.isPlaying()) {
MP2.stop();
}
} else if (playerTask != null && playerTask.getStatus() != AsyncTask.Status.FINISHED) {
playerTask.cancel(true);
}
super.onBackPressed();
}
i spent 2 days to resolve this problem without any result ,please someone help me i will be thankful to him
You could solve this by using Otto library. First create a new Java class but choose enum instead and inside enum you can add: PLAY and PAUSE for example:
public enum PlaybackEvent {
PLAY, PAUSE
}
Then if you are not using custom Application class create one and extend Application and override inside onCreate method. Inside your app gradle add compile 'com.squareup:otto:1.3.8' then create an instance of Bus inside Application class and register. For example this would look like this:
public class MApplication extends Application {
public static Bus sBus = new Bus(ThreadEnforcer.MAIN);
#Override
public void onCreate() {
super.onCreate();
sBus.register(this);
}
Don't forget to replace in manifest default application class with your new one
<application
android:name="com.packagename.MApplication"
After that in your MainActivity class override and register/unregister your event bus in onResume and in onPause.
#Override
protected void onResume() {
super.onResume();
try {
MApplication.sBus.register(this);
}
catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
MApplication.sBus.unregister(this);
}
catch(Exception e){
e.printStackTrace();
}
}
After that in MainActivity create a public void method passing as parameter PlayBackEvent and Subscribe so you can listen a message which will be send from your fragment class. For example:
#Subscribe
public void handlePlaybackEvent(PlaybackEvent event) {
switch (event) {
case PLAY:
if(MP1.isPlaying())
MP1.pause();
break;
case PAUSE:
if(!MP1.isPlaying())
MP1.play();
break;
}
}
And last thing you have to do is to send the message from your fragment when starting second activity and that will go:
MApplication.sBus.post(PlaybackEvent.PAUSE);
and of course you can also send a message to play again MP1 from second activity overriding onBackPressed putting inside line of code:
MApplication.sBus.post(PlaybackEvent.PLAY);
Hope this will help you to resolve the problem.
Have you tried using startActivityForResult()?

UtteranceProgressListener not being Called even after passing hashmap String(read before flagging as duplicate)

I'm trying to put an onUtteranceProgressListener on tts. I've gone through other relevant questions on stackoverflow and followed them. But even after passing utterance id string through Hashmap or Bundle(Since Hashmap is deprecated after api21), utteranceProgressListener isn't getting called. I've used toasts to verify, but there were no toast outputs. I'm getting the audio output, but unable to get the progressListener work on it.
#Override
public void onInit(int initStatus) {
if (initStatus == TextToSpeech.SUCCESS) {
myTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
Toast.makeText(InvisibleActivity.this,"listener Started",Toast.LENGTH_SHORT).show();
}
#Override
public void onDone(String utteranceId) {
if (utteranceId.equals("utteranceId")) {
myTTS.stop();
Toast.makeText(InvisibleActivity.this,"mytts stopped",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onError(String utteranceId) {
}
});
myTTS.setLanguage(Locale.US);
} else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry,Text To speech not supported", Toast.LENGTH_SHORT).show();
}
Bundle bundle = new Bundle();
bundle.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"utteranceId");
myTTS.speak(outText, TextToSpeech.QUEUE_FLUSH, bundle,null);
chan();
}
The Hashmap Code (with deprecated speak()) I've used, is:
HashMap<String,String> params = new HashMap<>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"utteranceId");
myTTS.speak(outText,TextToSpeech.QUEUE_FLUSH, params);
I've tried both QUEUE_ADD and QUEUE_FLUSH but the result is the same.
This is because it works on another thread.
You need to use the runOnUiThread to make it work:
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String s) {
final String keyword = s;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Started " + keyword, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onDone(String s) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Done ", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onError(String s) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Error ", Toast.LENGTH_SHORT).show();
}
});
}
});
Make sure that this method is called before the speak method.

How to use AsyncTask method outside

I am checking server available or not with AsyncTask class and its working fine with below code
class AsyncServerOnlineCheck extends AsyncTask {
boolean isReachable;
#Override
protected Object doInBackground(Object[] objects) {
isReachable = NetworkCheck.isReachable(SplashsActivity.this);
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
if (isReachable) {
new DownloadLatestData().execute();
Toast.makeText(SplashsActivity.this, "Server is online", Toast.LENGTH_SHORT).show();
} else {
if (database.isDataBaseCreated()) {
Toast.makeText(SplashsActivity.this, "Server is offline", Toast.LENGTH_SHORT).show();
Intent i = new Intent(SplashsActivity.this, MainActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
finish();
} else {
connectionerror();
}
}
}
}
Now I want use isReachable condition in other method called connectionerror. Both is in same activity. connectionerror is like below
public void connectionerror() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(SplashsActivity.this);
alertDialog.setTitle("Error!");
alertDialog.setMessage("Connection Lost ! Try Again");
alertDialog.setPositiveButton("Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (downloadLatestDataStatus != null) {
downloadLatestDataStatus.clear();
}
if (NetworkCheck.isInternetAvailable(SplashsActivity.this)) {
new DownloadLatestData().execute();
} else {
connectionerror();
}
}
});
alertDialog.show();
}
You can see one condition in connectionerror method like below
if (NetworkCheck.isInternetAvailable(SplashsActivity.this)) {
new DownloadLatestData().execute();
}
instead this condition for network check, I want use isReachable from AsyncTask....How can I do it ?
I have got solved via hire freelancer for fix it. He have done like below in alert dialogue
new AsyncServerOnlineCheck().execute();
Thanks all friends !!

AsycTask Throwing IllegalStateException - Fragment Not Attached To Activity

I have the following AsyncTask in my Android application. This AsyncTask is contained with within the OnCreate() method of a class that extends PreferenceFragment.
public class NotificationsPreferenceFragment extends PreferenceFragment {
private static Context context;
public NotificationsPreferenceFragment() {
}
public NotificationsPreferenceFragment(Context context) {
this.context = context;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notifications);
getPreferenceManager().findPreference(getString(R.string.send_all_notifications))
.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
class NotificationSendTask extends DialogAsyncTask {
public static final String TAG = "NotificationFragment";
public NotificationSendTask(Activity activity, String dialogMsg) {
super(activity, dialogMsg);
}
#Override
protected String doInBackground(String... params) {
String url = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(getString(R.string.notification_web_service_url), getString(R.string.default_notification_web_service_url));
if (NetworkingHelper.isNetworkAvailable(getActivity())) {
NotificationDao notificationDao = new NotificationDaoImpl(DatabaseManager.getInstance(getActivity().getApplicationContext()), getActivity().getApplicationContext());
List<Notification> unsentNotificationList = notificationDao.findAllNotSent();
if (unsentNotificationList.size() != 0) {
NotificationSenderTask ns = new NotificationSenderTask(url, context);
try {
if (ns.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (unsentNotificationList)).get()) {
return getString(R.string.success);
}
} catch (InterruptedException e) {
Log.e(TAG, e.getMessage());
} catch (ExecutionException e) {
Log.e(TAG, e.getMessage());
}
return getString(R.string.failed_to_send_notifications);
} else {
return getString(R.string.no_notifications_to_send);
}
} else {
return getString(R.string.no_connection_notifications);
}
}
public void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog != null && dialog.isShowing()) {
dialog.hide();
}
Toast.makeText(activity, result, Toast.LENGTH_SHORT).show();
}
}
NotificationSendTask notificationSendTask = new NotificationSendTask(getActivity(), "Sending unsent notifications...");
notificationSendTask.execute();
return true;
}
});
getPreferenceManager().findPreference(getString(R.string.export_notifications)).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
NotificationExportTask notificationExportTask = new NotificationExportTask(NotificationsPreferenceFragment.this.getActivity(), 1);
notificationExportTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return true;
}
});
}
}
I am getting the following exception:
java.lang.IllegalStateException: Fragment NotificationsPreferenceFragment{416092f8} not attached to Activity
at android.app.Fragment.getResources(Fragment.java:741)
at android.app.Fragment.getString(Fragment.java:763)
Can someone please explain to me why this is happening and suggest ways to fix this issue?
UPDATE:
Here is the code for the Activity:
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
}
Since you are performing background task in your app. there is no guarantee that user will stay on same screen until task finishes so if user navigates to other screen or presses home button before task is completed; your fragment is detached from activity. So always make sure that you have fragment attached with the Activity.
try checking with
if (isAdded) {
//Do your UI stuff here
}
add above check wherever you get callback
Move your code from onCreate to onActivityCreated instead of trying to getActivity # onCreate.
That's because the fragment can be created when the activity is not yet ready, that's when you are trying to use it.
That is of course if you are adding the fragment to an activity like:
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(android.R.id.content, new PreferenceFragment()).commit();

Categories

Resources