I've added a return statement to my AsncTask and yet I still get an error telling me to add one. The only snippet of code that stops this Syntax error is adding a return statement after the catch statement, but that's counter productive and doesn't address the needs of the program and I can't access the Strings I need to ( I need to check if the return OuputStream is equal to true.
Code:
#Override
protected Boolean doInBackground(String... userandpass) { //I still get an error telling me to add a return statement
// TODO Auto-generated method stub
URL url;
try {
url = new URL("http://127.0.0.1:1337");
HttpURLConnection URLconnection = (HttpURLConnection) url.openConnection();
URLconnection.setDoOutput(true);
URLconnection.setChunkedStreamingMode(0);
//output stream
OutputStream out = new BufferedOutputStream(URLconnection.getOutputStream());
writestream(out, userandpass);
//buffered server response
InputStream in = new BufferedInputStream(URLconnection.getInputStream());
String result = readstream(in);
Log.e(result, result);
// check we haven't been redirected (Hotel Wifi, for example).
checkrediect(URLconnection, url);
Boolean result_true = checkresult(result);
if(result_true) {
return true;
} else {
return false;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
but that's counter productive and doesn't address the needs of the program
Well what are the "needs of the program"? What do you want the result to be if an IOException is thrown? It must be true, false, or an exception - at the moment, it's none of those.
I'd recommend that most of the time, you just let exceptions bubble up... can you actually proceed as if nothing had gone wrong in the case of an IOException?
As a side-note, this is ugly:
if(result_true) {
return true;
} else {
return false;
}
Just use:
return checkresult(result);
(And ideally rename various methods and variables to follow Java naming conventions.)
I'd also suggest changing it to return boolean rather than Booelean.
You have a branch of your catch statement that neither returns a value nor throws an exception.
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
That block there needs to have some form of code that will return something, otherwise the method will not be able to function properly.
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
You have to add a return statement with in the method block.
Do it like this....
protected Boolean doInBackground(String... userandpass) {
boolean isOk = false;
// Your code
if(result_true) {
isOk = true;
} else {
isOk = false;
}
return isOk;
}
You must had a return statement in the catch (IOException e) block. The compiler cannot know what to return when you catch the IOException.
You have 2 choices, return something (false), or rethrow the exception.
Related
i am facing a problem regrading specifying the return data type. I have the FOComp class which implements callabale, the call() method of the 'FOComp' returns data type List<ArrayList<Mat>> as shown in the code of 'FOComp' class below.
and the method 'getResults()' returns data of type ArrayList<Mat> as shown in the code below. and currently, at run time, when I execute the code, I receive the folowing error:
Multiple markers at this line
The return type is incompatible with Callable<ArrayList<Mat>>.call()
The return type is incompatible with Callable<List<Mat>>.call()
kindly please let me know how to fix it.
'FOComp' class:
static class FOComp implements Callable<List<Mat>> {//should return list contains 4 mats(0,45,90,135)
private ArrayList<Mat> gaussianMatList = null;
private List<ArrayList<Mat>> results_4OrientAngles_List = null;
public FOComp(ArrayList<Mat> gaussianMatList) {
// TODO Auto-generated constructor stub
this.gaussianMatList = gaussianMatList;
this.results_4OrientAngles_List = new ArrayList<ArrayList<Mat>>();
}
public List<ArrayList<Mat>> call() throws Exception {
// TODO Auto-generated method stub
try {
featOrient = new FeatOrientation(this.gaussianMatList);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
featOrient.start();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.results_4OrientAngles_List.add(featOrient.getResults());
return results_4OrientAngles_List;
}
}
'getResults':
public ArrayList<Mat> getResults() {
if (this.crossAddOrientMapsList != null) {
if (!this.crossAddOrientMapsList.isEmpty()) {
if (this.crossAddOrientMapsList.size() == 4) {
double[] theta = new double[4];
theta[0] = 0;
theta[1] = 45;
theta[2] = 90;
theta[3] = 135;
for (int i = 0; i < this.crossAddOrientMapsList.size(); i++) {
MatFactory.writeMat(FilePathUtils.newOutputPath("FinalCrossAdd_" + theta[i]+"_degs"), this.crossAddOrientMapsList.get(i));
//ImageUtils.showMat(this.crossAddOrientMapsList.get(i), "OrientMap_" + theta[i] + " degs");
}
return this.crossAddOrientMapsList;
} else {
Log.WTF(TAG, "getResults", "crossAddOrientMapsList != 4 !!");
return null;
}
} else {
Log.E(TAG, "getResults", "crossAddOrientMapsList is empty.");
return null;
}
} else {
Log.E(TAG, "getResults", "crossAddOrientMapsList is null");
return null;
}
}
class FOComp implements Callable<List<Mat>>
and
public List<ArrayList<Mat>> call()
aren't really compatible... Your call() method should be
#Override public List<Mat> call()
Also, it is good practice to avoid implementation classes in method signatures, use the interfaces instead (in this case, use List rather than ArrayList). That will also fix your problem with one of the "multiple markers" :-)
Cheers,
You class declaration says that you are going to return a List of Mat (FOComp implements Callable<List<Mat>>), but your call method signature says you are going to return a List of ArrayList of Mat (List<ArrayList<Mat>>).
You will need to make them consistent.
I seem to be stuck with a very simple task that would require GOTO statements and, in my opinion, would justify a use of those.
I have the very simple task to exit a void on different conditions. Within its code, several dozen operations are being done and most of them can fail. I test them with try {}.
Now, based on the criticality of the operation, I either need to exit immediately and do nothing else, or, I just need to interrupt control flow and jump to a final point to do some cleaning up and then exit the method.
MWE:
public void myMethod () {
try { op1(); } catch (Exception e) { return; } // Fail here: exit immediately
try { op2(); } catch (Exception e) { cleanUpFirst(); return; } // Fail here: do Cleaning up first, then exit
try { op3(); } catch (Exception e) { return; } // Fail here: exit immediately
try { op4(); } catch (Exception e) { cleanUpFirst(); return; } // Fail here: do Cleaning up first, then exit
try { op5(); } catch (Exception e) { cleanUpFirst(); return; } // Fail here: do Cleaning up first, then exit
// ....
}
public void cleanUpFirst() { /* do something to clean up */ }
For code readability, I'd like to a) avoid a separate function and b) do not have more than one statement within the catch block; it just blows up the code. So, in my opinion this would perfectly justify the use of a GOTO statement.
However, the only solution I came up with, given that only two outcomes are possible, is this:
public void myMethod () {
do {
try { op1(); } catch (Exception e) { return; }
try { op2(); } catch (Exception e) { break; }
try { op3(); } catch (Exception e) { return; }
try { op4(); } catch (Exception e) { break; }
try { op5(); } catch (Exception e) { break; }
// ....
} while (1==0);
/* do domething to clean up */
}
Yes, I have heard of exceptions and that is is the Java way. Is that not as overkilled as using the separate void? I do not need the specifics, I simply need a yes/no result from each operation. Is there a better way?
why not
boolean cleanupfirst = false;
try {
op1 ();
cleanupfirst = true;
op2 ();
cleanupfirst = false;
op3 ();
} catch (Exception e) {
if (cleanupfirst)
cleanup ();
return;
}
You're over-thinking it.
4 minor adjustments.
Let Opn() return a boolean for success or failure, rather than throwing an Excpetion.
Let CleanupFirst handle program termination (you can rename it to clean exit if you want). The new parameter passed to CleanExit is the System.exit code.
Use System.Exit to return a proper return code to the OS, so you can use it in scripting.
It does not seem like your program has a successful path.
if (!op1())
System.exit(1); // <- send a failed returncode to the OS.
if(!op2())
cleanExit(2);
if (!op3())
System.exit(3); // <- send a failed returncode to the OS.
if (!op4())
cleanExit(4);
if (!op5())
cleanExit(5);
cleanExit(0);
More methods for better readability:
public void myMethod() {
try {
tryOp1();
tryOp2();
...
} catch(Exception ignore) {}
}
public void tryOp1() throws Exception {
op1();
}
public void tryOp2() throws Exception {
try {
op1();
} catch (Exception e) {
cleanUp();
throw e;
}
}
I'm trying to load the radio version of the Android device using reflection. I need to do this because my SDK supports back to API 7, but Build.RADIO was added in API 8, and Build.getRadioVersion() was added in API 14.
// This line executes fine, but is deprecated in API 14
String radioVersion = Build.RADIO;
// This line executes fine, but is deprecated in API 14
String radioVersion = (String) Build.class.getField("RADIO").get(null);
// This line executes fine.
String radioVersion = Build.getRadioVersion();
// This line throws a MethodNotFoundException.
Method method = Build.class.getMethod("getRadioVersion", String.class);
// The rest of the attempt to call getRadioVersion().
String radioVersion = method.invoke(null).toString();
I'm probably doing something wrong here. Any ideas?
Try this:
try {
Method getRadioVersion = Build.class.getMethod("getRadioVersion");
if (getRadioVersion != null) {
try {
String version = (String) getRadioVersion.invoke(Build.class);
// Add your implementation here
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Log.wtf(TAG, "getMethod returned null");
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
What Build.getRadioVersion() actually does is return the value of gsm.version.baseband system property. Check Build and TelephonyProperties sources:
static final String PROPERTY_BASEBAND_VERSION = "gsm.version.baseband";
public static String getRadioVersion() {
return SystemProperties.get(TelephonyProperties.PROPERTY_BASEBAND_VERSION, null);
}
According to AndroidXref this property is available even in API 4. Thus you may get it on any version of Android through SystemProperties using the reflection:
public static String getRadioVersion() {
return getSystemProperty("gsm.version.baseband");
}
// reflection helper methods
static String getSystemProperty(String propName) {
Class<?> clsSystemProperties = tryClassForName("android.os.SystemProperties");
Method mtdGet = tryGetMethod(clsSystemProperties, "get", String.class);
return tryInvoke(mtdGet, null, propName);
}
static Class<?> tryClassForName(String className) {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
return null;
}
}
static Method tryGetMethod(Class<?> cls, String name, Class<?>... parameterTypes) {
try {
return cls.getDeclaredMethod(name, parameterTypes);
} catch (Exception e) {
return null;
}
}
static <T> T tryInvoke(Method m, Object object, Object... args) {
try {
return (T) m.invoke(object, args);
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getTargetException());
} catch (Exception e) {
return null;
}
}
Not sure if this has already been answered, but.
I know that in java there is the try, catch and finally blocks, but is there one which is only called if try has no errors/exceptions?
Currently after stating the command that needs to be run, I'm setting a boolean to true, and after the try and catch block, the program checks for if the boolean is true.
I'm pretty sure that there is a much simpler way, help is appreciated!
Just put your code after the try...catch block and return in the catch:
boolean example() {
try {
//dostuff
} catch (Exception ex) {
return false;
}
return true;
}
This would also work if you put the return true at the end of the try block as the code would jump to the catch on error and not execute the rest of the try.
void example() {
try {
//do some stuff that may throw an exception
//do stuff that should only be done if no exception is thrown
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
No, there is no block called only if no exceptions were raised.
The catch block is called if there were exceptions, finally is called regardless.
As stated, you can emulate such a beast with something like:
bool completed = false;
try {
doSomeStuff();
completed = true;
} catch (Exception ex) {
handleException();
} finally {
regularFinallyHandling();
if (completed) {
thisIsTheThingYouWant();
}
}
but there's nothing built into the language itself that provides this functionality.
i'm struggling with a JSONObject. I allready returned some json and converted it succesfully to objects and list of objects. My now i'm stuck.
This is the JSONObject i'm getting:
{"Result":true,"Messages":["Goe bezig!"]}
I'm able to get the Messages, but i can't seem to get the boolean in Result. Can somebody explain how to get it plz?
Here is the code:
public boolean Convert(JSONObject json) {
try
{
return json.getBoolean("Result");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
This worked fine for me, although it's pretty vague your question.
String jsonString = "{\"Result\":true,\"Messages\":[\"Goe bezig!\"]}";
JSONObject jsonObject = new JSONObject(jsonString);
boolean result = (Boolean) jsonObject.get("Result");
System.out.println(result);
You might want to catch at the end of your method Exception as well:
try {
return json.getBoolean("Result");
} catch (JSONException e) {
e.printStackTrace(); // replace these with `Log` statement
return false;
} catch (Exception e) {
e.printStackTrace(); // replace these with `Log` statement
return false;
}