gpt4 book ai didi

java - Android 解析时出现空指针异常

转载 作者:行者123 更新时间:2023-12-01 13:15:45 25 4
gpt4 key购买 nike

编辑:我已经解决了问题,因为我没有在异步任务中实现解析内容,所以出现错误。不管怎样,谢谢你的回复!

我一直在尝试解析一个网站。当我将其作为 Java 项目执行时,它正常工作并返回给我一个干净的结果,但是当我尝试在 Android 中执行相同的操作时,它给出了 java.lang.NullPointerException。我使用的是 .jar 文件,认为问题可能出现在 jar 类内部,对其进行了反编译,但没有任何改变。这是类(class)。任何帮助将不胜感激。

PS:有一件奇怪的事情,当它是一个jar文件时,没有与类相关的错误,但是当我反编译它时,它在Keyboard类的第96行给了我错误,所以我把它注释掉了。

从现在起再次感谢大家。

标准IO类

package com.example.parsetester;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintStream;

public class StdIO
{
public static final String version = "StdIO:v1.0:15/12/2003";
static final String stdOutStreamName = "Screen";
static final String stdInStreamName = "Keyboard";
private static PrintStream origOut = System.out;
private static PrintStream stdout = null;
private static String outStreamName = "Screen";
private static InputStream origIn = System.in;
private static InputStream stdin = null;
private static String inStreamName = "Keyboard";

public static boolean exists(String paramString)
{
File localFile = new File(paramString);
return localFile.exists();
}

public static String getInStreamName()
{
return inStreamName;
}

public static void from(String paramString)
{
if (stdin != null) {
resetIn();
}
try
{
stdin = new FileInputStream(paramString);
System.setIn(stdin);
inStreamName = paramString;

Keyboard.reset();
}
catch (Exception localException)
{
System.err.println("Error: Unable to open input file [" + paramString + "]");
System.exit(1);
}
}

public static void resetIn()
{
try
{
if (stdin != null)
{
stdin.close();
stdin = null;
}
System.setIn(origIn);
inStreamName = "Keyboard";

Keyboard.reset();
}
catch (Exception localException)
{
System.err.println("Error: Unable to close [" + inStreamName + "]");
System.exit(1);
}
}

public static String getOutStreamName()
{
return outStreamName;
}

public static void addTo(String paramString)
{
to(paramString, true);
}

public static void to(String paramString)
{
to(paramString, false);
}

public static void to(String paramString, boolean paramBoolean)
{
if (stdout != null) {
resetOut();
}
try
{
stdout = new PrintStream(new FileOutputStream(paramString, paramBoolean));
System.setOut(stdout);
outStreamName = paramString;
}
catch (Exception localException)
{
System.err.println("Error: Unable to open output file [" + paramString + "]");
System.exit(1);
}
}

public static void resetOut()
{
try
{
if (stdout != null)
{
stdout.close();
stdout = null;
}
System.setOut(origOut);
outStreamName = "Screen";
}
catch (Exception localException)
{
System.err.println("Error: Unable to close [" + outStreamName + "]");
System.exit(1);
}
}
}

SimpleURLReader 类

package com.example.parsetester;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;

public class SimpleURLReader
{
public static final String version = "SimpleURLReader:v1.0:03/03/2002";
String pageContents;
int lineCount;

public SimpleURLReader(String paramString)
{
try
{
URL localURL = new URL(paramString);
BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(localURL.openStream()));

this.lineCount = 0;
String str = localBufferedReader.readLine();
while (str != null)
{
this.pageContents = (this.pageContents + str + "\n");
this.lineCount += 1;
str = localBufferedReader.readLine();
}
}
catch (Exception localException)
{
System.out.println(localException);
}
}

public String getPageContents()
{
return pageContents;
}

public int getLineCount()
{
return this.lineCount;
}
}

MySimpleURLReader 类

package com.example.parsetester;

public class MySimpleURLReader extends SimpleURLReader {

String url;
String name;

// constructor, extends the one in SimpleURLReader class.
public MySimpleURLReader(String url)
{
super (url);
this.url = url;
}

// getter method for URL.
public String getURL ()
{
return this.url;
}

// getter method for file name, looks at the end of the link, then substrings the page extension.
public String getName()
{
name = url.substring(url.lastIndexOf('/')+1, url.length());
return name;
}

// overrides cs1.getPageContents() method, deletes "null" word, which is a mistake in super method.
public String getPageContents()
{
return super.getPageContents().substring(4);
}
}

键盘类

