How to check if string is empty - java

I have an activity 'B'. I have 2 more activities A and C. Both the activities lead to B. But i pass different Data from A and C. So while fetching
String dataFromA = getIntent.getStringExtra("SomethingA");
String dataFromC = getIntent.getStringExtra("SomethingC");
How to not get an error. I wont know from where the user is getting to activity B So how do i add an If statement or seomthing to not get an error while fetching as Either line A or C will get a NullPOinterException

You can use hasExtra method to check if that String exists.
if (getIntent().hasExtra("SomethingA")) {
String dataFromA = getIntent.getStringExtra("SomethingA");
} else if (getIntent().hasExtra("SomethingC")) {
String dataFromC = getIntent.getStringExtra("SomethingC");
}

You can try this code.
Bundle arguments = getArguments();
if (arguments != null){
if (arguments.containsKey("SomethingA")) {
String somethingA = arguments.getString("SomethingA");
if (TextUtils.isEmpty(somethingA)){
// Your codes comes here
}
}
}
Bundle (arguments) can be null if there is no data passed.

To check if string is empty or not use below code :
if(TextUtils.isEmpty(yourString))
{
// String empty
}
else
{
// string not empty
}
In your case you check it as :
if (getIntent()!=null && getIntent().getStringExtra!=null )
{
if (getIntent().hasExtra("SomethingA") && getIntent().hasExtra("SomethingB"))
String dataFromA = getIntent.getStringExtra("SomethingA");
String dataFromB = getIntent.getStringExtra("SomethingB");
}

Related

Set default value, if exist in config.properties use that, if overridden on command line use that

Untested code (just thinking out loud), but I'm thinking there must be a more elegant way to do this.
So there's three ways to set a variable:
just assign it
read it from a properties file (might not be there)
read it from the command line (could be more than one argument or none)
Higher number takes precedence. How would I approach this?
public static final String APP_DOWNLOAD_PATH;
[...]
// If download path is not defined in config.properties, set it to the app dir.
String download = properties.getProperty("download", System.getProperty("user.dir"));
// Override if download path is set via command line.
String override = null;
try {
override = System.getProperty("download");
} catch (NullPointerException | IllegalArgumentException ok) {
// property is either not found or empty.
}
String APP_DOWNLOAD_PATH = (override == null || override.isEmpty()) ? download : override;
E: Added restrictions.
The straight forward approach is the best in my opinion. For example:
public static final String APP_DOWNLOAD_PATH = "foo";
public static void main(String... args) {
String dwnPath = null;
if(args.length > 0) {
dwnPath = args[0];
} else if(System.getProperty("download") != null) { // don't need try-catch, "download" is not null and not empty ("")
// not DRY at all
dwnPath = System.getProperty("download");
} else {
dwnPath = APP_DOWNLOAD_PATH;
}
// rest of program
}
The above could also be extracted to it's own function leading to a one liner:
String dwnPath = getDownloadPath(args, System.getProperty("download"), APP_DOWNLOAD_PATH);
The extracted function can also be more elegant than the code above:
/** Documentation */
public static String getDownloadPath(String[] args, String property, String default) {
return (args.length > 0) ? args[0] : (property != null) ? property : default;
}
If it is ok to use a external library, then this apache commons method could be useful -
StringUtils.firstNonEmpty(System.getProperty("download"),
properties.getProperty("download", System.getProperty("user.dir")),
"some value");

Android Fragment - how to get the "mWho" value?

