Android: NullPointerException: Attempt to invoke virtual method 'boolean [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am getting the following error:
*E/AndroidRuntime: FATAL EXCEPTION: main
Process: xxx.mxxxa.xxx, PID: 10610
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.contains(java.lang.CharSequence)' on a null object reference*
on the following lines:
public void onLoadResource (WebView view, String url) {
if (datingView.getUrl().contains("messages.php") && datingView.getUrl().contains("messages.php" +
"")){
bannerReklam.setVisibility(View.GONE);
}else if (datingView.getUrl().contains("upgrade.php") && datingView.getUrl().contains("upgrade.php" +
"")){
bannerReklam.setVisibility(View.GONE);
}else if (datingView.getUrl().contains("index.php") && datingView.getUrl().contains("index.php" +
"")){
bannerReklam.setVisibility(View.GONE);
}else if (datingView.getUrl().contains("join.php") && datingView.getUrl().contains("join.php" +
"") ){
bannerReklam.setVisibility(View.GONE);
}else{
bannerReklam.setVisibility(View.VISIBLE);
}
// if url contains string androidexample
// Then show progress Dialog
if (progressDialog == null && url.contains("instasquare")
) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(arkadasBulMain.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
This problem causes the application to stop. This error occurs for versions below android 9.0.

In some cases datingView.getUrl() return null. First try to check null and then try to search item using contains. For Example:
String datingUrl = datingView.getUrl();
if(datingUrl != null && datingUrl.contains("messages.php"))

Related

If condition is true, the function in if statement not execute and the application has stopped working

1) I was getting the address from the google map by tap on the map and store
the value with the code place = PlacePicker.getPlace(parentActivity, data);.
2) After I get the address store in place, I use the code String address[] = place.getAddress().toString().split(","); to split the address with comma.
3) After I have selected use this location, the application stopped working and closed, not even to run the locationAlertDialog(); method.
I got the error with the address[address.length-2] because it no value sometimes depend on user choosing the place where no have complete address, so I can manage with if, else condition for do checking, if the value is null I show the AlertDialog builder which allow user to enter manually.
Error:
java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=65537, result=-1, data=Intent { (has
extras) }} to activity: java.lang.ArrayIndexOutOfBoundsException:
length=1; index=-1
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1;
index=-1
Below is my code:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode== 1) {
place = PlacePicker.getPlace(parentActivity, data);
String address[] = place.getAddress().toString().split("\\,");
String location ;
if(address[address.length-2] == null || address[address.length-2].trim().isEmpty() || address[address.length-2].length() < 0 ){
locationAlertDialog(); **<---The function is not execute and the application stopped working**
}
else{
locationAlertDialog();
location = place.getName() + "," + address[address.length-2] + "," + address[address.length-1];
locationET.setText(location);
}
}else if (requestCode == Config.PICK_FILE_REQUEST) {
if (data == null) {
//no data present
return;
}
}
}
}
String address[] = place.getAddress().toString().split("\\,");
This means you are trying to split your address with \\, but what if your address does not contain \\, or has only one \\, match. In those cases your address[] will have 0 or 1 element only.
Afterwards,
if(address[address.length-2] == null || address[address.length-2].trim().isEmpty() || address[address.length-2].length() < 0 ){
in this line you are trying to access address[address.length-2]th element, which will not be present.
ArrayIndexOutOfBoundsException error means that you are trying access element which is not present in the array. example you have 5 elements & trying to fetch 6th one.

Java :: Caused by: java.lang.IllegalArgumentException: Comparison method violates its general contract [duplicate]

This question already has answers here:
Java error: Comparison method violates its general contract
(13 answers)
"Comparison method violates its general contract!"
(13 answers)
Closed 5 years ago.
FileStatus[] status = hdfs.listStatus(new Path(args[5] + "/" + typeOfFlow + "/" + args[4] + "/" + decileValue + "/"));
// you need to pass in your hdfs path
ArrayList<FileStatus> directories1 = new ArrayList<FileStatus>();
for (FileStatus f : status) {
if (f.isDir()) {
directories1.add(f);
}
}
FileStatus[] directories = directories1.toArray(new FileStatus[directories1.size()]);
Arrays.sort(directories, new Comparator<FileStatus>() {
public int compare(FileStatus o1, FileStatus o2) {
return (int) (o1.getModificationTime() - o2.getModificationTime());
}
});
I am getting below exception :
Caused by: java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeHi(TimSort.java:899)
at java.util.TimSort.mergeAt(TimSort.java:516)
at java.util.TimSort.mergeForceCollapse(TimSort.java:457)
at java.util.TimSort.sort(TimSort.java:254)
at java.util.Arrays.sort(Arrays.java:1438)
I made a test class and checked for any of two object null or object.getModeificationTime null but the stack trace is not same :
Exception in thread "main" java.lang.NullPointerException
at MyObject.getModificationTime(Main.java:45)
at Main$1.compare(Main.java:35)
at Main$1.compare(Main.java:33)
at java.util.TimSort.countRunAndMakeAscending(TimSort.java:355)
at java.util.TimSort.sort(TimSort.java:220)
at java.util.Arrays.sort(Arrays.java:1438)
I want to know what is the case I am getting exception at the first.

Error when trying to get a bundle from another activity [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm trying to retrieve a bundle from another activity but when I try this, the following error appears in my logs: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
The part of the code where I try to retrieve and show the bundle is this:
Bundle bundlefrankrijk = getIntent().getExtras();
int scorefrankrijk = bundlefrankrijk.getInt("finalScoreFrankrijk");
TextView highscoreLabelfranrkijk = (TextView) findViewById(R.id.highscorefrankrijk);
SharedPreferences settingsfrankrijk = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE);
int highScorefrankrijk = settingsfrankrijk.getInt("HIGH_SCORE", 0);
if (scorefrankrijk > highScorefrankrijk) {
highscoreLabelfranrkijk.setText("High Score : " + scorefrankrijk);
SharedPreferences.Editor editor = settingsfrankrijk.edit();
editor.putInt("HIGH_SCORE", scorefrankrijk);
editor.commit();
} else {
highscoreLabelfranrkijk.setText("High Score : " + highScorefrankrijk);
}
This is how I'm sending the intent to the current activity:
Intent i = new Intent(QuizActivityFrankrijk.this,
QuizResultaatFrankrijk.class);
Bundle bundlefrankrijk = new Bundle(0);
bundlefrankrijk.putInt("finalScoreFrankrijk", mScoreFrankrijk);
i.putExtras(bundlefrankrijk);
QuizActivityFrankrijk.this.finish();
startActivity(i);
Thanks in advance!
Better if you could post the code to see how you are sending the intent with extras to current activity too, for what I´m seeing here, the error is in this line:
Bundle bundlefrankrijk = getIntent().getExtras(); // is returning null object
And when youre trying to:
int scorefrankrijk = bundlefrankrijk.getInt("finalScoreFrankrijk"); // NullPointerException throwed
Cause your bundle is null from beginning, you should check if you´re sending correctly the intent with extras, please use the method:
mIntent.putExtra("key", intValue)
and check that youre receiving it like this:
if (getIntent().getExtras() != null){
getIntent().getExtras().getInt("key");}
or just like this too:
if (getIntent().getExtras() != null){
getIntent().getExtras().get("key");}
Remember, if the key is just different in some character, it will return NULL.
Please read this for more info: https://developer.android.com/reference/android/content/Intent.html

Failed to Execute if Block Statements just because of Condition Checking is always false in Android using JAVA? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
can someone please help me what wrong with below written "IF CODE" this is not coming inside block everytime even the values before if is logged in console.
if(userNameString == userInstance.getUsername() && passwordString == userInstance.getPassword())
Here is the complete code:
if(userInstance == null)
{
Log.i("no record found againse User Instance",""+userInstance);
Toast.makeText(getApplicationContext(),
"User Id and Password is wrong", Toast.LENGTH_SHORT).show();
getLoaderManager().destroyLoader(arg0.getId());
}
else
{
Log.i("Record found againse User Instance 1st",""+userInstance + "userName:" + userNameString +":pass:::"+passwordString);
if(userNameString == userInstance.getUsername() && passwordString == userInstance.getPassword())
{
Log.i("Record found againse User Instance 2nd",""+userInstance);
//Log.i("UserInstance else","" + userInstance);
SessionManager.saveLoginCredentials(context,userInstance.getUsername().toString(),userInstance.getPassword().toString());
Intent intent = new Intent(LoginActivityService.this,
ProposalListActivity.class);
startActivity(intent);
getLoaderManager().destroyLoader(arg0.getId());
}
}
Here is the LogCat:
02-04 22:36:39.150: I/on LoadFinished of Loader(14572): Name: kong,Password: f10343d1dc8d44c8935b356aa3f8aae2,First Name: Kong
02-04 22:36:39.150: I/Record found againse User Instance 1st(14572): Name: kong,Password: f10343d1dc8d44c8935b356aa3f8aae2,First Name: KonguserName:kong:pass:::kongkong
EDIT:
There was some logical problem the password i was getting from webservice is encoded instead of text and i was comparing the text with encoded value thats why the block of if statements were not executed.*
In String you must use String#equals() method for checking instead of ==.
Use following code:
if(userNameString.equals(userInstance.getUsername()) &&
passwordString.equals(userInstance.getPassword()))
use equals method instead of == to compare strings
if(userNameString.equals(userInstance.getUsername()) && passwordString.equals(userInstance.getPassword()))

How to put path in variable without getting null exception

Im trying to do the quick following:
lblNewLabel.setIcon(new ImageIcon(ItemDialog.class.getResource("/items/" + items.get(seed).getImage())));
however I am getting Null Pointer exception in the above line.
The program is running fine when I am using it in following manner.
lblNewLabel.setIcon(new ImageIcon(ItemDialog.class.getResource("/items/item10312344.jpeg")));
it works.
EDIT: seed is the index number (1 in this case). items.get(1).getImage() holds the value of item10312344.jpeg but as above I get a null exception. but if manually input it, it works
what do I need to do to make this not get a null exception by getting it from the item list?
Try to validate the object before calling "getImage"
//FIRST OF ALL: Make sure "items" is not null
if(items != null && items.get(seed) != null){
ItemDialog itemDialog = ItemDialog.class.getResource("/items/" + items.get(seed).getImage())
if(itemDialog != null)
lblNewLabel.setIcon(new ImageIcon(itemDialog));
}
/*I am not sure about of which type is the object items is carrying, but a more
decent approach would be*/
if(items != null){
"ObjectThatItemsIsCarrying" obj = items.get(seed);
//Checking if you got the image name
if(obj != null)
ItemDialog itemDialog = ItemDialog.class.getResource("/items/" + obj.getImage());
//Cheking if you got the image
if(itemDialog != null)
lblNewLabel.setIcon(new ImageIcon(itemDialog));
}
Put the path in a string and use the string in the getResource method.
String path = "/items/" + item.get(seed).getImage();

Categories