nullpointerexception in a for and if statement - java

I want to find 'elements in an array wjoined' which are not included in an array cjoined.
I cannot find what is wrong. Please help me. Following is my code. LogCat says 'Caused by:java.lang.NullPointerException'.
for (int x = 0; x < wjoined.length; x++)
{
int count1 = 0;
for (int y = 0; y < cjoined.length; y++)
{
if (wjoined[x].equals(cjoined[y]) )
{
count1++;
}
}
if (count1 == 0){
String sql = "INSERT INTO ErrorCausingFactor (errorcausingelement)"+"VALUE('"+wjoined[x] +"')";
db.execSQL(sql);
}
}
This is my logcat.
08-30 13:34:02.618: W/dalvikvm(1150): threadid=1: thread exiting with
uncaught exception (group=0x40014760) 08-30 13:34:02.628:
E/AndroidRuntime(1150): FATAL EXCEPTION: main 08-30 13:34:02.628:
E/AndroidRuntime(1150): java.lang.RuntimeException: Unable to start
activity
ComponentInfo{com.demo.testdemo/com.demo.testdemo.NextActivity}:
java.lang.NullPointerException 08-30 13:34:02.628:
E/AndroidRuntime(1150): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1748)
08-30 13:34:02.628: E/AndroidRuntime(1150): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1764)
08-30 13:34:02.628: E/AndroidRuntime(1150): at
android.app.ActivityThread.access$1500(ActivityThread.java:122) 08-30
13:34:02.628: E/AndroidRuntime(1150): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1002)
08-30 13:34:02.628: E/AndroidRuntime(1150): at
android.os.Handler.dispatchMessage(Handler.java:99) 08-30
13:34:02.628: E/AndroidRuntime(1150): at
android.os.Looper.loop(Looper.java:132) 08-30 13:34:02.628:
E/AndroidRuntime(1150): at
android.app.ActivityThread.main(ActivityThread.java:4025) 08-30
13:34:02.628: E/AndroidRuntime(1150): at
java.lang.reflect.Method.invokeNative(Native Method) 08-30
13:34:02.628: E/AndroidRuntime(1150): at
java.lang.reflect.Method.invoke(Method.java:491) 08-30 13:34:02.628:
E/AndroidRuntime(1150): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
08-30 13:34:02.628: E/AndroidRuntime(1150): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599) 08-30
13:34:02.628: E/AndroidRuntime(1150): at
dalvik.system.NativeStart.main(Native Method) 08-30 13:34:02.628:
E/AndroidRuntime(1150): Caused by: java.lang.NullPointerException
08-30 13:34:02.628: E/AndroidRuntime(1150): at
com.demo.testdemo.NextActivity.onCreate(NextActivity.java:157) 08-30
13:34:02.628: E/AndroidRuntime(1150): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
08-30 13:34:02.628: E/AndroidRuntime(1150): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1712)
08-30 13:34:02.628: E/AndroidRuntime(1150): ... 11 more

Whenever you see an Exception in the log it states the exact line where the error occurs. You should look into that. Not knowing the line i suspect either wjoined, cjoined or db is null
EDIT: seeing your log the error is on line 157 of NextActivity.java. See what that is and you probably know what's wrong

Your locat should give you more details than just the exception, there will also be a stacktrace that should give you an indication on which line the NPE occured.
In your code I can see 3 possible locations to have an NPE being thrown:
In case wJoined is null then you will get an NPE thrown at the line number of your first for statement
In case cJoined is null then you will get an NPE thrown at the line number of your second for loop
if your database object db is null then you will get an NPE where you execute the insert statement.
Just inspect your stacktrace:
Caused by: java.lang.NullPointerException 08-30 13:34:02.628: E/AndroidRuntime(1150): at com.demo.testdemo.NextActivity.onCreate(NextActivity.java:157)
EDIT: 4. is wJoined[x] is null this also raises an NPE as indicated by Roddy the frozen peas :-)
So it is on line 157 where the error occurs

Some of the values are null. Try this:
if (wjoined != null)
{
for (int x = 0; x < wjoined.length; x++)
{
int count1 = 0;
if (cjoined != null && wjoined[x] != null)
{
for (int y = 0; y < cjoined.length; y++)
{
if (cjoined[y] != null)
{
if (wjoined[x].equals(cjoined[y]) )
{
count1++;
}
} else {
System.out.println("cjoined[y]" is null at: " + y);
}
}
if (count1 == 0){
String sql = "INSERT INTO ErrorCausingFactor (errorcausingelement)"+"VALUE('"+wjoined[x] +"')";
if (db != null)
db.execSQL(sql);
else
System.out.println("db is null!");
}
} else {
System.out.println("cjoined or wjoined[x] at x: " + x + " is null!");
}
}
} else {
System.out.println("wjoined is null!");
}

Related

Getting java.util.NoSuchElementException with Iterator.next() while using the libphonenumber

code :
public void extractPhoneNumber(String input){
Iterator<PhoneNumberMatch> existsPhone= PhoneNumberUtil.getInstance().findNumbers(input, "IN").iterator();
while (existsPhone.hasNext()){
System.out.println("Phone == " + existsPhone.next().number());
Log.d("existsPhone",":"+existsPhone.next().rawString());
gotPhone.setText(existsPhone.next().rawString());
}
}
Log :
2019-06-11 16:23:43.059 11176-11176/com.example.cardscaning E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cardscaning, PID: 11176
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cardscaning/com.example.cardscaning.Activity.ProcessImage}: java.util.NoSuchElementException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2678)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2743)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1490)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6165)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
Caused by: java.util.NoSuchElementException
at com.google.i18n.phonenumbers.PhoneNumberMatcher.next(PhoneNumberMatcher.java:710)
at com.google.i18n.phonenumbers.PhoneNumberMatcher.next(PhoneNumberMatcher.java:43)
at com.example.cardscaning.Activity.ProcessImage.extractPhoneNumber(ProcessImage.java:291)
at com.example.cardscaning.Activity.ProcessImage.onCreate(ProcessImage.java:97)
at android.app.Activity.performCreate(Activity.java:6687)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2631)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2743) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1490) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6165) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778) 
Inside log I can get desire result but exception occurs when I am adding this line gotPhone.setText(existsPhone.next().rawString())
Desirable outcome is able use extracted number.
You are calling next() thrice in one iteration forcing the Iterator to move to an element that doesn't exist.
Instead of:
while (existsPhone.hasNext()){
System.out.println("Phone == " + existsPhone.next().number());
Log.d("existsPhone",":"+existsPhone.next().rawString());
//...
}
Use something like:
while (existsPhone.hasNext()){
PhoneNumberMatch phone = existsPhone.next();
System.out.println("Phone == " + phone.number());
Log.d("existsPhone",":"+phone.rawString());
//....
}

Remove extra dots in float value before a separater " , " occurs using java

