空指针异常Java [英] Null Pointer Exception Java

查看:103
本文介绍了空指针异常Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习Java,并遇到了问题。在尝试运行Android应用程序时,调用方法makeResponse时会出现NullPointerException。

I'm just starting out with learning Java, and have run into a problem. When trying to run an Android application, I get a NullPointerException when the method makeResponse is called.

代码提取(在本文末尾附加完整代码):

Code extract (full code appended at the end of this post):

private String makeResponse(String input){
    //This doesn't work yet.  I keep getting null pointer exceptions on the line beginning "int id" line, but can't tell why.
    String response = "You picked "+input;
    if (sw==null){
        response+=" and sw is null"; //This doesn't activate
    }
    if (input==null){
        response+=" and input is null"; //This doesn't activate
    }
    int id = sw.getIdFromName(input); //If this line (and the following one) are commented out, the method runs with no problem, but neither of the if clauses above trigger.
    response+=", that has id "+String.valueOf(id);
    return response;
}

(sw是父类的字段,在另一种方法中设置.sw是一个自制类的实例 - 最后的完整代码)

(sw is a field of the parent class, set in another method. sw is an instance of a self-made class - full code at the end)

在int id =

我最初搜索NullPointerException告诉我,当某个应用程序在需要对象的情况下尝试使用null时,它被抛出。 - 因此我上面的代码中的两个if子句,试图找到哪个对象意外为null。由于这些都不是,我得出结论,sw.getIdFromName必须返回一个Integer类型的null(就像在这个类似的问题中一样: Java:取消装箱整数后出现空指针异常?)。但是,我没有看到如何在sw.getIdFromName中实现这一点,如下所示(nameLookup是一个String数组,一个sw字段):

My initial searching for NullPointerException told me that it was "thrown when an application attempts to use null in a case where an object is required." - hence the two "if" clauses in my code above, to try to find which object was unexpectedly null. Since neither of these are, I concluded that sw.getIdFromName must be returning a null of type Integer (as in this similar problem: Java: null pointer exception when unboxing Integer?). However, I don't see how this is possible in sw.getIdFromName as shown below (nameLookup is a String array, a field of sw):

public int getIdFromName(String name){
    for (int i=0;i<267;i++){
        if (nameLookup[i].equals(name)){
            return i;
        }
    }
    return -1;
}

(顺便提一下,如果有更好的搜索字符串数组的方法搜索词,如果有人能告诉我,我将不胜感激 - binarySearch似乎没有在String数组中定义。)

(Incidentally, if there is a better way of searching a String array for a search term, I would be grateful if someone could tell me - binarySearch doesn't appear to be defined on String arrays).

按照最高评论者的建议上面链接的问题,我尝试在makeResponse中用Integer id替换int id,但没有效果 - 在同一个地方抛出相同的异常。

Following the advice of the top commenter in the question linked above, I tried replacing "int id" with "Integer id" in makeResponse, but with no effect - the same exception is thrown at the same place.

任何建议将不胜感激。

从上面链接的stackoverflow问题中的注释判断,提供堆栈跟踪不会提供任何新信息,但我很乐意如果被问到,请这样做。

Judging from the comments in the stackoverflow question linked above, providing a stack trace would not provide any new information, but I'd be happy to do so if asked.

Ps这是我在这里提出的第一个问题,如果我违反礼仪或者错误的话,我会道歉。

P.s. this is my first question here, so apologies if I make some breach of etiquette or inane mistake.

完整代码清单

ConversationActivity.java:

ConversationActivity.java:

package com.example.Conversation;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;

public class ConversationActivity extends Activity {
/** Called when the activity is first created. */
StationsWrapper sw;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    /**Setting the adapter for the AutoComplete*/
    final AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.ACTextView1);
    String[] stationsArray = getResources().getStringArray(R.array.stations);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, stationsArray);
    textView.setAdapter(adapter);

    /**Code below grabs the data from stations.xml and puts it in a readable object */
    this.sw = new StationsWrapper();

    /** Code below is to set a click function for the AutoComplete*/
    OnItemClickListener ACListener = new OnItemClickListener(){

        public void onItemClick(AdapterView<?> parent, View v, int position,
                long id) {
            TextView reply = (TextView) findViewById(R.id.reply);
            reply.setText("working...");
            String ChosenStation = (String) parent.getItemAtPosition(position);
            reply.setText(makeResponse(ChosenStation));
            //Toast.makeText(ConversationActivity.this, "You clicked "+parent.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
            textView.setText("");

        }
    };
    textView.setOnItemClickListener(ACListener);

}

