Why does it go to exception when parse to integer? - java

I canĀ“t figure out why this Integer.parseInt makes an exception, its a NullpointerException..
try
{
int numberOfPictures = Integer.parseInt(editTextNumberOfGames
.getText().toString());
Toast toast =Toast.makeText(getBaseContext(), "ratt", Toast.LENGTH_SHORT);
toast.show();
} catch (Exception e)
{
Toast toast =Toast.makeText(getBaseContext(), "fel", Toast.LENGTH_SHORT);
toast.show();
}

Have you used a debugger to verify that editTextNumberOfGames is not null when you get to this code?
You can temporary break up the Integer.parseInt(editTextNumberOfGames.getText().toString()) statement to see exactly which part of the compound statement is causing the exception.
See http://developer.android.com/reference/java/lang/Integer.html

As ratchet freak pointed out in comments, i had not done this:
editTextNumberOfGames = (EditText)findViewById(R.id.editTextNrOfPictures);
Thanks for all help though.

It throws an expecption because editTextNumberOfGames is null
initialize editTextNumberOfGames correctly, or if for whatever reason you cannot garuantee, that it is initialized then
int numberOfPictures;
if (editTextNumberOfGames != null) {
numberOfPictures = Integer.parseInt(editTextNumberOfGames.getText());
}

Related

I am not able to toast messages in Android Studio

