简体   繁体   中英

Android Null Pointer Exception While Parsing

Edit: I have solved the problem, since I do not implement the parsing stuff in async task, it was giving an error. Thanks for the respond anyway!

I have been trying to parse a website. When I do it as a Java project, it works normally and returns me a clean result, however as I try to do same thing in Android, it gives me java.lang.NullPointerException. I was using a .jar file and thought that the problem may be occured inside the jar classes, decompiled it but nothing changed. Here are the classes. Any help will be appreciated.

PS: One weird thing, when it was a jar file there were no erros related with classes, but when I decompiled it, it gave me error on line 96 of Keyboard class, so I commented it down.

Thanks again guys from now on.

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 class

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 Class

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);
    }
}

Keyboard Class

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 Class

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();
    }
}

And finally my 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();
    }

}

Here is the 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)

pageContents in SimpleURLReader is not initialized before it's used. The only place I can see it assigned to is here:

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

If the while loop never gets executed, pageContents will remain null . That's probably what's happening. If the while loop does get executed, then in this statement

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

when you concatenate the strings, the four characters "null" should appear in the result--did you notice that happening?

In any event, initialize to "" somewhere. Somewhere before the try , although I question why your SimpleURLReader catches exceptions but then allows the object to be constructed even if an exception occurs. Is that the intent? If it is, pageContents still needs to be set to something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM