2016-03-14 6 views
0

я получаю эту ошибку в Android Studio:Android Studio Runtime ошибок

java.lang.RuntimeException: Невозможно создать экземпляр активности ComponentInfo {dit.assignment3/dit.assignment3.Timer}: java.lang .NullPointerException: Попытка вызвать виртуальный метод «android.view.View android.view.Window.findViewById (INT)» на ссылку на объект нулевой

, но я не могу найти, где в моем коде Я ошибаюсь, пробовал комментировать все ndViewById, что мне не повезло.

Код:

public class Timer extends AppCompatActivity {  
    //declaring all items on page in class  
     EditText hoursIn = (EditText) findViewById(R.id.hoursET); 
     EditText minIn = (EditText) findViewById(R.id.minET); 

     Button start = (Button) findViewById(R.id.startButton); 
     Button stop = (Button) findViewById(R.id.stopButton); 

     TextView textViewTime = (TextView) findViewById(R.id.timeDisp); 


    /** 
    * ATTENTION: This was auto-generated to implement the App Indexing API. 
    * See https://g.co/AppIndexing/AndroidStudio for more information. 
    */ 
     // private GoogleApiClient client; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_timer); 

     textViewTime.setText("00:00:30"); 

     final CounterClass timer = new CounterClass(30000, 1000); 
     start.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       timer.start(); 
      } 
     }); 


     stop.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       timer.cancel(); 
      } 
     }); 
     // ATTENTION: This was auto-generated to implement the App Indexing API. 
     // See https://g.co/AppIndexing/AndroidStudio for more information. 
     //client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); 
    } 

    //@Override 
    /*public void onStart() { 
     super.onStart(); 

     // ATTENTION: This was auto-generated to implement the App Indexing API. 
     // See https://g.co/AppIndexing/AndroidStudio for more information. 
     client.connect(); 
     Action viewAction = Action.newAction(
       Action.TYPE_VIEW, // TODO: choose an action type. 
       "Timer", // TODO: Define a title for the content shown. 
       // TODO: If you have web page content that matches this app activity's content, 
       // make sure this auto-generated web page URL is correct. 
       // Otherwise, set the URL to null. 
       Uri.parse("http://host/path"), 
       // TODO: Make sure this auto-generated app deep link URI is correct. 
       Uri.parse("android-app://dit.assignment3/http/host/path") 
     ); 
     AppIndex.AppIndexApi.start(client, viewAction); 
    } 

    @Override 
    public void onStop() { 
     super.onStop(); 

     // ATTENTION: This was auto-generated to implement the App Indexing API. 
     // See https://g.co/AppIndexing/AndroidStudio for more information. 
     Action viewAction = Action.newAction(
       Action.TYPE_VIEW, // TODO: choose an action type. 
       "Timer Page", // TODO: Define a title for the content shown. 
       // TODO: If you have web page content that matches this app activity's content, 
       // make sure this auto-generated web page URL is correct. 
       // Otherwise, set the URL to null. 
       Uri.parse("http://host/path"), 
       // TODO: Make sure this auto-generated app deep link URI is correct. 
       Uri.parse("android-app://dit.assignment3/http/host/path") 
     ); 
     AppIndex.AppIndexApi.end(client, viewAction); 
     client.disconnect(); 
    }*/ 

     public class CounterClass extends CountDownTimer { 

     /** 
     * @param millisInFuture The number of millis in the future from the call 
     *       to {@link #start()} until the countdown is done and {@link #onFinish()} 
     *       is called. 
     * @param countDownInterval The interval along the way to receive 
     *       {@link #onTick(long)} callbacks. 
     */ 
     public CounterClass(long millisInFuture, long countDownInterval) { 
      super(millisInFuture, countDownInterval); 
     } 

     @Override 
     public void onTick(long millisUntilFinished) { 
      long millis = millisUntilFinished; 
      String hrsminsec = String.format("%02:%02:%02", TimeUnit.MILLISECONDS.toHours(millis), 
        TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toMinutes(millis)), 
        TimeUnit.MILLISECONDS.toSeconds(millis - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toSeconds(millis))) 
      ); 

      textViewTime.setText(hrsminsec); 
     } 

     @Override 
     public void onFinish() { 
      textViewTime.setText("DONE"); 
     } 
    } 
} 

Приветствия

ответ

1

Вы должны поместить свои findViewById звонки в свой onCreate, который вы пытаетесь назначить им до того, как будет создано Окно.

EditText hoursIn; 
EditText minIn; 

Button start; 
Button stop; 

TextView textViewTime; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_timer); 
    hoursIn = (EditText) findViewById(R.id.hoursET); 
    minIn = (EditText) findViewById(R.id.minET); 

    start = (Button) findViewById(R.id.startButton); 
    stop = (Button) findViewById(R.id.stopButton); 

    textViewTime = (TextView) findViewById(R.id.timeDisp); 
1

findViewById не может быть вызвана перед как onCreate и setContentView.

Изменение по следующим

EditText hoursIn; 

public void onCreate(...){ 
    ... 

    setContentView(...); 

    hoursIn = (EditText) findViewById(R.id.hoursET); 

    ... 
} 

Причина этого заключается в том, что findViewById собирается для поиска элемента, который в настоящее время на дисплее, перед установкой вид контента, нет ничего, чтобы найти, в результате чего результат findViewById будет null.

0
You should assign all controls in onCreate() 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_timer); 
     EditText hoursIn = (EditText) findViewById(R.id.hoursET); 
     EditText minIn = (EditText) findViewById(R.id.minET); 
     textViewTime.setText("00:00:30"); 

     final CounterClass timer = new CounterClass(30000, 1000); 
     start.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       timer.start(); 
      } 
     }); 
Смежные вопросы