I have created an add button. No data is entered in the EditText field and when the user press the button I am not able to Toast the message.
If(text1.getText( ).toString( ).matches(" ") || text2.getText( ).toString( ).matches(" "))
{
Toast.makeText(MainActivity.this,"input values",Toast.LENGTH_SHORT.show( );
}
you can try this
EditText usernameEditText = (EditText) findViewById(R.id.editUsername);
sUsername = usernameEditText.getText().toString();
if (sUsername.matches("")) {
Toast.makeText(MainActivity.this, "You did not enter a username", Toast.LENGTH_SHORT).show();
}
You are matching wrong string. Instead of .match(" ") use .match("") or it is better to use text1.getText().toString().isEmpty(). In fact your if block never reached.
Try changing your code and IF condition like this:
If (String.valueOf(text1.getText()).equals("") || String.valueOf(text2.getText()).equals(""))
{
Toast.makeText(MainActivity.this,"input values",Toast.LENGTH_SHORT).show();
}
That's all,
Hope it helps :)
Use trim() this function will remove spaces.
If(text1.getText( ).toString( ).trim().equals("") || text2.getText( ).toString.trim().equals(""))
{
Toast.makeText(MainActivity.this,"You did not enter a username and password",Toast.LENGTH_SHORT.show( );
}
I hope this will helpful.

Java show me long error but missing in my log file

Hi all I know its a stupid question but I'm trying everything.
My game server show me a very long error which is too long for console and can see the top of it, but it is missing from my log and I can't see the details of this error.
Can somebody help me on how can I capture that error:
private void fix(L2PcInstance pl, int playerPoints)
{
try
{
IAchievement arc = Achievements.getInstance().GetAchivment(_id, pl.getAchivmentLevelbyId(_id) + 1);
if ((arc != null) && (playerPoints > arc.getNeedPoints()))
{
Achievements.getInstance().reward(pl, arc);
fix(pl, playerPoints);
}
}
catch (Exception e)
{
_log.error(getClass().getSimpleName() + ": Error in fix: " + e);
}
}
the error
the line 96 is
fix(pl, playerPoints);
but the error is missing from my log im try to capture the console to txt file from command
java myserver.jar > capturemyconsole.txt but again it's showing error in console that the txt is missing. How is this possible ? Thanks for your time and help :)
and sorry for my bad english :(
You method fix calls itself, with the same arguments, causing stack overflow...
Should add some modification to the arguments, or some more condition to the recursion...
You can catch "Error" instead of "Exception" and then log
[...] catch (Error e)
{
_log.error(getClass().getSimpleName() + ": Error in fix: " + e, e);
}
In Your current code StackOverflowException (which is not a child of Exception) is propagated without going into catch block. Remember to put additional "e" parameter to log full stacktrace.
It's not a good practice to catch Error, but it'll answer Your question.
More info: try/catch on stack overflows in java?

AssertTrue in try/catch

Please what exactly am i doing wrong.
I have checked and checked but all to no avail.
I have also checked previous code but I am not getting an error so my code works fine but just slight error somewhere.
The code is running fine and assertTrue is behaving as expected but when I put it in the try/catch, I only get the log in the catch block, even when text was found.
I believe that if the assertTrue found the text, it should go to the next line of code in the try block and pass the test rather than the catch block. Don't get me wrong, I am not getting any error just that it's printing out the wrong message.
Code below including print out message in console.
public boolean verifyTextPresent(String value) throws Exception {
Thread.sleep(5000);
try{
boolean txtFound = driver.getPageSource().contains(value);
log.log(value + " : text Found, .......continue");
return txtFound;
}catch(Exception e)
{
log.log(value + " :NOT Found, check element again ot Contact developer.");
return false;
}
}
public static void verifySignOutBtn() throws Exception
{
log.header("VERIFY IF SIGN_OUT EXIST AND CLICKABLE.........");
callMethod.myAccountPageNative(CONSTANTElements.SIGN_IN_LINK);
Thread.sleep(2000);
log.header("LOCATE SIGN_OUT BTN, AND CLICK ......");
callMethod.elementPresent_Click(By.cssSelector(CONSTANTElements.SIGN_OUT_BTN));
Thread.sleep(4000);
log.header("VERIFY SIGN_OUT NAVIGATES TO HOME PAGE WHEN CLICKED......");
try{
Assert.assertTrue(callMethod.verifyTextPresent("SIGN IN"), "SIGN IN");
log.log("User Successfully Signed Out.......");
log.log("Test Passed!...");
//callMethod.close();
}
catch(Throwable e)
{
log.log("User NOT Successfully Signed Out.... Contact developer.");
log.log("Test Failed!...");
//callMethod.close();
}
callMethod.close();
}
}
Msg in console:
SIGN IN : text Found, .......continue
User NOT Successfully Signed Out.... Contact developer.
Test Failed!...
The confusing part is that why is it printing out the catch block instead of the next line in the try block?
Shouldn't it be the other way around?
Assert.assertTrue("Message if it is false", callMethod.verifyTextPresent("SIGN IN"));
The only possible explanation is that verifyTextPresent(String value) returns false (you never actually check the value of boolean txtFound) and assertTrue fails (throwing an AssertionError which is not handled well in your catch block). To find out, replace this
log.log(value + " : text Found, .......continue");
for example with this line
log.log(value + " : text Found, ......." + txtFound);
or just print the stacktrace in catch block.

java check condition after clicking on save button before commit

i want to put if else or switch statement which is more suitable for checking employee count before commit.where i put my if else or switch code . i want restriction on employee if count is 5 then its show message "reached maximum employee limites" otherwise allow commit.
i am new in java plz someone help me to solve this
public String cmdSave_action()
{
// my code before
{
DeptSet result;
try {
dbo.connect();
result =
dbo.execSQL("select count(*) from empmasterinfo where mainid='ORGElement' and designationid='?') "
(inputText_ORGElement.getValue() != null ?
""));
result = dbo.execSQL(sSQL);
catch (Exception e) {
System.out.println(e.getMessage());
finally
{
dbo.close();
}
return null;
}}}
// my code above
{
Global.PerformIteratorAction(this.bindings, "Commit");
AdfFacesContext afContext = AdfFacesContext.getCurrentInstance();
afContext.getProcessScope().put("EmployeeID",
Global.getCurrRowFieldValue("EmpmasterinfoViewIterator",
"Employeeid"));
if (afContext.getProcessScope().get("AddEdit").toString().equals("0"))
{
Global.PerformIteratorAction(this.bindings,
"EPR_TRANSFER_APPLICANT_INFO");
Global.PerformIteratorAction(this.bindings, "eprGenerateApPlan");
}
return null;
}}
My Error Log
Error(149,12): 'try' without 'catch' or 'finally'
Error(154,36): , expected
Error(157,34): field SQL not found in class hcm.view.backing.empprofile.EmployeeMasterInfo_Add
Error(159,11): illegal start of expression
Error(159,11): ; expected
E:\HCM\ViewController\src\hcm\view\backing\empprofile\dbo.java
Error(13,16): method does not return a value
Please close Your try catch block properly
try{
}catch(Exception e){
}finally{
}
And Read this
catch and finally are within try block
try {
//code
}
catch(Exception e) {
System.out.println(e.getMessage());
}
finally {
dbo.close();
}
Using an IDE will help you with indentation and proper formatting while writing code. e.g Eclipse.
For the first error close the try-catch blocks properly
And for the second error: Since your method is declared as public String cmdSave_action(), you should return a String value at the end of the method. The return statement is missing in your code.

PMD rules: How to properly solve this DD-anomaly issue

I have the following Android code:
public final List<MyObj> getList() {
Cursor cursor = null;
try {
final String queryStr = GET_LIST_STATEMENT;
cursor = db.rawQuery(queryStr, new String[] {});
List<MyObj> list = null;
//here I get the data from de cursor.
return list ;
} catch (SQLiteFullException ex) {
//do something to treat the exception.
} finally {
if (cursor != null) {
cursor.close();
}
}
}
When I run PMD analysis over this code, I get the following issue: Found 'DD'-anomaly for variable 'cursor' (lines '182'-'185').
The line 182 is: Cursor cursor = null;.
The line 185 is: cursor = db.rawQuery(queryStr, new String[] {});
So, I understand that the problem is that I'm doing a Premature Initialization in the line 182 (I never read the variable between the lines 182 and 185), but if I don't do that, I can't have the code closing the cursor in the finally block.
What to do in this case? Just ignore this PMD issue? Can I configure PMD to don't rise up this specific kind of DD-anomaly (not all DD-anomaly)? Should PMD be smart enough to doesn't rise up this issue?
Another example of DD-anomaly that I think is not a real problem:
Date distributeDate;
try {
distributeDate = mDf.parse(someStringDate);
} catch (ParseException e) {
Log.e("Problem", "Problem parsing the date of the education. Apply default date.");
distributeDate = Calendar.getInstance().getTime();
}
In this case, the anomaly occurs with the distributeDate variable.
The documentation is pretty easy to understand:
Either you use annotations to suppress warnings:
// This will suppress UnusedLocalVariable warnings in this class
#SuppressWarnings("PMD.UnusedLocalVariable")
public class Bar {
void bar() {
int foo;
}
}
or you use a comment:
public class Bar {
// 'bar' is accessed by a native method, so we want to suppress warnings for it
private int bar; //NOPMD
}
When it comes to your specific code, I'd say that the easiest way to handle it is to not use a finally block even though this would look like the perfect place for it.

Categories