解析时的Android Null指针异常

时间:2014-03-18 19:22:58

标签: java android parsing nullpointerexception runtime

编辑:我已经解决了这个问题,因为我没有在异步任务中实现解析,所以它给出了一个错误。无论如何,谢谢你的回复!

我一直在尝试解析一个网站。当我作为一个Java项目,它正常工作并返回一个干净的结果,但是当我尝试在Android中做同样的事情时,它给了我java.lang.NullPointerException。我正在使用.jar文件并认为问题可能发生在jar类中,反编译它但没有改变。这是课程。任何帮助将不胜感激。

PS:奇怪的是,当它是一个jar文件时,没有与类相关的错误,但是当我反编译它时,它在Keyboard类的第96行给了我错误,所以我对它进行了评论。

再次感谢你们这些人。

StdIO Class

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)

1 个答案:

答案 0 :(得分:1)

pageContents中的

SimpleURLReader在使用前未初始化。我能看到它的唯一地方就是:

  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捕获异常,但是即使发生异常也允许构造对象。这是意图吗?如果是,则pageContents仍然需要设置为某种内容。