If one prints a Fragment:
println("fragment: ${Fragment()}")
it prints out:
Fragment{8d157db} (d63150f2-7497-4c04-9214-d20c3ccaba34)
Looking at the implementation of the toString(), I can see:
public String toString() {
StringBuilder sb = new StringBuilder(128);
Class<?> cls = getClass();
sb.append(cls.getSimpleName());
sb.append("{");
sb.append(Integer.toHexString(System.identityHashCode(this)));
sb.append("}");
sb.append(" (");
sb.append(mWho);
if (mFragmentId != 0) {
sb.append(" id=0x");
sb.append(Integer.toHexString(mFragmentId));
}
if (mTag != null) {
sb.append(" tag=");
sb.append(mTag);
}
sb.append(")");
return sb.toString();
}
So the UUID it's printing is from mWho variable which gets generated using:
// Internal unique name for this fragment;
#NonNull
String mWho = UUID.randomUUID().toString();
Is there a way to get this value for use as the tag when using supportFragmentManager.findFragmentByTag? Getting it without parsing the toString string.
I am asking this because right now I have my own custom uniqueUUID which I use for restoring a fragment using retainInstance. If I can get the mWho, I won't need my own custom code for the uniqueUUID.
I was able to achieve this using reflection and lazy variable:
val who: String by lazy {
println("Trying to get who!")
var toReturn = ""
try {
println("Fields: ${javaClass.superclass.superclass}")
toReturn = javaClass.superclass.superclass.getDeclaredField("mWho").let {
it.isAccessible = true
it.get(this)
} as String
} catch (e : Exception) {
println("Exception getting who: $e")
}
toReturn
}
Note the use of superclass.superclass because I placed this in a subclass of Fragment. The use of lazy prevents the use of reflection each time it's required as this value doesn't change once initialized.

How do I split a string by specific pairing groups?

I am writing my own JSON parser in Java and I am looking for a way to split a string by a comma or a colon, that are outside [], {} or "" pairs.
I found a tutorial via Google, and it works. The issue is, that it also captures the commas inside those brackets, and I need it to ommit them. I don't know how to edit the regular expression to exclude captured commass from one of these bracket pairs. I tried something like ",(?=([^\"\\{\\[]*\"[^\"\\}\\]]*\")*[^\"]*$)", but it doesn't work. It messes it up even more. The same also applies to the colon separation, which is used in separation of key and value of a JSON object.
Is there a way to combine the "", {} and [] pairs together in the regex in such way that it works? Sorry if I look like a lame, but I really can't figure out how the regex should look like.
BTW, this is a code snippet I want to use it in:
public class JavaJSON {
private HashMap<String, Object> content;
// Constructors
/**
* Create new empty JSON object
*/
public JavaJSON() {
this.content = new HashMap<>();
}
// ...
/**
* Parse a JSON string to a JSON object
*
* #param JSON JSON string to be converted to JSON object
* #return JSON object from given string
*/
public static JavaJSON parse(#NotNull String JSON) {
if (!JSON.startsWith("{") || !JSON.endsWith("}")) return null;
// If this is not a valid JSON string, return nothing.
JavaJSON output = new JavaJSON();
String content = JSON.substring(1, JSON.length() - 1);
if (content.length() == 0) return output; // if empty, return an empty JSON object
// Regex literals
String commaSeparated = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"; // TODO: Change commaSeparated to capture any {} [] "" pair group
String colonSeparated = ":(?=([^\"]*\"[^\"]*\")*[^\"]*$)"; // TODO: Change colonSeparated to capture any {} [] "" pair group
String[] tokens = content.split(commaSeparated);
if (tokens.length == 0) return null;
// Don't know exactly if this is going to happen, but better be sure
for (String token : tokens) {
String rawToken = token.trim();
if (rawToken.length() == 0) return null;
// Omitted comma, extra comma, etc. = JSON error
String[] mapToken = rawToken.split(colonSeparated);
if (mapToken.length < 2 || mapToken.length > 2) return null;
// Expected format = {"foo": "bar"}; format isn't valid
String mapKey = mapToken[0].trim();
String mapValue = mapToken[1].trim();
if (!mapKey.startsWith("\"") || !mapKey.endsWith("\"")) return null;
// Key must be a string
String rawMapKey = mapKey.substring(1, mapKey.length() - 1); // get quote-less variant
if (rawMapKey.length() == 0) return null;
// Key must not be empty
// check errors
if (mapValue.startsWith("{") && !mapValue.endsWith("}")) return null;
// Not a valid JSON object
if (mapValue.startsWith("[") && !mapValue.endsWith("]")) return null;
// Not a valid JSON array
if (mapValue.startsWith("\"") && !mapValue.endsWith("\"")) return null;
// Not a valid string
// get value object
Object rawMapValue;
// parse value object
if (mapValue.startsWith("\"") && mapValue.endsWith("\"")) {
rawMapValue = mapValue.substring(1, mapValue.length() - 1);
} else if (mapValue.startsWith("{") && mapValue.endsWith("}")) {
rawMapValue = parse(mapValue);
} else if (mapValue.startsWith("[") && mapValue.endsWith("]")) {
rawMapValue = parseArray(mapValue);
} else {
try {
rawMapValue = Long.parseLong(mapValue);
} catch (Exception e) {
try {
rawMapValue = Double.parseDouble(mapValue);
} catch (Exception f) {
return null;
// Not a valid number
}
}
}
output.update(rawMapKey, rawMapValue);
}
return output;
}
// ...
}

