I have a program that relates to a database. I start out my program by inserting a row using the following command.
long id = db.insertMajor(null, null, null, null);
it works perfect. I than alter the information but lets ignore that since for the time being I commented out all those lines. Now I want to check and see if it is null which is should be. If it is not null than I would like to check a checkbox. if it is null than I want to leave the box unchecked. So far I have this line to test.
String change = db.getMajorTitle(value).getString(1);
if (change.equals(null)) {
filled = false;
}
the filled boolean will check the box or not. If the database field is filled or not I always get a checkmark. Whats wrong?
UPDATE:
Since no one has figure it out I will post most of my code to try and help figure it out. I have also reset my emulator to ensure there is not problems with corrupted data.
chk1.setChecked(checker(1));
chk2.setChecked(checker(2));
chk3.setChecked(checker(3));
chk4.setChecked(checker(4));
}
boolean checker(int value){
DBAdapter db = new DBAdapter(this);
boolean filled = false;
db.open();
for (int i = 1; i <= 4; i++) {
String change = db.getMajorTitle(value).getString(1);
if (change == null) {
filled = false;
}else{
filled = true;
}
}
db.close();
return filled;
}
If someone copies this and it works can you please tell me what might be wrong with my emulator or eclipse or whatever. Thanks everyone for there input.
FINISHED:
I noticed that at another part in my program I changed null to "". I would like to thank everyone for being right and showing me different ways to code it.
You really don't need if statements for this.
filled = (change != null);
if (change.equals(null)) {
If change instance is not null, the above condition always returns false. Read Object equality constraints for more info.
If you want to check against null use
if( change == null) {
// change is null, update filled field
} else {
// change is not null, update filled field
}
If the database field is filled or not
I always get a checkmark. Whats wrong?
I guess that you would have initialized the filled field as true and never set it as false since your if condition always returns false or throws NullPointerException.
User ExceptionHandling mechanism. then you will succeed. Like
try {
if(change!=null)
{
//do ur work,if not null
}
else
{
// do some thing
}
}catch(NullPointerException e)
{
//do ur work,if null.
}
Related
I have a MutableLiveData variable in my AppRepository which is updated and contains my data. This I have no issues with. I also have the following observable to trigger a UI update with the data it holds in my onCreateView function:
viewModel.projectWithContent.observe(viewLifecycleOwner, {
pwc = it
counterList = it.counterList
})
When I tap either to increase or decrease the counter count and then try to push the update to my Room database, it skips it. I have the following check currently:
if(counterList != null) {
try {
for(counter: Counter in counterList!!) {
if(counter.counter_count != pwc?.counterList!![
pwc?.counterList!!.indexOf(counter)
].counter_count) {
Log.i(LOG_TAG, "Hello")
} else {
Log.i(LOG_TAG, "Goodbye")
}
}
} catch(e: IndexOutOfBoundsException) {
e.printStackTrace()
}
}
It'll always go to Goodbye.
Now. If I put the following just below try
Log.i(LOG_TAG, "PWC: ${pwc?.counterList!![0].counter_count}, " +
"CPWC: ${counterList!![0].counter_count}," +
"VMPWC: ${viewModel.projectWithContent.value?.counterList!![0].counter_count}")
It provides the following output:
PWC: 70, CPWC: 70,VMPWC: 70
Is this a side effect of what I'm doing or?
Thanks
Like #Tenfour04 says, your condition is actually checking they don't match, so "Goodbye" is the output when they do match.
If you don't mind (this is a little long), I just want to recommend some stuff because I feel like you're making life hard for yourself with all the null-checking that's going on - the logic of the code was really hard to read, and I'm guessing that's why you didn't notice the flipped logic too!
First: the ? null safety stuff (and !! which is the opposite of safe, never use it unless you know you have good reason) is there because you have nullable variable types. Normally the IDE would smart cast them to non-null once you've done a null check (like on your first line) - but because they're vars, they can be changed at any time.
That means that a variable that wasn't null before could be now, so you're forced to null-check every single time you access it. But even if the types weren't nullable, because they're vars, they can still change, and the thing you were looking at a moment ago is something different now.
The simple solution is to just make a new variable:
val counters = counterList
if (counters != null) {
...
}
// or if you want to use one of kotlin's scope functions
counterList?.let { counters ->
...
}
Because that new one is a val, it's not going to change what it's pointing at! Once it's null-checked, it's always going to be non-null, so you don't need to use ? anymore.
You have a couple of variables to make - you want to make sure pwc isn't null, and also their counterLists. A quick way to do that is with pwc?.counterList - if pwc is null, it will return null. Otherwise it will move to the next step, and return counterList, which may be null. (Using !! is saying that it definitely never will be null, in which case it shouldn't be nullable at all!)
And you don't actually care about pwc anyway - you're just comparing its counterList to the other, so why don't we pare it back to just those?
val counters = counterList
val pwcCounters = pwc?.counterList
if (counters != null && pwcCounters != null) {
try {
for(counter: Counter in counters) {
if(counter.counter_count != pwcCounters[
pwcCounters.indexOf(counter)
].counter_count) {
Log.i(LOG_TAG, "Hello")
} else {
Log.i(LOG_TAG, "Goodbye")
}
}
} catch(e: IndexOutOfBoundsException) {
e.printStackTrace()
}
}
There's more we could do here, but just by cleaning up those nulls and using the specific variables we want to work with, does that feel easier to read? And more importantly, easier to understand what's happening and what could happen?
Might be worth throwing it in a function too, stops the call site getting cluttered with these temp variables:
fun doThing(counters: List<Counter>?, pwcCounters: List<Counter>?) {
if (counters == null || pwcCounters == null) return
// do the stuff
}
// when you want to do the thing:
doThing(counterList, pwc?.counterList)
So all your null checking is out of the way, your "temp variables" are the fixed parameters passed to the function, it's all nice and neat.
I know this is a long post for such a short bit of code, but it's a good habit to get into - if you're writing code where you're working with nullable vars and you're wrestling with the null safety system, or you keep repeating yourself to access a particular variable nested inside another object, you can make things a lot easier for yourself! You can imagine how wild this could all get for more complex code.
Also if you care, this is how I'd personally write it, if it helps!
fun doThing(counters: List<Counter>?, pwcCounters: List<Counter>?) {
if (counters == null || pwcCounters == null) return
// for (counter in Counters) is fine too I just like this version
counters.forEach { counter ->
// find returns the first item that matches the condition, or null if nothing matches,
// so no need to handle any exceptions, just handle the potential null!
// (this is a really common Kotlin pattern, lots of functions have a "returns null on failure" version)
val pwcCounter = pwcCounters.find { it == counter }
// remember pwcCounter can be null, so we have to use ? to access its count safely.
// If it evaluates to null, the match just fails
if (counter.count == pwcCounter?.count) Log.i(LOG_TAG, "Hello")
else Log.i(LOG_TAG, "Goodbye")
}
}
I also renamed counter_count to just count since it's a property on a Counter anyway. I feel like counter.count is easier to read than counter.counter_count, y'know? It's the little things
Here the Text Area is constantly changing in terms of number and I want to trigger an event when the Text Area gets a particular number example I have tried this -
public void myfunction45(Canvas Panel)
{
if (Indicator = 45) {
Panel.enabled = false;.
}
} //(indicator- www.progress).
But it does not work(it does not read it nothing happens). how do I match the condition as the number is to be specific. please give an example for explanation. Thanks in advance.
That if statement would cause you problems.
You would want:
if(Indicator == 5)
instead. At the moment you're assigning the value without checking it, this would cause a compiler error. If it's just a typo, then update your answer, slightly confusing otherwise.
With regards to checking the text value. You'd have to grab the text value, for that you need a reference to the Text area. This approach assumes that the text area has it's value set by a user. Currently you're not grabbing any text values to compare, as a result, the if statement won't know what to compare.
Here's one approach:
public void myfunction5(Canvas Panel)
{
float result;
string textValue = yourTextArea.text;
if(Single.TryParse(textValue, out result))
{
if(result == Indicator)
{
Panel.enabled = false;
}
}
}
You use TryParse to avoid any potential exceptions that would be thrown if the user entered something that wasn't a number. This method will take the value from your text area, how you get your text area is up to you, and try to parse the text value into a float. The method will return true if the parse was a success, false otherwise.
Here's the reference for the TryParse stuff:
https://msdn.microsoft.com/en-us/library/26sxas5t(v=vs.110).aspx
If you wanted to parse it to an int, then you'd be using the Int32's version of TryParse, https://msdn.microsoft.com/en-us/library/system.int32_methods(v=vs.110).aspx
I'd also recommend having a peak at the Input Field documentation: https://docs.unity3d.com/Manual/script-InputField.html
You can subscribe your method to the Input-fields On Value Changed event, your function will need to tweaked slightly though:
public void myfunction5(string text)
{
float result;
if(Single.TryParse(text, out result))
{
if(result == Indicator)
{
CachedPanel.enabled = false;
}
}
}
Don't forget to store a reference to the panel you want to disable.
Hopefully this is what you're after.
Panel is already a Canvas type, it doesn't make any sense to GetComponent<Canvas> on the same type.
Try using Panel.enabled = false;.
For the rest, we don't know how you get the Indicator reference, or how you built the UI hierarchy, so we can't assess if the problem is there.
Edit: I could I miss the single = baffles me lol. I should avoid answering questions when I'm tired.
i'm having an issue that soon enough going to blow me.
i have Database table lets call it A. table A has field that determines if this row is processed or no. i update the field myself from within the Parse Browser to either True | False, and trying to call query.findInBackground() to check with the Boolean value however the returned List always returns False if its True and vice versa. enough talking let me show you what i'm doing.
public static void getMyRequests(ParseUser user, final FindCallback<ServicesModel> callback) {
ParseQuery<ServicesModel> query = new ParseQuery<>(ServicesModel.class);
if (!user.getBoolean(ParseHelper.CAN_UPLOAD)) {
query.whereEqualTo("user", user);
}
query.findInBackground(new FindCallback<ServicesModel>() {
#Override public void done(final List<ServicesModel> objects, ParseException e) {
if (e == null) {
if (objects != null && !objects.isEmpty()) {
for (ServicesModel object : objects) {
object.setHandlerUser(object.getParseUser("handlerUser"));
object.setProcessedTime(object.getLong("processedTime"));
object.setCategoryType(object.getString("categoryType"));
object.setUser(object.getParseUser("user"));
object.setUserRequest(object.getString("userRequest"));
object.setImageUrl(object.getString("imageUrl"));
object.setProcessed(object.getBoolean("isProcessed"));
Logger.e(object.getBoolean("isProcessed") + "");
}
callback.done(objects, null);
} else {
callback.done(null, new ParseException(1001, "No Services"));
}
} else {
callback.done(null, e);
}
}
});
}
the code above suppose to refresh my data but however my log always shows that isProcessed is False even tho it's set to True inside the Parse Browser
what i have tried besides this? fetchAllInBackground & fetch() you name it. the object will always return false until i re-run the application from Android Studio what i'm doing here wrong? btw here is how i initialize Parse
Parse.setLogLevel(BuildConfig.DEBUG ? DEBUG_LEVEL : Parse.LOG_LEVEL_NONE);
ParseObject.registerSubclass(ProductsModel.class);
ParseObject.registerSubclass(ProductRentalModel.class);
ParseObject.registerSubclass(ServicesModel.class);
Parse.enableLocalDatastore(context);
Parse.initialize(context, context.getString(R.string.app_id), context.getString(R.string.client_id));
the answer was to remove
Parse.enableLocalDatastore(context);
which is bad anyway, without the datastore enabled the data are refreshed probably, however with enabling the local database, the data will not refresh unless if i killed the app and/or re-install it. that's bad. but did the trick.
Hopefully a simple answer but I'm a little baffled. I'm expecting the code to go down the first if section below, but it always goes to the else.
When I get to line on a breakpoint >> if (url2!=null && !url2.isEmpty())
In the expressions window:
url2 IS "???/wp-content/uploads/2011/01/toonieJune10_091-640x334.jpg"
url2!=null IS true
!url2.isEmpty() IS true
However when debugging it always seems to hit the else, even though both conditions are true. I'm suspecting something is out of sync with my built code somehow as the step through debugging seems to give me inconsistencies.
I've tried cleaning the code and making some changes in the class and recompiling etc.
Help is much appreciated! Thanks!
public String getImageBannerUrl()
{
if (getPhotoFile1()!=null) return getPhotoFile1().getUrl();
String url2 = getRemoteImageUrl();
if (url2!=null && !url2.isEmpty())
{
return url2;
}
else
{
//Otherwise get default image based on category
return getImageCategoryUrl();
}
}
Try somthing like..
public String getImageBannerUrl()
{
if ((!getPhotoFile1().isEmpty()) && (!getPhotoFile1().matches(" "))) return getPhotoFile1().getUrl();
String url2 = getRemoteImageUrl();
if ((!url2.isEmpty()) && (!url2.matches(" ")))
{
return url2;
}
else
{
//Otherwise get default image based on category
return getImageCategoryUrl();
}
}
Note : here getPhotoFile1() must be returning String value..
I have some code, but it is not working as expected. My logic doesn't seem to be faulty, so I think it is an implementation error. My code:
public boolean[] party_check(){
Date date_ET = new Date(party_dateET.getYear(), party_dateET.getMonth(), party_dateET.getDayOfMonth());///Date is deprecated,
///but easy to handle
///this is used to test the date contained in the datepicker, party_dateET. If it is before the day today, then it will not write,
///and a message is displayed
boolean[] return_array = new boolean[4];
///EditText party_titleET;
///EditText party_timeET;
///EditText party_dateET;
///EditText party_venueET;
return_array[0] = true;
if(party_titleET.getText().length() == 0){
return_array[1] = false;
return_array[0] = false;
}else{
return_array[1] = true;
}
if(date_ET.before(Calendar.getInstance().getTime()) == true){
return_array[2] = false;
return_array[0] = false;
///tests that the date entered is not invalid, ie. is in the future.
///not test for time. I could say that if time == 00:00, then don't run, or use a listener to check if it has changed,
///using a boolean value. But this would not really benefit the task much, so I haven't. It would also
///take more coding, and more complex coding.
}else{
return_array[2] = true;
}
if(party_venueET.getText().length() == 0){
return_array[3] = false;
return_array[0] = false;
}else{
return_array[3] = true;
}
return return_array;
///return_array[0] - 1st value in array - is used as toggle as to whether the party is ready or not.
///return_array[1-4] are used to indicate to the user which textbox is empty/ has a problem.
}
However it does not do what I expect it to do when I return the boolean array. This is used for testing whether the user has entered a text value into the EditText's.
However it does not work as expected. Is my logic faulty, or I have implemented it wrong? Thanks for the help!!
The hint does not get returned, when you use getText(). You can use getHint() though.
Text and Hint are different properties.
So the Text will be empty, if the hint is shown.
Let's say that the hint is a "dress" for the text (not to let it "naked"), but it's not the text itself.