I am generating a statistical calculator application.
So I want to format input from edittext like this
i/p = 3.5.6, 6.5 to 3.5 , 6.5
Using " , " (comma) as separator so splitting the input string to float array when a " , " occurs.
I want to ignore 3.5[.6] and generate array like this
s[1] = 3.5 , s[2] = 6.5
While calculating mean application crashes due to extra " . " dots.
s = it.getText().toString(); //"it" is edittext
s=s.replaceAll( ",+" , "," );
String[] strarray =s.split(",");
float[] farray = new float[strarray.length];
for(int i = 0; i < strarray.length; i++)
{
farray[i] = Float.parseFloat(strarray[i]);
}
--DEBUG LOGCAT--
W/dalvikvm(3051): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
FATAL EXCEPTION: main
java.lang.NumberFormatException: Invalid float: "6.7."
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseFloat(StringToReal.java:310)
at java.lang.Float.parseFloat(Float.java:300)
at com.cal.mc2.Mean$1.onClick(Mean.java:67)
at android.view.View.performClick(View.java:4204)
at android.view.View$PerformClick.run(View.java:17355)
at android.os.Handler.handleCallback(Handler.java:725)`
`at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Force finishing activity com.cal.mc2/.Mean
How about this simple function (IdeOne link here: https://ideone.com/utKPjP):
public static float myParseFloat(String str) {
int firstDot = str.indexOf('.');
if (firstDot != -1) {
int secondDot = str.indexOf('.', firstDot+1);
return Float.parseFloat(secondDot == -1 ? str : str.substring(0,secondDot));
}
return Float.parseFloat(str);
}
Then you just replace this statement in your code:
farray[i] = Float.parseFloat(strarray[i]);
with:
farray[i] = myParseFloat(strarray[i]);
You can use regex like this :
public static void main(String[] args) {
String s = "3.5.6, 6.5";
s = s.replaceAll("(?<=\\d\\.\\d)\\.\\d", "");// positive look behind. Only replace `.[digit]` if it is preceeded by [digit][.][digit]
System.out.println(s);
String[] arr = s.split(",");
System.out.println(Arrays.toString(arr));
}
O/P :
3.5, 6.5 --> value of s after replacement
[3.5, 6.5] --> array contents

Strange runtime exception on Android 4.4.4

I've got this strange stack trace from Flurry Analytics and I have no idea where it comes from. All the classes are from android system and not a single line that tells me where it comes from.
This error happened 3 times on a same device with android 4.4.4
Any ideas? Thanks.
java.lang.RuntimeException
android.app.ActivityThread.performResumeActivity(ActivityThread.java:2836)
android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2865)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2291)
android.app.ActivityThread.access$800(ActivityThread.java:144)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:212)
android.app.ActivityThread.main(ActivityThread.java:5135)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
dalvik.system.NativeStart.main(Native Method)
Caused by: android.app.ActivityThread.deliverResults(ActivityThread.java:3455)
android.app.ActivityThread.performResumeActivity(ActivityThread.java:2823)
android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2865)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2291)
android.app.ActivityThread.access$800(ActivityThread.java:144)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:212)
android.app.ActivityThread.main(ActivityThread.java:5135)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:877)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
dalvik.system.NativeStart.main(Native Method)
Part of the problem here seems to be that Flurry error reporting is leaving out important information.
Anyhow, this is where I think the exception is coming from:
private void deliverResults(ActivityClientRecord r, List<ResultInfo> results) {
final int N = results.size();
for (int i=0; i<N; i++) {
ResultInfo ri = results.get(i);
try {
if (ri.mData != null) {
ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
}
if (DEBUG_RESULTS) Slog.v(TAG,
"Delivering result to activity " + r + " : " + ri);
r.activity.dispatchActivityResult(ri.mResultWho,
ri.mRequestCode, ri.mResultCode, ri.mData);
} catch (Exception e) {
if (!mInstrumentation.onException(r.activity, e)) {
throw new RuntimeException(
"Failure delivering result " + ri + " to activity "
+ r.intent.getComponent().toShortString()
+ ": " + e.toString(), e);
}
}
}
}
(This code isn't from Android 4.4.4, but this particular method is identical in the versions I looked at ...)
It would seem that deliverResults is catching some exception it got further up the stack, and wrapping / resthoring it as a RuntimeException. At the point that the exception is constructed, it has a message, and cause. Whatever is generating the stacktrace has removed that information, and that is going to make diagnosis hard.

File for loop causing force close on Nexus 7, not SGS2?

When my app runs on my S2, it works perfectly with absolutely no errors, however when I try and run it on my Nexus 7 it force closes and I have no idea why it's happening on one device and not on another...
Here is the LogCat:
07-03 18:33:29.139: E/AndroidRuntime(11990): FATAL EXCEPTION: main
07-03 18:33:29.139: E/AndroidRuntime(11990): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.liamw.root.logeraser/com.liamw.root.logeraser.MainActivity}: java.lang.NullPointerException
07-03 18:33:29.139: E/AndroidRuntime(11990): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2312)
07-03 18:33:29.139: E/AndroidRuntime(11990): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
07-03 18:33:29.139: E/AndroidRuntime(11990): at android.app.ActivityThread.access$600(ActivityThread.java:156)
07-03 18:33:29.139: E/AndroidRuntime(11990): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1250)
07-03 18:33:29.139: E/AndroidRuntime(11990): at android.os.Handler.dispatchMessage(Handler.java:99)
07-03 18:33:29.139: E/AndroidRuntime(11990): at android.os.Looper.loop(Looper.java:137)
07-03 18:33:29.139: E/AndroidRuntime(11990): at android.app.ActivityThread.main(ActivityThread.java:5229)
07-03 18:33:29.139: E/AndroidRuntime(11990): at java.lang.reflect.Method.invokeNative(Native Method)
07-03 18:33:29.139: E/AndroidRuntime(11990): at java.lang.reflect.Method.invoke(Method.java:525)
07-03 18:33:29.139: E/AndroidRuntime(11990): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:799)
07-03 18:33:29.139: E/AndroidRuntime(11990): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
07-03 18:33:29.139: E/AndroidRuntime(11990): at dalvik.system.NativeStart.main(Native Method)
07-03 18:33:29.139: E/AndroidRuntime(11990): Caused by: java.lang.NullPointerException
07-03 18:33:29.139: E/AndroidRuntime(11990): at com.liamw.root.logeraser.FolderTools.folderSize(FolderTools.java:96)
07-03 18:33:29.139: E/AndroidRuntime(11990): at com.liamw.root.logeraser.FolderTools.folderSize(FolderTools.java:87)
07-03 18:33:29.139: E/AndroidRuntime(11990): at com.liamw.root.logeraser.MainActivity.initialize(MainActivity.java:194)
07-03 18:33:29.139: E/AndroidRuntime(11990): at com.liamw.root.logeraser.MainActivity.onCreate(MainActivity.java:131)
07-03 18:33:29.139: E/AndroidRuntime(11990): at android.app.Activity.performCreate(Activity.java:5167)
07-03 18:33:29.139: E/AndroidRuntime(11990): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
07-03 18:33:29.139: E/AndroidRuntime(11990): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2266)
07-03 18:33:29.139: E/AndroidRuntime(11990): ... 11 more
The 2 foldersize functions are:
public long folderSize() {
long length = 0;
for (File file : directory.listFiles()) {
if (file.isFile())
length += file.length();
else if (file != null)
length += folderSize(file);
}
return length;
}
and
public long folderSize(File directory) {
long length = 0;
for (File file : directory.listFiles()) {
if (file.isFile())
length += file.length();
else if (file != null)
length += folderSize(file);
}
return length;
}
Line 96:
for (File file : directory.listFiles()) {
(second function)
Line 87:
length += folderSize(file);
(first function)
I don't understand why this only happens on the one device though!
EDIT1:
Directory declaration:
directory = new File("/data/log");
(It's already defined as a global variable)
The directory doesn't exist on your Nexus 7 and so directory.listFiles() returns null and therefore the iterator throws an NPE.
Here's what the javadoc for File.listFiles() says:
An array of abstract pathnames denoting the files and directories
in the directory denoted by this abstract pathname.
The array will be empty if the directory is empty.
Returns null if this abstract pathname does not denote a directory,
or if an I/O error occurs.
A simple exists() would do the job but it won't cover the case where you don't have access to the directory, which will return Null as well. So best just check for listFiles() returning null and while doing that you consolidate your two methods into one:
public long folderSize(File directory) {
long length = 0;
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
length += file.isFile() ? file.length() : folderSize(file);
}
}
return length;
}
Now you just call this passing the directory along:
long size = folderSize(directory);
Also make sure you have the android.permission.READ_EXTERNAL_STORAGE permission defined in your manifest.

