Set Receive Intent back to Default Value in Android using Java - java

FirstActivity.java
startActivity(new Intent(FirstActivity.this, SecondActivity.class)
.putExtra("passed_value", true));
SecondActivity.java
#Override
public void onPageFinished(final WebView view, String url) {
if(getIntent().getBooleanExtra("passed_value", false)){
}
}
After receiving intent value from FirstActivity.java every reload it runs the if block . But i need this intent to run only in onPageFinished method.
So how to run if block only when it comes from FirstActivity.java. Is there any way so that i can make this intent value back to default value after if block executed?

In your SecondActivity create a class level variable as boolean passed_value = false;
Then in your onCreate(), change its value like - passed_value = getIntent().getBooleanExtra("passed_value", false);
Finally you can use it like -
#Override
public void onPageFinished(final WebView view, String url) {
if(passed_value){
}
}

A fairly straight forward method would be to have a Boolean passedValue variable that you instantiate with the intent extra in onCreate, and then set as false in the if block. Something along the following lines should work,
public class SecondActivity extends AppCompatActivity {
Boolean passedValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
passedValue = getIntent().getBooleanExtra("passed_value", false);
//Other code things
}
#Override
public void onPageFinished(final WebView view, String url) {
if(passedValue){
//Do what you need to do
passedValue = false
}
}
}

Related

SavedIntanceState.getBoolean() is making my app crash (i think)

My Goal:
So I need help putting a boolean primitives into a bundle and retrieving it from the bundle when there is a screen orientation change in Android. I am using that boolean value in a conditional statement that helps decide if 2 Button views (mTrueButton, mFalseButton) should be enabled or not. What i have so far is causing the app to shut down (aka crash) when there is a screen rotation. I think I am not retrieving or writing my boolean from my bundle or into my bundle correctly, and it is causing the app to crash.
How The App Should Works:
When a user touches the mTrueButton or mFalseButton button to answer a question, both buttons become disabled so the user is not allowed to answer again. I want those buttons to keep being disabled when the user answers and then rotates the screen.**
I know that when a user rotates their Android device, onDestroy() is called because runtime configuration changes take place, causing the app to be relaunched without having knowledge of it's previous state, (unless store my necessary data onto a bundle and pass it onto my onCreate method).
These are SOME global variables in my activity class
private int index = 0;
priavate Button mTrueButton,mFalseButton;
private static final String KEY_INDEX = "index";
private static final String BTTN_ENABLED = "bttnEnabled";
private boolean trueFalseButtonsEnabled = true;
These are SOME statements in my onCreate() method of the same activity class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
if(savedInstanceState != null) {
index = savedInstanceState.getInt(KEY_INDEX, 0);
changeButtonEnableStatus(savedInstanceState.getBoolean(BTTN_ENABLED,true));
}
mTrueButton = (Button)findViewById(R.id.true_button);
mFalseButton = (Button)findViewById(R.id.false_button);
mTrueButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
checkAnswer(true);
changeButtonEnableStatus(false);
}
});
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
changeButtonEnableStatus(false);
}
});
}
These are SOME methods in the same activity class but not in my onCreate()
private void changeButtonEnableStatus(boolean bool){
trueFalseButtonsEnabled = bool;
mTrueButton.setEnabled(bool);
mFalseButton.setEnabled(bool);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
Log.d(TAG,"onSavedInstanceState() called");
savedInstanceState.putInt(KEY_INDEX,index);
savedInstanceState.putBoolean(BTTN_ENABLED, trueFalseButtonsEnabled);
}
Note that:
index = savedInstanceState.getInt(KEY_INDEX, 0);
works properly. It is setting global variable "index" to equal to the int primitive what was stored in into keywork "KEY_INDEX".
However I don't think: changeButtonEnableStatus(savedInstanceState.getBoolean(BTTN_ENABLED,true)); is working properly. My app seems to crash when I include that statement and run the app, and then rotate the device.

