I have set to break on both read and write to a field, as shown below:
The problem is that the code never breaks when the field was access/modified when I know for a fact that the field was being accessed, and that breakpoints set in methods work as intended. How do I make it work?
Maybe you can try this: it's not a perfect solution, but a compromise one.
public class MainActivity extends Activity {
private boolean value = test();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (value) {
// do sth.
value = false;
}
}
private boolean test() {
return false;
}
}
create break point at return false line. But you may want to delete the extra code when the debugging is done.
Related
I have a boolean private field variable on my Main Activity that is set to False:
private boolean accountCreated = false;
When the acccount is created, I set it to true:
createAccountButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = nameInput.getText().toString();
username = usernameInput.getText().toString();
age = Integer.parseInt(ageInput.getText().toString());
saveData();
openMainMenuActivity();
accountCreated = true;
}
});
but the boolean value isn't changing from false to true. The code shown above is located inside the MainActivity.java class and inside a public void method. I want this boolean value to change because if false the user can't play, if true the user will be able to play.
I guess you try to continue your game in openMainMenuActivity() method so try to move the accountCreated = true; before openMainMenuActivity();
Otherwise it's hard to tell without providing more of your code
openMainMenuActivity() method should work in that way
Intent i = new Intent(CurrentActivity.this, MainMenuActivity.class);
i.putExtra("isAccountCreated", accountCreated);
startActivity(i);
And in OtherActivity's simply should look like this
public class MainMenuActivity extends AppCompatActivity {
boolean aDifferentAccountCreatedBoolean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
aDifferentAccountCreatedBoolean = getIntent().getBooleanExtra("isAccountCreated", false);
//Do stuff
}
}
It seems that openMainMenuActivity(); was resetting the value of the boolean. Instead of using openMainMenuActivity(); I opted to make a popup stating that the account was created successfully and simply dismissing the popup when the user presses X, hence going back to the openMainMenuActivity(); and the boolean value didn't reset. That made it work for me. Thanks to everyone for your answers!
I am working on an app with a RecyclerView, and I thought I almost had it running, but ran into a strange error.
I had made a few small changes to correct a small bug, and after that the app would no longer finish setting up the main activity layout. Instead I got the following screens:
App closed --- App keeps closing
My first thought was to look back at my small changes. But they did not cause this problem. (Undoing those changes did not fix the problem.)
I now believe that the problem is related to a change in the way the app operates between the first "successful" (though buggy) run and the following runs that fail.
In the first run, the app had to request permission from the user in order to access the documents folder. But after that, the app no longer needs to ask, because the user has already granted permission.
This means the order of execution has changed prior to the RecyclerView layout being created. But I can't (yet) figure out what's going wrong or how to fix it.
Here's the OnCreate() method in my main activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prog_summary);
}
Here's the OnCreate() method & other related methods in the superclass (the class that implements the permissions request):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.state = savedInstanceState;
if (state != null) {
isInPermission = state.getBoolean(STATE_IN_PERMISSION, false);
}
if (hasAllPermissions(getDesiredPermissions())) {
onReady(state);
}
else if (!isInPermission) {
isInPermission = true;
ActivityCompat.requestPermissions(this,
netPermissions(getDesiredPermissions()),
REQUEST_PERMISSION);
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions,
int[] grantResults) {
isInPermission = false;
if (requestCode == REQUEST_PERMISSION) {
if (hasAllPermissions(getDesiredPermissions())) {
onReady(state);
}
else {
onPermissionDenied();
}
}
}
Here's the OnReady() method in my activity class (called when permission is granted):
#Override
protected void onReady(Bundle savedInstanceState) {
_alEntries = new ArrayList();
TaskData tdSource = new TaskData();
// load task item array & trim the excess (unused) ArrayList space
tdSource.LoadData(this, _alEntries);
_alEntries.trimToSize();
// create summary item array & populate it based on task item array
_alSummaries = new ArrayList();
PopulateSummaryList();
_rv = (RecyclerView) findViewById(R.id.rvBookList);
_li = getLayoutInflater();
_rv.setLayoutManager(new LinearLayoutManager(this));
_adapter = new TaskItemAdapter();
_rv.setAdapter(_adapter);
}
The app actually closes when the call to setLayoutManager is executed. Any thoughts on where I've gone wrong or how to proceed in tracking this down?
Seems like it could be a NullPointerException in that your _rv variable is null. Judging by the code it makes sense, your superclass's onCreate method calls onReady() BEFORE setContentView() is called in your subclass's onCreate therefore by the time onReady() is called in your subclass findViewById(R.id.rvBookList) will return null as you haven't set the content of the class yet. To fix this I recommend making your superclass an abstract class. For example, in your superclass do this:
public abstract class BaseActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutId());
this.state = savedInstanceState;
// ... remaining code from your superclass's onCreate()
}
public abstract int getLayoutId();
}
Now in your MainActivity, extend BaseActivity. Since BaseActivity is abstract and getLayoutId() is an abstract method, it will force you to implement getLayoutId() like so:
public class MainActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public int getLayoutId() {
return R.layout.activity_prog_summary;
}
}
Doing this will ensure that all classes that inherit your superclass will perform the correct order of operations, in that setContentView is called before anything else.
I made a class for handling important data changes such as App Purchase Status and other stuff .
For this goal I have created a class which does the setting and reading of the values. but the problem is whenever I call the appIsPurchased() method, the result is true while it hasen't been changed since app installation and its first initial launch.
This is my code:
/**
* Created by neemasa on 5/29/14.
* This class handles more crucial data values within app.
*/
public class AppCore {
private SharedPreferences settings;
private String keyPurchase = "app_purchased";
private Context context;
public AppCore(Context context){
this.context = context;
settings = PreferenceManager.getDefaultSharedPreferences(context);
}
public void setAppInPurchasedMode(String status){
if (status.equals("successful")){
settings.edit().putBoolean(keyPurchase, true).commit();
}else if (status.equals("failed")){
settings.edit().putBoolean(keyPurchase, false).commit();
}
}
public boolean appIsPurchased(){
boolean purchased = false;
if (settings.getBoolean(keyPurchase,true)){
purchased = true;
}
return purchased;
}
}
Question 1st: is there something wrong with my code? if there is then why appIsPurchased() always return true?
Question 2nd: do all values in the shared preferences are true by default?
Meanwhile when I use this class in my code the toast "Purchased!" runs even when app is running for the first time.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppCore appCore = new AppCore(getApplicationContext());
if (appCore.appIsPurchased()){
Toast.makeText(getApplicationContext(),"Purchased!",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(),"Not Purchased!",Toast.LENGTH_SHORT).show();
}
}
Actually there is a problem in your code!! thats why its always showing purchased!!
if (settings.getBoolean(keyPurchase,true)){
purchased = true;
}
in this lines if the keyPurchased tag if not used , u are passing true value by default
so when u call
if (appCore.appIsPurchased()){
it always return a true value.. The solution is that make sure that the preference values are set before u call them.. hope this helps
Found It, the problem is that I was thinking
settings.getBoolean(keyPurchase,false)
returns the value of keyPurchased variable but the fact is it only returns the variable itself not its value so I fixed the problem by changing the method of my class to this:
public boolean appIsPurchased(){
return settings.getBoolean(keyPurchase,false);
}
you are setting the default value to true, so either your sharedpreference does not contains an entry for key_purchased or setAppInPurchasedMode is never called or is called wit status successful. On the minor side, your
public boolean appIsPurchased(){
boolean purchased = false;
if (settings.getBoolean(keyPurchase,true)){
purchased = true;
}
return purchased;
}
can be implemented like:
public boolean appIsPurchased(){
return settings.getBoolean(keyPurchase, false);
}
about setAppInPurchasedMode, if I were in you I would change the way you compare status, this way:
public void setAppInPurchasedMode(String status){
if ("successful".equals(status)){
settings.edit().putBoolean(keyPurchase, true).commit();
} else if ("failed".equals(status)){
settings.edit().putBoolean(keyPurchase, false).commit();
}
}
the difference is that if status is null, the way you implemented will crash your application with NPE. With my implementation you'll get false, because "successful" instanceof null is always false, and instanceof is the first check for equals
For those still having a problem, remember to apply the changes to your preferences.
private SharedPreferences sharedPreferences ;
private SharedPreferences.Editor sharedPreferencesEditor;
sharedPreferencesEditor.putBoolean("myVariable", false);
sharedPreferencesEditor.apply();
I have some preferences in my activity and I would like to achieve that, depending on these preferences, some services will be initiated or not.
I am trying to implement and onSharedPreferenceChangedmethod, but it never gets called (even if I have assigned it to a field).
The code is the following:
public class MtprojectActivity extends Activity {
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
callsCheckbox = prefs.getBoolean("callsLogChk", true);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (!started) {
startCallsService();
bindCallsService();
} else {
releaseCallsService();
stopCallsService();
}
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
Thanks a lot in advance!
Are you sure it isn't being called or is it just a case of it not doing what you expect? I may be wrong but shouldn't the code look like this...
if (key.equals("callsLogChk")) {
if (!started) { // Check NOT started ???
startCallsService();
bindCallsService();
}
else { // The 'else' should compliment the check for !started ???
releaseCallsService();
stopCallsService();
}
}
Sorry, as I don't know your code I may be totally wrong but as you've posted it, it doesn't look quite right to me.
EDIT:
Also, are you making sure you call the SharedPreferences.Editor.commit() method when you make the change to the preference?
I am trying to set a breakpoint inside an Activity class:
public class MainActivity extends Activity {
private EditText htmlContent = null;
private Button getBtn = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // <<<< this is where I set a breakpoint
htmlContent = (EditText)findViewById(R.id.htmlContent);
getBtn = (Button)findViewById(R.id.get);
// anonymous inner class implementing OnClickListener
getBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// fill htmlContent using HTTP GET
try {
final TestHttpGet thgObj = new TestHttpGet();
thgObj.executeHttpGet();
}
catch (Exception e){
// do something meaningful here
}
}});
// start some activity here?
getBtn.setEnabled(true);
}
}
Now, the funny thing is that this program runs and I can even see its layout screen in the emulator, but when I click the getBtn nothing happens, and so I tried to set a breakpoint inside to see why.
The amazing thing is... No breakpoint is ever reached - even if I set it on the first statement in OnCreate(). How is this possible???
Maybe mine is a stupid question, but... Are you running the program normally? or using the debug button?