Android - java.lang.ArrayIndexOutOfBoundsException

I'm new to Java, but I have done some PSP coding in C before. This seems to be quite different.
Below is the stack trace for what I'm seeing:
java.lang.RuntimeException: An error occured while executing doInBackground()
enter code hereenter code here`at android.os.AsyncTask$3.done(AsyncTask.java:299)
enter code here`at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
at com.adev.abmp3.ViewSongDialog$FindLyrics.doInBackground(ViewSongDialog.java:173)
at com.adev.abmp3.ViewSongDialog$FindLyrics.doInBackground(ViewSongDialog.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
And here is the patch of code:
#Override
protected Void doInBackground(Void... arg0) {
String searchQuery = title.replaceAll("[^ \\w]", "");
searchQuery = searchQuery.replace(" ", "+");
String searchResult = httpRun("http://search.azlyrics.com/search.php?q="+searchQuery).toString();
System.out.println("http://search.azlyrics.com/search.php?q="+searchQuery);
if(!searchResult.contains("Sorry, no results") && !searchResult.equals("")) {
String link = searchResult.split("<table width=100%>")[1];
link = link.substring(link.indexOf("<a href=\""), link.indexOf("\" rel"));
link = link.replace("<a href=\"", "");
String lR = httpRun(link).toString();
if(lR != "" && lR.contains("<!-- start of lyrics -->")) {
lR = lR.substring(lR.indexOf("<!-- start of lyrics -->"), lR.indexOf("<!-- end of lyrics -->"));
lR = lR.replace("<!-- start of lyrics -->", "");
lyrics = lR;
} else {
fail = 1;
lyrics = "Couldn't find lyrics";
}
} else {
fail = 1;
lyrics = "Couldn't find lyrics";
}
return null;
}
I've done some research, and have read that you can't print to the screen within doInBackground - but I'm not sure where to go from here. Any help would be appreciated.
EDIT: java.lang.StringIndexOutOfBoundsException
in java.lang.String.startEndAndLength
Heres the new stack:
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.StringIndexOutOfBoundsException: length=7338; regionStart=537; regionLength=-538
at java.lang.String.startEndAndLength(String.java:593)
at java.lang.String.substring(String.java:1474)
at com.adev.abmp3.ViewSongDialog$FindLyrics.doInBackground(ViewSongDialog.java:174)
at com.adev.abmp3.ViewSongDialog$FindLyrics.doInBackground(ViewSongDialog.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
Your split call is returning an array of size 1, but you're trying to get the 2nd item in it (with the [1]). You have to account for the possibility that your split string isn't in the input.
String link = searchResult.split("<table width=100%>")[1];
The error is occuring there. Indices start at 0, and your split is returning an array of size 1, so element 1 is out of bounds, and hence the exception is thrown. If you change it to String link = searchResult.split("<table width=100%>")[0]; the exception will no longer be thrown.

Categories

Resources