How initialize correctly static variable in PreferenceActivity

I have Preference class extent PreferenceActivity.
I create public static String quality; in Preference.class i add in onCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref);
quality = "QUALITY_HIGH";//initialize
}
and add in Preference.class this method
public void getQuality() {
if (keyquality.equals("480p")) {
quality = "QUALITY_LOW";
//
}
if (keyquality.equals("720p")) {
//
quality = "QUALITY_720P";
}
if (keyquality.equals("1080p")) {
//
quality = "QUALITY_HIGH";
}
}
in another class i create method to get my variable and set settings
private void getqualityvideo() {
/*if (Prefernce.quality == null) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
} else {*/
if (Prefernce.quality.equals("QUALITY_LOW")) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
}
if (Prefernce.quality.equals("QUALITY_720P")) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_720P);
}
if (Prefernce.quality.equals("QUALITY_HIGH")) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
}
// }
}
Problem:
when start application
private void startServes() {
btnStart = (ImageView) findViewById(R.id.StartService);
btnStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
v.startAnimation(mAnimationImage);
Intent intent = new Intent(MainActivity.this, RecorderService.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(intent);
changeCamera
.setEnabled(false);
btnStart.setEnabled(false);
setings.setEnabled(false);
moveTaskToBack(false);
}
});
}
in another class in method
getqualityvideo() error NullPointerException
error in this first line
if (Prefernce.quality.equals("QUALITY_LOW"))
why the quality variable is empty?
The reason is that you're setting Preference.quality in the onCreate method in your Preference class. So what's probably happening is that when you start your application in your other class, Preference.quality is going to be null because it was never initialized to anything. The reason is that the other class has no way to access the onCreate method in your Preference class as of now. onCreate is executed when an activity starts, but that doesn't seem to happen anywhere in your code. A solution could be to initialize public static String quality outside of your onCreate method but still within the Preference class,
public static String quality = "QUALITY_HIGH";
#Override
public void onCreate(Bundle savedInstanceState) {
//insert code here
}
The problem was merely a scope issue.

On Preference change listener - after click run twice

I have in my app preference activity with EditTextPreference and I added this, to detect, when the text in edittext is changed. All works, except for that, the code runs always twice... I tryed to add System.out.println("now"); to proove if the code runs twice, and it writes "now" two times...
Here is the code:
SharedPreferences.OnSharedPreferenceChangeListener myPrefListner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.admin_activity);
myPrefListner = new SharedPreferences.OnSharedPreferenceChangeListener(){
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
switch(key) {
case "prefAddUser":
EditTextPreference connectionPref = (EditTextPreference) findPreference(key);
String jmeno = connectionPref.getText();
System.out.println("now");
add_user(jmeno); //custom method to add user to MySQL database
Toast.makeText(getApplicationContext(), "add user", Toast.LENGTH_SHORT).show();
connectionPref.setText("");
break;
}
}
};
}
#Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(myPrefListner);
}
#Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(myPrefListner);
}
I don't know what to do with this weird problem...
What should I do?
Calling OnSharedPreferenceChangeListener in anonymous class makes it become the target of garbage collection.
As soon as you leave the current scope and can cause unregisterOnSharedPreferenceChangeListener() to be call on a null context.
Implement it in the class scope like this:
public class SettingsActivity extends PreferenceActivity
implements OnSharedPreferenceChangeListener {
public static final String KEY_PREF_SYNC_CONN = "pref_syncConnectionType";
...
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals(KEY_PREF_SYNC_CONN)) {
Preference connectionPref = findPreference(key);
// Set summary to be the user-description for the selected value
connectionPref.setSummary(sharedPreferences.getString(key, ""));
}
}
}
Read the next tutorials for further explanation:
1. Good So answer on the subject
2. Official documentation here

Why does the code run a command, even if its if statement isn't fulfilled?

