0

Androidの別のアクティビティのクラスに配列を設定しようとしています。

これが私の主な活動です:

public class main_activity extends Activity {
  int i = 0;
  TextView title;
  TextView inst;
  TextView word;
  EditText edittext;
  Button btn;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
   // TODO Auto-generated method stub
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_four);

   MyArray mine = new MyArray();
   mine.shuffle(getApplicationContext());
  }
}

myArrayは次のとおりです。

public class MyArray{
  String[] words = new String[2];

  public void choose(int id) {
    switch (id) {
    case 1:
      words[0] = "zero";
      words[1] = "one";
      break;
    case 2:
      words[0] = "two";
      words[1] = "three";
  }

  public void shuffle(Context mcontext) {
    MyArray mine = new MyArray();
     mine.choose(2);
     Log.d("TEST", words[1]);
     Log.d("TEST", words[2]);
  }
}

でNullPointerエラーが発生して強制終了しますLog.d("TEST", words[1]);。私が間違っていることを理解することはできません。前もって感謝します。

4

3 に答える 3

4

配列は初期化されていますが、メソッド自体のオブジェクトではなく、オブジェクトwords内でのみです。メソッド内に別のオブジェクトを作成し、そのメソッドを呼び出してから、独自の配列にアクセスしようとしている理由は不明です。mineshufflethisMyArrayshuffle choosewords

質問の編集に一致するように編集して、に変更myArrayMyArrayます。

于 2013-03-05T01:36:32.697 に答える
1

shuffle()メソッドを次のように変更します。

public void shuffle() {
    choose(2);
    Log.d("TEST", words[0]);
    Log.d("TEST", words[1]);
}

必要のないローカルを作成していないので、これでnullポインタがmine処理されます。

2また、存在しない配列メンバーにアクセスしようとしているため、次に取得する範囲外も修正されます。

それはまたContext、明らかに理由もなく、あなたが通過しているものを排除します。

于 2013-03-05T01:39:39.670 に答える
0

onCreateMyArrayには大文字の「m」があり、クラスの名前「m」は小文字であり、ログには位置2には0と1しかないと記載されています。

于 2013-03-05T01:36:15.697 に答える