I want to get value from several variables for example user1, user2, user3, user4.
how to check if variables are empty otherwise get the value and ignore variables that empty.
how I achieve this?, and sorry for newbie question...
if I do this
if(user1 != null && user2!= null && user3 != null && user4 != null){
user1.getText(); // or v1 = user1.value();
user2.getText(); // or v2 = user2.value();
user3.getText(); // or v3 = user3.value();
user4.getText(); // or v4 = user4.value();
}
which I dont want to do that, I just want to get the variable which had value in it and save it in array
Try with the following code.
ArrayList<String> listItems=new ArrayList<String>();
if(user1!=null)
{
listItems.add(user1.getText());
}
if(user2!=null)
{
listItems.add(user2.getText());
}
if(user3!=null)
{
listItems.add(user3.getText());
}
if(user4!=null)
{
listItems.add(user4.getText());
}
String [] arrayData = listItems.toArray(new String[listItems.size()]);
Note:You can also use isEmpty() method instead of checking for not a null value.
You mean a null check?
Value v1;
Value v2;
if (user1 != null) {
v1 = user1.value();
}
if (user2 != null) {
v2 = user2.value();
}
...etc
If you are dealing with String values then you may want to check the empty or null using TextUtils.isEmpty(str) API
public static boolean isEmpty (CharSequence str) Returns true if the string is null or 0-length.
if(user1!=null && !TextUtils.isEmpty(user1.getText()){
//not empty or null
}
Related
I do the following:
if (!items.containsKey(item) || items.get(item).getPrice() != 0) continue;
For the above I get the warning. In order to avoid it, I do
Objects.requireNonNull(items.get(item)).getPrice() != 0
The above works but it's not clean and anyway, I just checked that the item exists so for sure it's not null.
Is there a cleaner way? Thanks
Here is the full line of code:
if (!Utils.getInstance().items.containsKey(item.getId()) || Objects.requireNonNull(Utils.getInstance().items.get(item.getId())).getPrice() == 0) continue;
if (!Utils.getInstance().items.containsKey(item.getId()) || Objects.requireNonNull(Utils.getInstance().items.get(item.getId())).getPrice() == 0) continue;
That's quite a feat for a code!
You make to many logic in a single line.You need to divide it to a more readable one.
Let's simplify your code,
First, remove the requireNonNull. So it will be like this:
if (!Utils.getInstance().items.containsKey(item.getId()) || Utils.getInstance().items.get(item.getId()).getPrice() == 0) continue;
Second, extract Utils.getInstance().items to a single variable. So, it will be like this (Here I assume you're using a Map with HashMap):
// assuming a HashMap
HashMap items = Utils.getInstance().items;
if (!items.containsKey(item.getId()) || items.get(item.getId()).getPrice() == 0) continue;
Third, we extract the key as a single variable:
// assuming a HashMap
HashMap items = Utils.getInstance().items;
// assuming a string as the key
String key = item.getId();
if (!items.containsKey(key) || items.get(key).getPrice() == 0) continue;
Now, we can split the or part to this:
// assuming a HashMap
HashMap items = Utils.getInstance().items;
// assuming a string as the key
String key = item.getId();
if (!items.containsKey(key)) continue;
if(items.get(key).getPrice() == 0) continue;
the last code will gives you warning because Map.get() can return a null value. You can see from Map.get() documentation. So, we need to guard it.
Here the final version:
// assuming a HashMap
HashMap items = Utils.getInstance().items;
// assuming a string as the key
String key = item.getId();
if (!items.containsKey(key)) continue;
if(items.get(key) == null) continue;
if(items.get(key).getPrice() == 0) continue;
It maybe end up with more extra lines for your code. But it makes your code more readable and maintainable because you don't need to push your brain to hard to understand the code.
You could annotate your method/variable with #NonNull
#NonNull
fun test(){
}
#NonNull
private lateinit var test:List<String>
Maybe you should change your if condition from
if (!items.containsKey(item) || items.get(item).getPrice() != 0) continue;
to
if (items.get(item) == null || items.get(item).getPrice() != 0) continue;
You don't need to ensure that items contains the key item, just do it in following way:
Object value = items.get(item);
if (value == null || value.getPrice() != 0) continue;
I am getting a warning Argument amountTarget might be null. Is there any way to ignore this warning?
if (betid != null) {
String betnumber = mData.get(i).get("betnumber");
String amountTarget = mData.get(i).get("amountTarget");
holder.tx_amount.setText(amountTarget);
holder.tx_number.setText(betnumber);
holder.checkBox.setChecked(true);
//getting warning argument exception on amountTarget
int x = Integer.parseInt(amountTarget) * amountX - deductAmount;
holder.tx_counter.setText(x);
}
check that amountTarget isn't null by doing one of these:
if(amountTarget != null){
int x = Integer.parseInt(amountTarget) * amountX - deductAmount;
}
or initialize the variable to something before using it, for example
amountTarget = 0
int x = Integer.parseInt(amountTarget) * amountX - deductAmount;
alternatively you could also do something like this
if (amountTarget == null){
amountTarget = 0
}
code gets two user inputs from user and compares inputs to a database and prints out d corresponding data from the database.how do i add code to check for empty fields?
protected void onPostExecute(Void v) {
try {
boolean available=false;
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++) {
JSONObject Jasonobject = null;
//text_1 = (TextView)findViewById(R.id.txt1);
Jasonobject = Jarray.getJSONObject(i);
//get an output on the screen
//String id = Jasonobject.getString("id");
String name = Jasonobject.getString("name");
String name1 = Jasonobject.getString("name1");
String db_detail = "";
if (et.getText().toString().equalsIgnoreCase(name) && et1.getText().toString().equalsIgnoreCase(name1)||et.getText().toString().equalsIgnoreCase(name1) && et1.getText().toString().equalsIgnoreCase(name)) {
db_detail = Jasonobject.getString("detail");
text.setText(db_detail);
available = true;
break;
}
}
if(!available)
Toast.makeText(MainActivity.this, "Not available", Toast.LENGTH_LONG).show();
this.progressDialog.dismiss();
}
Use TextUtils.isEmpty(charactersequence)
if(!TextUtils.isEmpty(et.getText().toString().equalsIgnoreCase(name)))
{
}
Docs :
public static boolean isEmpty (CharSequence str)
Added in API level 1
Returns true if the string is null or 0-length.
Parameters
str the string to be examined
Returns
true if str is null or zero length
Also better to use optString
Jasonobject.optString("name");
You can use String.isEmpty() method which checks whether the length of the String is 0.
You can also try on String.matches().
Using equalsIgnoreCase("") performs an actual string comparison. This method returns true if the argument is not null and the Strings are equal, ignoring case; false otherwise.
So you may check using isEmpty() or matches("") method to check empty values and then do the comparison.
suppose your string you received is as below,
String nameString = jsonObj.getString("name");
you can check if its empty by using following check.
if(nameString.equals(""))
This question already has answers here:
How to remove duplicates from a list?
(15 answers)
Closed 8 years ago.
I want to remove duplicates from ArrayList of type Alerts where Alerts is a class.
Class Alerts -
public class Alerts implements Parcelable {
String date = null;
String alertType = null;
String discription = null;
public Alerts() {
}
public Alerts(String date, String alertType, String discription) {
super();
this.date = date;
this.alertType = alertType;
this.discription = discription;
}
}
Here is how I added the elements -
ArrayList<Alerts> alert = new ArrayList<Alerts>();
Alerts obAlerts = new Alerts();
obAlerts = new Alerts();
obAlerts.date = Date1.toString();
obAlerts.alertType = "Alert Type 1";
obAlerts.discription = "Some Text";
alert.add(obAlerts);
obAlerts = new Alerts();
obAlerts.date = Date2.toString();
obAlerts.alertType = "Alert Type 1";
obAlerts.discription = "Some Text";
alert.add(obAlerts);
What I want to remove from them-
I want all alerts which have unique obAlerts.date and obAlerts.alertType. In other words, remove duplicate obAlerts.date and obAlerts.alertType alerts.
I tried this -
Alerts temp1, temp2;
String macTemp1, macTemp2, macDate1, macDate2;
for(int i=0;i<alert.size();i++)
{
temp1 = alert.get(i);
macTemp1=temp1.alertType.trim();
macDate1 = temp1.date.trim();
for(int j=i+1;j<alert.size();j++)
{
temp2 = alert.get(j);
macTemp2=temp2.alertType.trim();
macDate2 = temp2.date.trim();
if (macTemp2.equals(macTemp1) && macDate1.equals(macDate2))
{
alert.remove(temp2);
}
}
}
I also tried-
HashSet<Alerts> hs = new HashSet<Alerts>();
hs.addAll(obAlerts);
obAlerts.clear();
obAlerts.addAll(hs);
You need to specify yourself how the class decides equality by overriding a pair of methods:
public class Alert {
String date;
String alertType;
#Override
public boolean equals(Object o) {
if (this == 0) {
return true;
}
if ((o == null) || (!(o instanceof Alert)))
return false;
}
Alert alert = (Alert) o;
return this.date.equals(alert.date)
&& this.alertType.equals(alert.alertType);
}
#Override
public int hashCode() {
int dateHash;
int typeHash;
if (date == null) {
dateHash = super.hashCode();
} else {
dateHash = this.date.hashCode();
}
if (alertType == null) {
typeHash = super.hashCode();
} else {
typeHash = this.alertType.hashCode();
}
return dateHash + typeHash;
}
}
You can then loop through your ArrayList and add elements if they aren't already there as Collections.contains() makes use of these methods.
public List<Alert> getUniqueList(List<Alert> alertList) {
List<Alert> uniqueAlerts = new ArrayList<Alert>();
for (Alert alert : alertList) {
if (!uniqueAlerts.contains(alert)) {
uniqueAlerts.add(alert);
}
}
return uniqueAlerts;
}
However, after saying all that, you may want to revisit your design to use a Set or one of its family that doesn't allow duplicate elements. Depends on your project. Here's a comparison of Collections types
You could use a Set<>. By nature, Sets do no include duplicates. You just need to make sure that you have a proper hashCode() and equals() methods.
In your Alerts class, override the hashCode and equals methods to be dependent on the values of the fields you want to be primary keys. Afterwards, you can use a HashSet to store already seen instances while iterating over the ArrayList. When you find an instance which is not in the HashSet, add it to the HashSet, else remove it from the ArrayList. To make your life easier, you could switch to a HashSet altogether and be done with duplicates per se.
Beware that for overriding hashCode and equals, some constraints apply.
This thread has some helpful pointers on how to write good hashCode functions. An important lesson is that simply adding together all dependent fields' hashcodes is not sufficient because then swapping values between fields will lead to identical hashCodes which might not be desirable (compare swapping first name and last name). Instead, some sort of shifting-operation is usually done before adding the next atomic hash, eg. multiplying with a prime.
First store your datas in array then split at as one by one string,, till the length of that data execute arry and compare with acyual data by if condition and retun it,,
HashSet<String> hs = new HashSet<String>();
for(int i=0;i<alert.size();i++)
{
hs.add(alert.get(i).date + ","+ alert.get(i).alertType;
}
alert.clear();
String alertAll[] = null;
for (String s : hs) {
alertAll = s.split(",");
obAlerts = new Alerts();
obAlerts.date = alertAll[0];
obAlerts.alertType = alertAll[1];
alert.add(obAlerts);
}
Why does this method always return true, even when the editTexts have nothing in them?
private boolean allFieldsFilledOut() {
boolean allFieldsFilledOut = false;
EditText name = (EditText) findViewById(R.id.editTextName);
EditText passWord = (EditText) findViewById(R.id.editTextPassWord);
EditText image = (EditText) findViewById(R.id.editTextProfilePicture);
if (name.getText().toString() != "" && passWord.getText().toString() != ""
&& image.getText().toString() != "") {
allFieldsFilledOut = true;
}
else {
allFieldsFilledOut = false;
}
return allFieldsFilledOut;
}
One thing I have been wondering about is, I create this activity through an intent a few times per use case. Am I referencing an old activity's editTexts? Should I be killing the activity when show a new activity? findViewById(R.id.editTextName) gets the application resource, with no reference to this specific activity. Is there another way to reference these editTexts?
When you compare string, use equals is compare string's value, use == is compare string's address
this mean (name.getText().toString())'s address != ("")'s address so that it always true
name.getText().toString() != ""
if you want to compare string's value, you need to use equals
if (name.getText().toString().equals("") == false &&
passWord.getText().toString().equals("") == false &&
image.getText().toString().equals("") == false)