When I run my code in debug mode, I can see, that for the value "ooy" another content is set (and it would be correct like this) than for the value "skii". But the code still starts the Activity "Game.class", and the Activity "Tutorial.class" too but only in background. How can I solve this?
MainScreen:
public class MainScreen extends Activity implements OnClickListener {
public static final String PREFS_NAME = "MyPrefsFile1";
String ooy;
String skii;
super.onCreate(savedInstanceState);
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main_screen);
SharedPreferences tutoask = getSharedPreferences(PREFS_NAME, 0);
ooy = tutoask.getString("skipMessage", "NOT checked");
skii = "checked";
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.btn_start) {
startActivity(new Intent(this, Tutorial.class));
if (ooy.equals(skii)){
startActivity(new Intent(this, Game.class));
}
}
Tutorial:
public class Tutorial extends Activity implements OnClickListener {
Button btn;
public CheckBox checkBox1;
String checkBoxResult = "NOT checked";
public static final String PREFS_NAME = "MyPrefsFile1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tutorial);
btn = (Button) findViewById(R.id.startut);
btn.setOnClickListener( this);
checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
}
#Override
public void onClick(View v) {
if (checkBox1.isChecked()){
checkBoxResult = "checked";
SharedPreferences tutoask = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = tutoask.edit();
editor.putString("skipMessage", checkBoxResult);
// Commit the edits!
editor.commit();
}
startActivity(new Intent(this, Game.class));
finish();
}
}
Are you saying that the two variables have different values? Sorry, your sentence is difficult to understand.
If the variables are not equal it would execute what is inside the if command since you have the NOT (!) command.
If they are NOT equal execute the command:
startActivity(new Intent(this,Game.class));
I am not sure what you want to do and what the actual problem is. You have two variables with not equal values; when you check the two, they are not equal, so the command inside the if is executed. As it should since you have the not statement.
Look at the equals method of the ooy and skii objects. They are probably implementhed wrong.

How can I access a method from an activity and use it into another activity in Android?

I have the first class named iHave
public class iHave extends ActionBarActivity
{
//below is the instance for calling the method from the other activity.
(The name of the other activity is **iThank**)
**iThank thankYou = new iThank();**
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_i_have);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
**//this is the method I want to access from iThank class** **strong text**
thankYou.display();
}
});
}
//The Next class is "iThank"
public class iThank extends ActionBarActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_i_thank);
txtThank = (TextView) findViewById(R.id.textView3);
//this is the method I want to access/use from iHave Activity
public void display()
{
txtThank.setText ("Shine");
}
}
How can I use the method "public void display()" of iThank activity to the "iHave" activity? It always gives me an error of NullPointerException. Please help. Thank you very much!
How can I access a method from an activity and use it into another
activity in Android?
By creating object for other to access method from Activity is right way.
Use LocalBroadcastManager for communicating between application components.
1. Send broadcast from iHave on Button click:
#Override
public void onClick(View v)
{
Intent intent = new Intent("DISPLAY_EVENT");
LocalBroadcastManager.getInstance(v.getContext()).sendBroadcast(intent);
}
2. Register LocalBroadcastManager in iThank Activity:
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(ReceiveMessage,
new IntentFilter("DISPLAY_EVENT"));
}
3. Create BroadcastReceiver object and call display() method in iThank Activity:
private BroadcastReceiver ReceiveMessage = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
display();
}
};
Also add null check in display method for TextView:
public void display()
{
if(txtThank !=null)
txtThank.setText ("Shine");
}
Please don't to this, it is not how activities are intended to work. You might want to have a look over the Activities Developer Guide to get started. If you want to launch a new activity (e.g. iThank) from the current foreground activity (e.g. iHave), you never instantiate the class yourself directly and always launch it using an intent. If you have data to pass along (such as a message to display), it needs to be bundled along with the intent as an extra (see same link).
Activities should never call methods on each other directly, because this requires them to have references to each other. The framework manages the life cycle of each activity independently, and those references can lead to leaks.

Categories

Resources