I already saw a lot of similar posts, but none seems to be the same as this. I am testing if a string is null in my Java Android (2.2) app and whatever the string is, it is always true. Here is the code :
public static String getLocalBluetoothName(){
String name;
if(mBluetoothAdapter == null){
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
try{
name = mBluetoothAdapter.getName();
if(name == null){
System.out.println("Name is null!");
name = mBluetoothAdapter.getAddress();
}
return name;
}
catch (Exception e){
return "";
}
}
The if(name == null) is always true even if my string has a value. By the way, I also tried mBluetoothAdapter.getName() == null and it is always true too. I saw somewhere that you can do something like that:
if(name.equals("null")){
}
But if the string is null, wouldn't that create an exception because I should not be able to use a method if the object is null? Also, testing "null" is somewhat strange to me...
Try this simplified version :
public static String getLocalBluetoothName(){
String name = null;
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter == null) {
//System.out.println("Can't get adapter");
Log.d(TAG, "Can't get adapter");
return name;
}
if ((name = adapter.getName()) == null) {
//System.out.println("Name is null!");
Log.d(TAG, "Name is null!");
name = adapter.getAddress();
}
return name;
}
and don't forget to include android.permission.BLUETOOTH permission in your app's manifest.
Also, note that sometimes your debugger may trick you by showing executing specific branches that are not in fact run (happened to me debugging in Eclipse before). So, make sure that you ACTUALLY have Name is null output in logcat, otherwise your name may be not null.
name = mBluetoothAdapter.getName();
Since name is null, your Bluetooth adapter probably doesn't have a name.
According to me, mBluetoothAdapter.getName() is always returning null, that is why the if condition is always returning true. Your method of comparing if(name == null) is absolutely correct, no doubt in this.
Related
I am learning Android but i am not much experienced with java.
I write these code to check if there is any data in sharedPreferences (Which i saved before using sharedPreferences.Editor) or not, and if there is any saved data then do something. But the code under if (savedData != null) Statement is always being executed, no matter if there is any value in savedData or not.
But when i use if (!savedData.isEmpty() it is doing what i meant it to do.
But i found on StackOverflow that we should not use isEmpty() with String because if String is null then isEmpty() will not execute.
I just wanted to know why if (savedData != null) is not working but if (!savedData.isEmpty()).
My code: Here Log.d("isRunning : ", "True") under if statement is always executing.
private String saveString = null;
private ListView listView;
private static List<String> listArray = new ArrayList<String>();
private SaveListInSharedPreferences saveListInSharedPreferences = new SaveListInSharedPreferences();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = getPreferences(MODE_PRIVATE);
String savedData = settings.getString(saveString, null);
if (savedData != null){
listArray = saveListInSharedPreferences.getList(savedData);
Log.d("isRunning : ", "True" );
}
if (myString != null && !myString.isEmpty()) {
//
}
If this doesn't work then it isn't null. If it's not working then try setting it directly equal to null beforehand, and then figuring out why that function isn't returning null
.
As to why myString != null doesn't work by itself, here's a post that can explain it better than I could.
Avoiding != null statements
i have a signup page connected to sql database.now i want to have validations in signup page like firstname,lastname,username etc can not be empty using java how can i do that
My code is
String fname=Fname.getText();
String lname=Lname.getText();
String uname=Uname.getText();
String emailid=Emailid.getText();
String contact=Contact.getText();
String pass=String.valueOf(Pass.getPassword());
Connection conn=null;
PreparedStatement pstmt=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/zeeshan","root","sHaNi97426");
pstmt=conn.prepareStatement("Insert into signup1 values(?,?,?,?,?,?)");
pstmt.setString(1,fname);
pstmt.setString(2,lname);
pstmt.setString(3,uname);
pstmt.setString(4,emailid);
pstmt.setString(5,contact);
pstmt.setString(6,pass);
int i=pstmt.executeUpdate();
if(i>0)
{
JOptionPane.showMessageDialog(null,"Successfully Registered");
}
else
{
JOptionPane.showMessageDialog(null,"Error");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
First your question is not direct. Validation occurs before database query. You should not proceed to database Connetction or making any query.
What should you do:
public static boolean nullOrEmpty(String value) {
return value == null || value.trim().equals("") ? true : false;
}
public void yourMethod(){
try{
//YourCode Here
String fname=Fname.getText();
if(nullOrEmpty(fname)){
new throw ValidationException("First name should not be null.");
}
//YourCode Here
}catch(ValidationException e){
System.err.println("Exception:"+e.getMessage());
}
}
Check for every string to validate.
that should not be hard, you can do it with simple if and else like below
if(fname != null && fname.isEmpty()){
throw new Exception(fname+" cannot be empty");
}else if(lname != null && lname.isEmpty()){
throw new Exception(fname+" cannot be empty");
}
.....
as a recommendation you should abstract validation and database access objects . see example of MVC here
You may do it just by downloading a jar named org.apache.commons.lang
Stringutils Class Reference
Sample Code
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
or
StringUtils.isEmpty(obj_String); // Another method to check either null or "";
To check if a String is empty you can use the method .isEmpty(). You'll probably want to use .trim() first, as this removes all the whitespaces at the beginning and ending of the String. For more options check out the full documentation here.
I have a set of JSONObject values which i receive from a server and operate on. Most times I get a JSONObject with a value (let's say statistics) and sometimes, it returns an Error object with a code and a description of the error.
How do I structure my code so that it doesn't break if it returns the error. I thought I could do this, but doesn't work.
public void processResult(JSONObject result) {
try {
if(result.getJSONObject(ERROR) != null ){
JSONObject error = result.getJSONObject(ERROR);
String error_detail = error.getString(DESCRIPTION);
if(!error_detail.equals(null)) {
//show error login here
}
finish();
}
else {
JSONObject info = result.getJSONObject(STATISTICS);
String stats = info.getString("production Stats"));
}
}
}
Use .has(String) and .isNull(String)
A conservative usage could be;
if (record.has("my_object_name") && !record.isNull("my_object_name")) {
// Do something with object.
}
It might be little late(it is for sure) but posting it for future readers
You can use JSONObject optJSONObject (String name) which will not throw any exception and
Returns the value mapped by name if it exists and is a JSONObject, or null otherwise.
so you can do
JSONObject obj = null;
if( (obj = result.optJSONObject("ERROR"))!=null ){
// it's an error , now you can fetch the error object values from obj
}
or if you just want to test nullity without fetching the value then
if( result.optJSONObject("ERROR")!=null ){
// error object found
}
There is whole family of opt functions which either return null or you can also use the overloaded version to make them return any pre-defined values.
e.g
String optString (String name, String fallback)
Returns the value mapped by name if it exists, coercing it if
necessary, or fallback if no such mapping exists.
where coercing mean, it will try to convert the value into String type
A modified version of the #TheMonkeyMan answer to eliminate redundant look-ups
public void processResult(JSONObject result) {
JSONObject obj = null;
if( (obj = result.optJSONObject("ERROR"))!=null ){
//^^^^ either assign null or jsonobject to obj
// if not null then found error object , execute if body
String error_detail = obj.optString("DESCRIPTION","Something went wrong");
//either show error message from server or default string as "Something went wrong"
finish(); // kill the current activity
}
else if( (obj = result.optJSONObject("STATISTICS"))!=null ){
String stats = obj.optString("Production Stats");
//Do something
}
else
{
throw new Exception("Could not parse JSON Object!");
}
}
In JSONObject there is a 'Has' method that you can do to Determaine the key.
I have no idea if this will work but it looks Credible.
public void processResult(JSONObject result) {
if(result.has("ERROR"))
{
JSONObject error = result.getJSONObject("ERROR")
String error_detail = error.getString("DESCRIPTION");
if(error_detail != null)
{
//Show Error Login
finish();
}
}
else if(result.has("STATISTICS"))
{
JSONObject info = result.getJSONObject("STATISTICS");
String stats = info.getString("Production Stats");
//Do something
}
else
{
throw new Exception("Could not parse JSON Object!");
}
}
It is sometimes more convenient and less ambiguous to have a NULL object than to use Java's null value.
JSONObject.NULL.equals(null) returns true.
JSONObject.NULL.toString()returns "null".
Example:
System.out.println(test.get("address").equals(null)); // Preferred way
System.out.println(test.getString("address").equals("null"));
source -- JSONObject oracle docs
Just a note:
With EE8 json specs, I can do an exception-safe get:
result.asJsonObject().getString("ERROR", null);
if, however, I want to do a check I can do it with:
result.asJsonObject().get("ERROR").equals(JsonValue.NULL)
If at any point in your code, org.json.JSONObject json_object becomes null and you wish to avoid NullPointerException (java.lang.NullPointerException), then do check it as below:
if(json_object == null) {
System.out.println("json_object is found as null");
}
else {
System.out.println("json_object is found as not null");
}
If in any case, your jsonobject is null.
Then use this statement for checking jsonobject is null or not.
if (!obj.get("data").isJsonNull()){
//Not Null
}else{
//Null
}
And for checking jsonobject is exist or not, use .has:
if (!obj.has("data")){
//Not Exist
}else{
//Exist
}
How can I detect when a json value is null?
for example: [{"username":null},{"username":"null"}]
The first case represents an unexisting username and the second a user named "null". But if you try to retrieve them both values result in the string "null"
JSONObject json = new JSONObject("{\"hello\":null}");
json.put("bye", JSONObject.NULL);
Log.e("LOG", json.toString());
Log.e("LOG", "hello="+json.getString("hello") + " is null? "
+ (json.getString("hello") == null));
Log.e("LOG", "bye="+json.getString("bye") + " is null? "
+ (json.getString("bye") == null));
The log output is
{"hello":"null","bye":null}
hello=null is null? false
bye=null is null? false
Try with json.isNull( "field-name" ).
Reference: http://developer.android.com/reference/org/json/JSONObject.html#isNull%28java.lang.String%29
Because JSONObject#getString returns a value if the given key exists, it is not null by definition. This is the reason JSONObject.NULL exists: to represent a null JSON value.
json.getString("hello").equals(JSONObject.NULL); // should be false
json.getString("bye").equals(JSONObject.NULL); // should be true
For android it will raise an JSONException if no such mapping exists. So you can't call this method directly.
json.getString("bye")
if you data can be empty(may not exist the key), try
json.optString("bye","callback string");
or
json.optString("bye");
instead.
In your demo code, the
JSONObject json = new JSONObject("{\"hello\":null}");
json.getString("hello");
this you get is String "null" not null.
your shoud use
if(json.isNull("hello")) {
helloStr = null;
} else {
helloStr = json.getString("hello");
}
first check with isNull()....if cant work then try belows
and also you have JSONObject.NULL to check null value...
if ((resultObject.has("username")
&& null != resultObject.getString("username")
&& resultObject.getString("username").trim().length() != 0)
{
//not null
}
and in your case also check resultObject.getString("username").trim().eqauls("null")
If you must parse json first and handle object later, let try this
Parser
Object data = json.get("username");
Handler
if (data instanceof Integer || data instanceof Double || data instanceof Long) {
// handle number ;
} else if (data instanceof String) {
// hanle string;
} else if (data == JSONObject.NULL) {
// hanle null;
}
Here's a helper method I use so that I can get JSON strings with only one line of code:
public String getJsonString(JSONObject jso, String field) {
if(jso.isNull(field))
return null;
else
try {
return jso.getString(field);
}
catch(Exception ex) {
LogHelper.e("model", "Error parsing value");
return null;
}
}
and then something like this:
String mFirstName = getJsonString(jsonObject, "first_name");
would give you your string value or safely set your string variable to null. I use Gson whenever I can to avoid pitfalls like these. It handles null values much better in my opinion.
i have an xml file with attributes like this:
<folder name = 'somename' description = ''/>
i want to display the description attribute as 'null' but it force closes and throws a FATAL Exception main in the LogCat.
i have this code below at the startElement() method
if (localName.equalsIgnoreCase("folder")) {
/** Get attribute value */
if(attributes.getValue("description")== "null"){
parseList.setFolderdesc(null);
}else{
String desc = attributes.getValue("description");
parseList.setFolderdesc(desc);
}
i tried this code but no luck...
how will i solve this without changing my xml file?
try with the following code
String desc = null;
try{
desc = attributes.getValue("description");
if((desc == null) || (desc.length()<=0)){
desc = null;
}
}catch(Exception ex){
desc = null;
}
if(parseList != null){
parseList.setFolderdesc(desc);
}
This code doesn't do what you expect:
if (attributes.getValue("description") == "null") {
You are comparing the attribute value with the String "null" not with a java null. (And you are testing strings the unsafe way too! Strings should be tested for equality using String.equals() not the == operator.)
That test should be written as follows:
if (attributes.getValue("description") == null) {
or better still:
if (attributes.getValue("description") == null ||
attributes.getValue("description").isEmpty()) {
(I'm not sure whether this will fix you problem, because I don't understand your problem description.)