package com.example.parsetester;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.StringTokenizer;

public class Keyboard
{
public static final String version = "Keyboard:v1.0:15/12/2003";
private static boolean printErrors = true;
private static int errorCount = 0;

public static int getErrorCount()
{
return errorCount;
}

public static void resetErrorCount(int paramInt)
{
errorCount = 0;
}

public static boolean getPrintErrors()
{
return printErrors;
}

public static void setPrintErrors(boolean paramBoolean)
{
printErrors = paramBoolean;
}

private static void error(String paramString)
{
errorCount += 1;
if (printErrors) {
System.out.println(paramString);
}
}

private static String current_token = null;
private static StringTokenizer reader;
private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in), 1);

public static void reset()
{
resetErrorCount(0);
current_token = null;
reader = null;
in = new BufferedReader(new InputStreamReader(System.in), 1);
}

public static void Wait()
{
try
{
current_token = null;
reader = null;
in.readLine();
}
catch (Exception localException)
{
error("OOPS.. ");
}
}

private static String getNextToken()
{
return getNextToken(true);
}

private static String getNextToken(boolean paramBoolean)
{
String str;
if (current_token == null)
{
str = getNextInputToken(paramBoolean);
}
else
{
str = current_token;
current_token = null;
}
return str;
}

private static String getNextInputToken(boolean paramBoolean)
{
String str = null;
try
{
if (reader == null)
{
reader = new StringTokenizer(in.readLine(), " \t\n\r\f", true);
//break label68;
}
label68:
do
{
do
{
while (!reader.hasMoreTokens()) {
reader = new StringTokenizer(in.readLine(), " \t\n\r\f", true);
}
str = reader.nextToken();
} while (str == null);
if (" \t\n\r\f".indexOf(str) < 0) {
break;
}
} while (paramBoolean);
}
catch (Exception localException)
{
str = null;
}
return str;
}

public static boolean endOfLine()
{
return !reader.hasMoreTokens();
}

public static String readString()
{
String str;
try
{
str = getNextToken(false);
while (!endOfLine()) {
str = str + getNextToken(false);
}
}
catch (Exception localException)
{
error("Error reading String data, null value returned.");
str = null;
}
return str;
}

public static String readWord()
{
String str;
try
{
str = getNextToken();
}
catch (Exception localException)
{
error("Error reading String data, null value returned.");
str = null;
}
return str;
}

public static boolean readBoolean()
{
String str = getNextToken();
boolean bool;
try
{
if (str.toLowerCase().equals("true"))
{
bool = true;
}
else if (str.toLowerCase().equals("false"))
{
bool = false;
}
else
{
error("Error reading boolean data, false value returned.");
bool = false;
}
}
catch (Exception localException)
{
error("Error reading boolean data, false value returned.");
bool = false;
}
return bool;
}

public static char readChar()
{
String str = getNextToken(false);
char c;
try
{
if (str.length() > 1) {
current_token = str.substring(1, str.length());
} else {
current_token = null;
}
c = str.charAt(0);
}
catch (Exception localException)
{
error("Error reading char data, MIN_VALUE value returned.");
c = '\000';
}
return c;
}

public static int readInt()
{
String str = getNextToken();
int i;
try
{
i = Integer.parseInt(str);
}
catch (Exception localException)
{
error("Error reading int data, MIN_VALUE value returned.");
i = -2147483648;
}
return i;
}

public static long readLong()
{
String str = getNextToken();
long l;
try
{
l = Long.parseLong(str);
}
catch (Exception localException)
{
error("Error reading long data, MIN_VALUE value returned.");
l = -9223372036854775808L;
}
return l;
}

public static float readFloat()
{
String str = getNextToken();
float f;
try
{
f = new Float(str).floatValue();
}
catch (Exception localException)
{
error("Error reading float data, NaN value returned.");
f = (0.0F / 0.0F);
}
return f;
}

public static double readDouble()
{
String str = getNextToken();
double d;
try
{
d = new Double(str).doubleValue();
}
catch (Exception localException)
{
error("Error reading double data, NaN value returned.");
d = (0.0D / 0.0D);
}
return d;
}
}

HTMLFilteredReader 类

package com.example.parsetester;