private String makeResponse(String input){
    //This doesn't work yet.  I keep getting null pointer exceptions on the line beginning "int id" line, but can't tell why.
    String response = "You picked "+input;
    if (sw==null){
        response+=" and sw is null"; //This doesn't activate
    }
    if (input==null){
        response+=" and input is null"; //This doesn't activate
    }
    int id = sw.getIdFromName(input); //If this line (and the following one) are commented out, the method runs with no problem, but neither of the if clauses above trigger.
    response+=", that has id "+String.valueOf(id);
    return response;
}

}

StationsWrapper.java:

StationsWrapper.java:

package com.example.Conversation;


import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class StationsWrapper {

    private int[][] stats;
    private String[] nameLookup;

    public StationsWrapper(){
        //Constructor.  Grabs data from XML, and whacks it into relevant arrays.
        //stats is an integer array, indexed first by station id (1-267), and then by datatype (0 for line, 1 for zone) 
        final int[][] stats = new int[267][2];
        final String[] nameLookup = new String[267];

        try {

            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();

            DefaultHandler handler = new DefaultHandler() {

                boolean bline = false;
                boolean bzone= false;
                String curStation;
                int curID;
                String curLine;
                String curZone;

                public void startElement(String uri, String localName,String qName, 
                        Attributes attributes) throws SAXException {

                    if (qName.equalsIgnoreCase("STATION")){
                        curStation=attributes.getValue(0);
                        curID=Integer.parseInt(attributes.getValue(1));
                    }

                    if (qName.equalsIgnoreCase("LINE")) {
                        bline = true;
                    }

                    if (qName.equalsIgnoreCase("ZONE")) {
                        bzone = true;
                    } 
                }

                public void endElement(String uri, String localName,
                        String qName) throws SAXException {
                    if (qName.equalsIgnoreCase("Station")){
                        nameLookup[curID-1]=curStation;
                        int intLine=(convLineToInt(curLine));
                        stats[curID-1][0]=intLine;
                        int intZone=(convZoneToInt(curZone));
                        stats[curID-1][1]=intZone;
                    }
                }

                public void characters(char ch[], int start, int length) throws SAXException {

                    if (bline) {
                        //System.out.println("Line : " + new String(ch, start, length));
                        curLine=new String(ch, start, length);
                        bline = false;
                    }

                    if (bzone) {
                        //System.out.println("Zone : " + new String(ch, start, length));
                        curZone=new String(ch, start, length);
                        bzone = false;
                    } 
                }

            };

            saxParser.parse("c:\\Users\\Jack Jackson\\Coding\\Java\\stations.xml", handler);

        } catch (Exception e) {
            e.printStackTrace();
        }

        this.stats=stats;
        this.nameLookup=nameLookup;

    }

    public static void main(String[] args){
        //Nothing to see here, move it along folks.
    }

    public String[] getNameLookup(){
        return nameLookup;
    }

    public int getIdFromName(String name){
        for (int i=0;i<nameLookup.length;i++){
            if (nameLookup[i].equals(name)){
                return i;
            }
        }
        return -1;
    }

    public int returnData(int id, int datapoint){
        return stats[id][datapoint];
    }

    public void displayStats(){
        for (int i=0;i<267;i++){
            for (int j=0;j<2;j++){
                System.out.print(stats[i][j]);
                System.out.print(" ");
            }
            System.out.println("");
        }
    }
   }


推荐答案

在不运行代码的情况下, nameLookup 数组条目中的一个很可能是 null ,所以尝试调用 nameLookup [i] .equals()抛出 NullPointerException

Without running your code, it seems very likely that one of nameLookup array entries is null, so trying to call nameLookup[i].equals() throws a NullPointerException.

如果 nameLookup 的元素可以合法地 null ,处理此问题的一种方法是撤消订单 getIdFromName()中的比较:

If elements of nameLookup can legitimately be null, one way to handle this is to reverse the order of the comparison in getIdFromName():

if (name.equals(nameLookup[i])) {

无论如何,我建议你确保 nameLookup 本身及其元素已完全初始化。

In any case, I'd recommend that you make sure that both nameLookup itself and its elements are fully initialized.

这篇关于空指针异常Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