Why doesn't “setContentView” work in if statement? [duplicate] - android

This question already exists:
why "setContentView" can't work in " if " ??? thx [closed]
Closed 9 years ago.
the code is in onCreate! when setContentView(R.layout.manual); is outside the if it works. But I moved setContentView(R.layout.manual); into if can’t work!
The followign:
if (settings.getBoolean("my_first_time", true)) {
setContentView(R.layout.manual); // can not work
}
But Log.d("Comments1", "First time"); always works
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getBoolean("my_first_time", true)) {
//the app is being launched for first time, do something
Log.d("Comments1", "First time");//this can be showed on logCat!
setContentView(R.layout.manual);// this can not work
// record the fact that the app has been started at least once
settings.edit().putBoolean("my_first_time", false).commit();
}
}

Your condition is not getting satisfied because
settings.getBoolean("my_first_time", true)
is not returning true.
Hence your
setContentView(R.layout.manual)
is not called inside the “if” block.

You need to know what you are doing if you set a if-else loop, because no matter what is the outcome setContentView() must be supplied with a valid layout id. If you have a condition to check before setting the layout, you can just check the id:
int layoutId=0;
if(condition) {
layoutId = R.layout.manual;
} else {
layoutId = R.layout.other;
}
setContentView(layoutId);

Related

Android text to speech voice distortion at the beginning

In Android app I have a text, which after the user press a button, it will be spoken by TTS:
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
final Button speech = findViewById(R.id.speech);
speech.setOnClickListener(speech1 -> {
if (!isPackageInstalled("com.google.android.tts")) {
showMsgSnack(getString(R.string.noTTS));
} else {
Boolean speak = checkSpeak();
if (!speak) {
speech.setCompoundDrawablesWithIntrinsicBounds(R.drawable.stop, 0, 0, 0);
if (history.length() > 3999) {
String var = history.substring(0, 3999);
ConvertTextToSpeech(var, "test");
String var2 = history.substring(3999);
ConvertTextToSpeech(var2, "test");
} else {
ConvertTextToSpeech(history, "test");
}
saveSpeak(true);
} else {
speech.setCompoundDrawablesWithIntrinsicBounds(R.drawable.play, 0, 0, 0);
tts.stop();
saveSpeak(false);
}
}
});
private void ConvertTextToSpeech(String history, String par) {
String readableText = fromHtml(history).toString(); //remove HTML tags -> do not read <br>
Bundle params = new Bundle();
params.putString(KEY_PARAM_UTTERANCE_ID, "");
tts.speak(readableText, TextToSpeech.QUEUE_ADD, params, par);
}
The stuff about TTS:
if ((isPackageInstalled("com.google.android.tts"))) {
tts=new TextToSpeech(SingleitemView.this, status -> {
if(status == TextToSpeech.SUCCESS){
if (isLangAvailable(this,tts,locale)) {tts.setLanguage(locale);}
else {tts.setLanguage(new Locale("en"));}
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onDone(String utteranceId) {
// Log.d("Speak", "TTS finished");
if (utteranceId.equals("test")) {
saveSpeak(false);
runOnUiThread(() -> {
Button view2 = findViewById(R.id.speech);
view2.setCompoundDrawablesWithIntrinsicBounds(R.drawable.play, 0, 0, 0);
});
}
}
#Override
public void onError(String utteranceId) {
}
#Override
public void onStart(String utteranceId) {
}
});
}
},"com.google.android.tts");}
This worked for years without problems, the TTS read the text even if it was short, or more than 3999 characters. Suddenly a few months ago (without any change from my side in application) when it starts to speak longer text, the first 3-4 words are distorted and hardly understandable in every text.
Looks like as it is doing something in the background while it is reading the text in the same time.
Not sure what happened, because I dod no change in my code and it worked till now.
So now I tried to update all libraries and dependencies, but it didn't help.
The problem is only with the text, which is longer than 3999 chars. The shorter text is working with no issues.
I also tried to put this condition outside of onClickListener, so the text is prepared first:
if (history.length() > 3999) {
String var = fromHtml(history.substring(0, 3999)).toString();
String var2 = fromHtml(history.substring(3999)).toString(); }
and then in onClickListener I just call the TTS twice:
ConvertTextToSpeech(var, "test");
ConvertTextToSpeech(var2, "test");
private void ConvertTextToSpeech(String history, String par) {
Bundle params = new Bundle();
params.putString(KEY_PARAM_UTTERANCE_ID, "");
tts.speak(history, TextToSpeech.QUEUE_ADD, params, par);
}
But I have the same issue, this solution didn't helped.
I thought the issue is that I call immediately two ConvertTextToSpeech after each other, but even if I remove the second one, the problem is there.
So definitely, the problem is with the longer text, but I can't find the solution why it started to happen. I checked this on many devices, same issue everywhere.
The only thing that helps is to create much smaller chunks of text:
for (int a=1; a <= history.length(); a+=100) {
if((history.length() - (a + 100)) > 0) {ConvertTextToSpeech(history.substring(a, a+100), "test");}
else {ConvertTextToSpeech(history.substring(a), "test");}
However, this causes a noticeable pause between speaking the chunks, often also inside the word, so this is not a good solution.
Ok, so even if the max limit for google TTS is 3999 characters, for some reason it started to have issues also with ca. 3000 characters. Not sure why it happened, but it just happened without any code change on my side. Seems an issue related to google TTS.
So, as in my case the text blocks are separated by a break line <br>, and I know each block has no more than 1000-2000 chars, I now splitted all my text like this:
String[] parts = history.split("<br>");
for(String part: parts) {ConvertTextToSpeech(part, "test");}
So now this is working for any text with any length. Problem solved.

Android Studio - Condition is always true?

This would be the first time I post a question since I couldn't find the answer to this. Something really weird is happening with my if/else statements. My code was working perfectly for the past week, but recently it kept on telling me that a statement is always true?
My code is the following:
int checking = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checking != 1) {
speaker.setChecked(true);
} else if (checking == 1) {
speaker.setChecked(false);
}
}
This says checking == 1 is always true which makes sense, but if I switch it around to:
if (checking == 1) {
speaker.setChecked(true);
} else if (checking != 1) {
speaker.setChecked(false);
}
This says that checking != 1 is always true as well. Can someone help?
It's just a logic of editor. In first if statement, you check checking == 1 and the second if statement, you negative the statement. The editor will understand the second if statement alway true
I think you should replace else if to else. Sorry my bad English.
The reason why you are seeing this warning is:
You have set int checking = 1 and you are either checking:
if (checking != 1) which is always true
Or checking == 1 which is also always true
Due to this other else if condition will not be executed at all.
The warning will be only removed if you try to change value of checking either at runtime or using some conditions at compile time.
If your intention is just to set the speaker.setChecked() you can do following:
speaker.setChecked(checking == 1)
Note: This will not remove the warning
Try this
int checking = 1;
boolean isChecked = false;
isChecked = ((checking == 1) ? true : false)
speaker.setChecked(isChecked)

how can i change background of textview in other activities [duplicate]

This question already has answers here:
How to use SharedPreferences in Android to store, fetch and edit values [closed]
(30 answers)
Closed 5 years ago.
I have a setting activity with a TextView and a set off buttons.
I Want each button to changes the background of textviews in other activities.
I need example codes on how to do this.
Thank you all in advance.
Code:
btn.setOnClickListener( new
View .OnClickListener () {
public boolean stateChanged;
public void onClick(View view) {
if (stateChanged) {
// reset background to default;
tv.setBackgroundResource
(R.drawable.favon);
} else {
tv.setBackgroundResource
(R.drawable.favoff);
}
stateChanged = !stateChanged;
In a nutshell, you would start by initializing it.
Use get to grab any saved value or default if nothing was found.
Or use edit and put to store the data.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.getInt("key", defaultValue);
sharedPreferences.edit().putInt("key", value).apply()
More
EDIT:
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// Set up how the background was before
if (sharedPreferences.getBoolean("textViewBackground", true)) {
// Default background
tv.setBackgroundResource(R.drawable.favon);
} else {
// Other background
tv.setBackgroundResource(R.drawable.favoff);
}
btn.setOnClickListener(new View.OnClickListener() {
public boolean stateChanged;
public void onClick(View view) {
if (stateChanged) {
// reset background to default;
tv.setBackgroundResource(R.drawable.favon);
} else {
tv.setBackgroundResource(R.drawable.favoff);
}
stateChanged = !stateChanged;
sharedPreferences.edit().putBoolean("textViewBackground", stateChanged).apply();
}
});

where to initialize the ID from GCM?

I use GCM in my project.Where do I get an ID, so it is always available at all times? Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!CloudMessaging.checkPlayServices(this)) {
return;
}
CloudMessaging.getInstance(this).setRegistrationListener(eventHandler);
}
"but if I turn aside and then expand Programmes at, then again will get ID." ->Possibly:
If I change my orientation, then again I get a new Id.
You can get your ID for GCM
if (m_gcm == null)
{
m_gcm = GoogleCloudMessaging.getInstance(m_context);
}
m_regid = m_gcm.register("Your project id from google api console");
Note : please do this network operation in background thread..
Use SharedPreferences to store your ID once you get a new one.
Steps required: (do this in your onCreate)
Check if you already have a valid GCM id in your SharedPreferences
If you already have one, use it.
Otherwise, request a new one and save it in your SharedPreferences.

Create a function that fires only once after app is installed on phone

I'm developing a mobile app using ApacheCordova/Phonegap.
I need a function that sends a SMS to me once per install. If I put my function on "DeviceReady" it will be run each time the app opens.
Is there any solution for a function to be run when app is installed OR when it runs for first time?
Any suggestion would be appreciated.
Check if it is the first time with a method and then perform the action if that method determines that it is the first time.
Ex:
isFirstTime() Method
private boolean isFirstTime()
{
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean ranBefore = preferences.getBoolean("RanBefore", false);
if (!ranBefore) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", true);
editor.commit();
// Send the SMS
}
return ranBefore;
}
You may want to add it to your onCreate()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
topLevelLayout = findViewById(R.id.top_layout);
if (isFirstTime()) {
topLevelLayout.setVisibility(View.INVISIBLE);
}
I added a field to the localstorage and on startup just check if that field exists. So something like this:
if (window.localStorage.getItem("installed") == undefined) {
/* run function */
window.localStorage.setItem("installed", true);
}
Edit: The reason I prefer this over the other methods is that this works on iOS, WP, etc as well, and not only on android
This should be what u are searching for:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("firstTime", false))
{
// run your one time code
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
Use some boolean value if its true don't call that function other wise call that function example is here
if(smssent!=true)
{
//call sms sending method
}
else
{
//just leave blank or else notify user using some toast message
}
Note:-the boolean value store in some database like sharedprefernce or sqllite, files....

Categories

Resources