2011-11-11 21 views
4

私はちょうどJavaを学ぶことから始まり、問題にぶつかっています。 Androidアプリケーションを実行しようとすると、メソッドmakeResponseが呼び出されたときにNullPointerExceptionが発生します。ヌルポインタ例外Java

コード(この記事の最後に追加フルコード)を抽出:

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が自作のクラスのインスタンスです。 - 最後にフルコード)

は、例外はNullPointerExceptionが発生するための「int型のID =」

私の最初の検索は、アプリケーションが場合にはnullを使おうとすると、それが」スローされたことを私に言った始まる行でスローされますどこのオブジェクトが必要です。 - したがって、上記の2つの "if"節は、どのオブジェクトが予期せずnullであるかを調べるためです。これらのどちらもないので、私はsw.getIdFromNameがInteger型のnullを返さなければならないと結論づけました(このような問題のように:Java: null pointer exception when unboxing Integer?)。

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

(ちなみに、検索のより良い方法があれば:しかし、私は(nameLookupは、String配列、SWの分野である)は、以下に示すように、これはsw.getIdFromNameで可能であるかが表示されません検索用語の文字列配列、誰かが私に教えてくれればと感謝します - binarySearchは文字列配列では定義されていないようです)。

上記の質問のトップコメント者のアドバイスに従って、私はmakeResponseの "int id"を "Integer id"に置き換えようとしましたが、効果はありません - 同じ場所で同じ例外がスローされます。

何かアドバイスをいただければ幸いです。

上記のstackoverflow質問のコメントから判断すると、スタックトレースを提供すると新しい情報は得られませんが、尋ねられたら喜んでできます。

p.s.これは私の最初の質問ですので、謝罪や礼儀違反をした場合は謝罪します。

完全なコードリスト:

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:

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

プログラムのデバッグを試しましたか? NullPointerExceptionでポイントを解除し、それが原因である理由を確認することができます。 –

+0

エミュレータでこれを再現できますか?スタックトレースをチェックしましたか? – alf

答えて

5

あなたのコードを実行せずに、それはnameLookup配列の1つ可能性が非常に高いと思われますエントリはnullなので、nameLookup[i].equals()に電話をかけようとするとがスローされます。

nameLookupの要素は、合法的にこれを処理する一つの方法は、getIdFromName()の比較の順序を逆にすることで、nullことができる場合は、次のいずれの場合で

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

、私はあなたが必ず両方のことを確認することをお勧めしますnameLookup自身とその要素は完全に初期化されます。

+0

ああ、これが問題だった。 getIdFromNameにテストコードを追加して、nameLookupの要素が実際にnullであることが判明しました。この場合、これは決して起こらないはずなので、私は初期化コードで何かを見逃しているに違いありません。今私はどこをもっと見るべきか知っています。ご協力ありがとうございました! – scubbo