2011-08-05 1 views
0

別のクラスファイルに含まれている関数を使用する方法を理解しようとしています。別のクラスファイルをAndroidアプリで使用するときにこのエラーを助けてください

私の別のクラスファイルはEncounterGenerator.javaと呼ばれます。そして、私はこのようにそれを呼び出す:だから以下

EncounterGenerator Encounter; testString = Encounter.EncounterGeneratorText();

HelloAndroid.javaと呼ばれる私のメインのファイルです:

package mot.HelloAndroid; 

import android.app.Activity; 
import android.os.Bundle; 
import android.widget.TextView; 
import android.widget.Button; 
import android.view.View; 
import android.view.View.OnClickListener; 


public class HelloAndroid extends Activity { 
/** Called when the activity is first created. */ 
TextView tvIntro; 
TextView tvNavigator; 
TextView tvAction; 
EncounterGenerator Encounter ; 

@Override 
public void onCreate(Bundle icicle) { 
    super.onCreate(icicle); 

    //setup text views 
    this.setContentView(R.layout.main); 

    tvIntro = (TextView)findViewById(R.id.tvIntro); 
    tvNavigator = (TextView)findViewById(R.id.tvNavigator); 
    tvAction = (TextView)findViewById(R.id.tvAction); 


    //display game intro 
    tvIntro.setText("Text Adventure"); 

    try { 
     Thread.sleep(5000); 
    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    tvIntro.setText("This is a really cool text adventure game!"); 

    //define navigation buttons 
    Button btnNorth = (Button)findViewById(R.id.btnNorth); 

    btnNorth.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      tvIntro.setText("You go north"); 
      String testString = "nothing"; 
      try { 
       testString = Encounter.EncounterGeneratorText(); 
      } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      testString = Encounter.EncounterGeneratorText(); 
      tvIntro.setText(testString); 

     } 
    }); 
    } 
} 

、これはEncounterGeneratorと呼ばれる私の別のクラスファイルです。 java:

package mot.HelloAndroid; 

public class EncounterGenerator { 

public String EncounterGeneratorText() { 
    String encounterText = "test value"; 
    return encounterText; 
} 
} 
私はそれを実行し、機能EncounterGeneratorTextを(呼び出すボタンをクリックしてください

毎回)私は私のAVPでこのエラーを取得する:

こんにちはAndroidが予期せず停止したアプリケーション...誰場合は、再び

を試してみてください私は大いに感謝しています!

+0

@MByDによる回答は正しいです。一般に、エラーが発生した場合は、Eclipseで 'adb logcat'、DDMS、またはDDMSパースペクティブを使用してLogCatを調べ、エラーに関連するスタックトレースを調べます。この場合、 'NullPointerException'があり、例外が発生した行番号を示します。 – CommonsWare

答えて

3

あなたはEncounterをインスタンス化する必要があります。

サイドノート、Javaでの変数は、通常は小文字で開始されます。

+0

また、 'Thread.sleep(5000)'は 'onCreate()'の中にあるので、ANRを起動するのに十分かもしれません。 – RivieraKid

+0

@RivieraKid - それは気付いていません。 – MByD

+0

@MByD - うわー、おかげさま...シンプルなので、私はそれを知らなかったと信じられない! – SkyeBoniwell

1

あなたのメソッドは静的メソッドではありません。 EncounterGeneratorText()メソッドを呼び出すには、クラスをインスタンス化する必要があります。

2点目:メソッドは常に小文字で始まる:):CountDownTimer(long delay, long unit);ない

Thread.sleep(long milliseconds); 

注意を使用するようにしてください。

+0

ホーシン - ありがとう...素晴らしいヒント! – SkyeBoniwell

+0

あなたは大歓迎です:) – Houcine

関連する問題