Error while trying to return a value.

I'm stuck on the very last part of my homework. I have to return an Agent value, but for some reason I keep getting an error saying that "This method must return type Agent", even though what I am returning is an Agent. Any help would be greatly appreciated.
import java.io.File;
import java.util.HashMap;
import jeff.ini.Ini;
public class ConfigLoader
{
private Ini _ini;
private HashMap<String, Space> _spaces = new HashMap<String, Space>();
private HashMap<String, Portal> _portals = new HashMap<String, Portal>();
private HashMap<String, Agent> _agents = new HashMap<String, Agent>();
public ConfigLoader(File iniFile)
{
_ini = new Ini(iniFile);
}
public Agent buildAll()
{
_buildSpaces();
_buildPortals();
_buildExits();
_buildDestinations();
_buildAgents();
return _selectStartAgent();
}
private void _buildSpaces(){
for(String spaceName : _ini.keys("spaces")){
String descrip= _ini.get("spaces", spaceName);
String image= _ini.get("images", "images");
Space space1= new Space(spaceName, descrip, image, null);
_spaces.put(spaceName, space1);
}
}
private void _buildPortals(){
for(String portalName : _ini.keys("portals")){
String descrip= _ini.get("portal", portalName);
Portal portal1=new Portal(portalName, descrip, null);
_portals.put(portalName, portal1);
}
}
private void _buildExits(){
for(String spaceName : _ini.keys("exits")){
String spaceExit = _ini.get("exits", spaceName);
Space space = _spaces.get(spaceName);
Portal exit = _portals.get(spaceExit);
space.setPortal(exit);
}
}
private void _buildDestinations(){
for(String portalName : _ini.keys("destinations")){
String destination = _ini.get("destinations", portalName);
Space des = _spaces.get(destination);
if(des == null){
System.out.print("ERROR");
System.exit(1);
}
else{
Portal portal = _portals.get(portalName);
portal.setDestination(des);
}
}
}
private void _buildAgents(){
for(String agentName : _ini.keys("agents")){
String agent = _ini.get("agents" , agentName);
Space space = _spaces.get(agent);
if(space == null){
System.out.print("ERROR");
System.exit(1);
}
else{
Agent a = new Agent(space, agentName);
_agents.put(agentName, a);
}
}
}
private Agent _selectStartAgent(){
for(String agentName : _ini.keys("start")){
String agent = _ini.get("start" , agentName);
Agent agent1 = _agents.get(agent);
if(agent == null){
System.out.print("ERROR");
System.exit(1);
}
else{
return agent1;
}
}
}
}
A method should return a value in all the different execution path. You are returning a value only in else block, which means in case when else block is not executed the value will not be returned and hence compiler complains for it. Make sure that you return a value in all different execution path, when if is not executed, when else is not executed, when for loop itself is not executed.
The key is that all execution paths must return a value of type Agent, which could be null. The calling method must, as usual, check whether the returned value is null.
Now let's look at what are missing:
The if branch does not return a value, instead it abruptly exits.
If the for loop is never entered, the method does not return anything either.
With all those fixed, the entire code could be something like:
for (String agentName : _ini.keys("start")){
String agent = _ini.get("start" , agentName);
Agent agent1 = _agents.get(agent);
if (agent == null){
System.out.print("ERROR");
return null;
} else {
return agent1;
}
return null;
}
The problem with your _selectStartAgent method is that a return isn't executed in all cases. You do call System.exit(1) inside this method, but the compiler doesn't care; it sees that as another method call. Even if it won't return because the JVM will be exited, the compiler still requires a return in the case where agent is null.
You could just place a return null; after System.exit(1). However, this method shouldn't be handling an error. It just needs to report the error. Just have it return null (or have it throw an exception).
if(agent == null){
return null;
// or
// throw an exception here
}
The method that calls _selectStartAgent should check for null (or handle the exception, depending on which you choose).
Additionally, the compiler doesn't assume that there will be an iteration of any for loop. There is no return there either. You can place a return statement after the for loop, to ensure that there is a return when there is no iteration of the for loop.
I believe it has to do with if your for loop doesn't have anything to loop through. In that case, you have no return statement.
Try adding return null after the for loop.
private Agent _selectStartAgent(){
for(String agentName : _ini.keys("start")){
String agent = _ini.get("start" , agentName);
Agent agent1 = _agents.get(agent);
if(agent == null){
System.out.print("ERROR");
System.exit(1);
}
else{
return agent1;
}
}
return null;
}