public class HTMLFilteredReader extends MySimpleURLReader {

String url;

//constructor, extends MySimpleURLReader.
public HTMLFilteredReader(String url)
{
super(url);
this.url = url;
}

// filtered method, returns user page's content without HTML codes.

public String getPageContents ()
{
String partFirst = "asd";
String partSecond = "asd";
int temp = 0;
String newContent=super.getPageContents();

// first for loop, counts how many '<' characters there are in the page.
for (int i = 0; i<newContent.length(); i++)
{
if (newContent.charAt(i) == '<')
temp++;
}
// second for loop, deletes the HTML code by starting at the end of the page.
for (int i=0; i<temp; i++)
{
partFirst = newContent.substring (0, newContent.lastIndexOf("<")); // and this one will substring the parts after the last HTML code, as the second for loop deletes from the end of the page.
partSecond = newContent.substring (newContent.indexOf(">", newContent.lastIndexOf ("<"))+1);// and this one will substring the parts after the last HTML code, as the second for loop deletes from the end of the page.
newContent = partFirst + partSecond; // concatenates this two parts to get the complete page.
}
return newContent;
}

// getUnfilteredPageContents method, returns the unfiltered page by getting it from its parent class.
public String getUnfilteredPageContents ()
{
return super.getPageContents();
}
}

最后是我的 MainActivity:

package com.example.parsetester;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HTMLFilteredReader reader = new HTMLFilteredReader("http://kafemud.bilkent.edu.tr/monu_eng.html");
reader.getPageContents();
}

}

这是 LogCat:

03-18 21:11:45.623: E/AndroidRuntime(8310): FATAL EXCEPTION: main
03-18 21:11:45.623: E/AndroidRuntime(8310): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.parsetester/com.example.parsetester.MainActivity}: java.lang.NullPointerException
03-18 21:11:45.623: E/AndroidRuntime(8310): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2304)
03-18 21:11:45.623: E/AndroidRuntime(8310): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
03-18 21:11:45.623: E/AndroidRuntime(8310): at android.app.ActivityThread.access$700(ActivityThread.java:165)
03-18 21:11:45.623: E/AndroidRuntime(8310): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1326)
03-18 21:11:45.623: E/AndroidRuntime(8310): at android.os.Handler.dispatchMessage(Handler.java:99)
03-18 21:11:45.623: E/AndroidRuntime(8310): at android.os.Looper.loop(Looper.java:137)
03-18 21:11:45.623: E/AndroidRuntime(8310): at android.app.ActivityThread.main(ActivityThread.java:5450)
03-18 21:11:45.623: E/AndroidRuntime(8310): at java.lang.reflect.Method.invokeNative(Native Method)
03-18 21:11:45.623: E/AndroidRuntime(8310): at java.lang.reflect.Method.invoke(Method.java:525)
03-18 21:11:45.623: E/AndroidRuntime(8310): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
03-18 21:11:45.623: E/AndroidRuntime(8310): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
03-18 21:11:45.623: E/AndroidRuntime(8310): at dalvik.system.NativeStart.main(Native Method)
03-18 21:11:45.623: E/AndroidRuntime(8310): Caused by: java.lang.NullPointerException
03-18 21:11:45.623: E/AndroidRuntime(8310): at com.example.parsetester.MySimpleURLReader.getPageContents(MySimpleURLReader.java:31)
03-18 21:11:45.623: E/AndroidRuntime(8310): at com.example.parsetester.HTMLFilteredReader.getPageContents(HTMLFilteredReader.java:28)
03-18 21:11:45.623: E/AndroidRuntime(8310): at com.example.parsetester.MainActivity.onCreate(MainActivity.java:14)
03-18 21:11:45.623: E/AndroidRuntime(8310): at android.app.Activity.performCreate(Activity.java:5369)
03-18 21:11:45.623: E/AndroidRuntime(8310): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
03-18 21:11:45.623: E/AndroidRuntime(8310): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2267)

最佳答案

SimpleURLReader 中的

pageContents 在使用之前未初始化。我唯一能看到它分配到的地方是这里:

  String str = localBufferedReader.readLine();
while (str != null)
{
this.pageContents = (this.pageContents + str + "\n");
this.lineCount += 1;
str = localBufferedReader.readLine();
}

如果 while 循环从未执行,pageContents 将保持 null。这可能就是正在发生的事情。如果 while 循环确实被执行,那么在此语句中

    this.pageContents = (this.pageContents + str + "\n");

当您连接字符串时,四个字符“null”应该出现在结果中——您注意到这种情况了吗?

无论如何,在某处初始化为""。在 try 之前的某个地方,尽管我质疑为什么您的 SimpleURLReader 会捕获异常,但即使发生异常,也允许构造对象。这是 Intent 吗?如果是,pageContents 仍然需要设置一些内容。

关于java - Android 解析时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22489056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com