Null Pointer Exception from JCalander Combobox

My Java Application produces Null Pointer Exception from JCalander Combobox. I tried to catch the error. But that didnt work. Can someone assist me to fix this. Please.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.util.Calendar.setTime(Calendar.java:1106)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:955)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:948)
at java.text.DateFormat.format(DateFormat.java:336)
at org.freixas.jcalendar.JCalendarCombo.paramString(JCalendarCombo.java:780)
at java.awt.Component.toString(Component.java:8095)
tbmodel = (DefaultTableModel)tblItmQty.getModel();
System.out.println(calRecvDate.getDate());
try{
if(calRecvDate.getDate()==null){ // Error
JOptionPane.showMessageDialog(null, "Please Select Shippment Received Date");
calRecvDate.requestFocus();
}else if(txtShipSs.getText().isEmpty()){
////////////////////////////////////////////////////////////////
if (inputValidate() == true) {
try {
String shipId = txtShipId.getText();
String invID = txtInvoice.getText();
String shipSs = txtShipSs.getText();
String address = txtNtfAddress.getText();
String sipper = txtAShipper.getText();
String vessal = txtVessal.getText();
Date rcvDate = calRecvDate.getDate(); // Jcalander
String consignee = txtConsigne.getText();
ArrayList<ShippmentItems> shipItems = new ArrayList<ShippmentItems>();
tbmodel = (DefaultTableModel) tblItmQty.getModel();
for (int i = 0; i < tbmodel.getRowCount(); i++) {
String itmcode = (String) tbmodel.getValueAt(i, 0);
String itmName = (String) tbmodel.getValueAt(i, 1);
int qty = (int) tbmodel.getValueAt(i, 2);
ShippmentItems shpItems = new ShippmentItems(shipId, itmcode, itmName, qty);
shipItems.add(shpItems);
}
Since this throws the NPE:
calRecvDate.getDate()==null
The calRecvDate variable is null, and you will either need to check if it's null before using it, or make sure that it isn't null by tracing back in your code to where you think you've initialized it and fix the problem (since it isn't initialized).
To check if it's null, you could do:
if (calRecvDate != null) {
// use the calRecvDate variable here
} else {
// initialize the calRecvDate variable here
// or perhaps better, display a JOptionPane error message to the user
// that the date hasn't been selected, and exit this method by calling return:
return;
}
Again, don't use try/catch blocks to handle NullPointerExceptions.

Categories