0

У меня было несколько проблем с набором инструментов Android для Android, и я не могу его исправить. Я попытался запустить свой код, и это то, что проявляется в LogCatNullPointerException - android.view.Window.findViewById (int) - Почему?

Вот моя основная деятельность:

public class MainActivity extends AppCompatActivity { 

EditText input = (EditText) findViewById(R.id.input); 
TextView output = (TextView) findViewById(R.id.output); 
ArrayList <String> charzart = new ArrayList<String>(); 
ArrayList <String> color = new ArrayList<String>(); 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
    fab.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
        .setAction("Action", null).show(); 
     } 
    }); 

    Button converter = (Button) findViewById(R.id.button); 

    int begin = 0; 
    int total = 16777216; 
    String text = input.getText().toString(); 

    ArrayList<Integer> hexa = new ArrayList<Integer>(); 


    //charzart array 
    int b = text.length(); 

    for (int i = 1; i <= b; i++) { 
     charzart.add(text.substring(i - 1, i)); 
    } 

    //hexa array 

    int a = text.length() - 1; 

    for (int z = 0; z < charzart.size(); z++) { 

     if (charzart.get(z).matches(" ")) { 
      a--; 
     } 
    } 


    int numb = total/a; 

    for (int x = 0; x <= 16777216; x = x + numb) { 
     hexa.add(x); 
    } 


    //changing into hexadecimal numbers 

    for (int y = 0; y < hexa.size(); y++) { 

     int cvalue = hexa.get(y); 
     int one, two, three, four, five, six; 

     one = cvalue/1048570; 
     cvalue = cvalue - one * 1048570; 

     two = cvalue/65356; 
     cvalue = cvalue - two * 65356; 

     three = cvalue/4096; 
     cvalue = cvalue - three * 4096; 

     four = cvalue/256; 
     cvalue = cvalue - four * 256; 

     five = cvalue/16; 
     cvalue = cvalue - five * 16; 

     six = cvalue; 

     if (one != 16) { 

      String let = ""; 
      String fin = "#"; 

      switch (one) { 
       case 0: 
        let = "0"; 
        break; 
       case 1: 
        let = "1"; 
        break; 
       case 2: 
        let = "2"; 
        break; 
       case 3: 
        let = "3"; 
        break; 
       case 4: 
        let = "4"; 
        break; 
       case 5: 
        let = "5"; 
        break; 
       case 6: 
        let = "6"; 
        break; 
       case 7: 
        let = "7"; 
        break; 
       case 8: 
        let = "8"; 
        break; 
       case 9: 
        let = "9"; 
        break; 
       case 10: 
        let = "A"; 
        break; 
       case 11: 
        let = "B"; 
        break; 
       case 12: 
        let = "C"; 
        break; 
       case 13: 
        let = "D"; 
        break; 
       case 14: 
        let = "E"; 
        break; 
       case 15: 
        let = "F"; 
        break; 
       default: 
        let = "x"; 
      } 

      fin += let; 
      let = ""; 

      switch (two) { 
       case 0: 
        let = "0"; 
        break; 
       case 1: 
        let = "1"; 
        break; 
       case 2: 
        let = "2"; 
        break; 
       case 3: 
        let = "3"; 
        break; 
       case 4: 
        let = "4"; 
        break; 
       case 5: 
        let = "5"; 
        break; 
       case 6: 
        let = "6"; 
        break; 
       case 7: 
        let = "7"; 
        break; 
       case 8: 
        let = "8"; 
        break; 
       case 9: 
        let = "9"; 
        break; 
       case 10: 
        let = "A"; 
        break; 
       case 11: 
        let = "B"; 
        break; 
       case 12: 
        let = "C"; 
        break; 
       case 13: 
        let = "D"; 
        break; 
       case 14: 
        let = "E"; 
        break; 
       case 15: 
        let = "F"; 
        break; 
       default: 
        let = "x"; 
      } 

      fin += let; 
      let = ""; 

      switch (three) { 
       case 0: 
        let = "0"; 
        break; 
       case 1: 
        let = "1"; 
        break; 
       case 2: 
        let = "2"; 
        break; 
       case 3: 
        let = "3"; 
        break; 
       case 4: 
        let = "4"; 
        break; 
       case 5: 
        let = "5"; 
        break; 
       case 6: 
        let = "6"; 
        break; 
       case 7: 
        let = "7"; 
        break; 
       case 8: 
        let = "8"; 
        break; 
       case 9: 
        let = "9"; 
        break; 
       case 10: 
        let = "A"; 
        break; 
       case 11: 
        let = "B"; 
        break; 
       case 12: 
        let = "C"; 
        break; 
       case 13: 
        let = "D"; 
        break; 
       case 14: 
        let = "E"; 
        break; 
       case 15: 
        let = "F"; 
        break; 
       default: 
        let = "x"; 
      } 

      fin += let; 
      let = ""; 

      switch (four) { 
       case 0: 
        let = "0"; 
        break; 
       case 1: 
        let = "1"; 
        break; 
       case 2: 
        let = "2"; 
        break; 
       case 3: 
        let = "3"; 
        break; 
       case 4: 
        let = "4"; 
        break; 
       case 5: 
        let = "5"; 
        break; 
       case 6: 
        let = "6"; 
        break; 
       case 7: 
        let = "7"; 
        break; 
       case 8: 
        let = "8"; 
        break; 
       case 9: 
        let = "9"; 
        break; 
       case 10: 
        let = "A"; 
        break; 
       case 11: 
        let = "B"; 
        break; 
       case 12: 
        let = "C"; 
        break; 
       case 13: 
        let = "D"; 
        break; 
       case 14: 
        let = "E"; 
        break; 
       case 15: 
        let = "F"; 
        break; 
       default: 
        let = "x"; 
      } 

      fin += let; 
      let = ""; 

      switch (five) { 
       case 0: 
        let = "0"; 
        break; 
       case 1: 
        let = "1"; 
        break; 
       case 2: 
        let = "2"; 
        break; 
       case 3: 
        let = "3"; 
        break; 
       case 4: 
        let = "4"; 
        break; 
       case 5: 
        let = "5"; 
        break; 
       case 6: 
        let = "6"; 
        break; 
       case 7: 
        let = "7"; 
        break; 
       case 8: 
        let = "8"; 
        break; 
       case 9: 
        let = "9"; 
        break; 
       case 10: 
        let = "A"; 
        break; 
       case 11: 
        let = "B"; 
        break; 
       case 12: 
        let = "C"; 
        break; 
       case 13: 
        let = "D"; 
        break; 
       case 14: 
        let = "E"; 
        break; 
       case 15: 
        let = "F"; 
        break; 
       default: 
        let = "x"; 
      } 

      fin += let; 
      let = ""; 

      switch (six) { 
       case 0: 
        let = "0"; 
        break; 
       case 1: 
        let = "1"; 
        break; 
       case 2: 
        let = "2"; 
        break; 
       case 3: 
        let = "3"; 
        break; 
       case 4: 
        let = "4"; 
        break; 
       case 5: 
        let = "5"; 
        break; 
       case 6: 
        let = "6"; 
        break; 
       case 7: 
        let = "7"; 
        break; 
       case 8: 
        let = "8"; 
        break; 
       case 9: 
        let = "9"; 
        break; 
       case 10: 
        let = "A"; 
        break; 
       case 11: 
        let = "B"; 
        break; 
       case 12: 
        let = "C"; 
        break; 
       case 13: 
        let = "D"; 
        break; 
       case 14: 
        let = "E"; 
        break; 
       case 15: 
        let = "F"; 
        break; 
       default: 
        let = "x"; 
      } 

      fin += let; 
      let = ""; 


      color.add(fin); 

      fin = "#"; 
     } else { 
      color.add("#FFFFFF"); 
     } 

    } 


    //BUTTON 

    converter.setOnClickListener(
      new View.OnClickListener() { 
       public void onClick(View v) { 

        String end = ""; 
        for (int p = 0; p < charzart.size(); p++) { 

         if (charzart.get(p).equals(" ")) { 

         } 
         else{ 

          Spannable colorSpan = new SpannableString(charzart.get(p)); 
          int fake = Integer.parseInt(color.get(p)); 
          colorSpan.setSpan(new ForegroundColorSpan(fake), 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

          end += colorSpan; 
         } 


        } 

        output.setText(end); 
       } 


      } 
    ); 

} 

Вот мой макет XML файл:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" 
    tools:context="com.hitchhikingapps.rainbowz.MainActivity" 
    tools:showIn="@layout/activity_main"> 

     <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Convert" 
     android:id="@+id/button" 
     android:layout_marginTop="124dp" 
     android:layout_below="@+id/input" 
     android:layout_centerHorizontal="true" /> 

     <EditText 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:inputType="textMultiLine" 
     android:ems="10" 
     android:id="@+id/input" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     android:gravity="center_horizontal" 
     android:text="Insert Text here" /> 

     <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceLarge" 
     android:id="@+id/output" 
     android:layout_alignParentBottom="true" 
     android:layout_centerHorizontal="true" 
     android:layout_marginBottom="78dp" /> 
     </RelativeLayout> 

И это ошибка, которую я получил:

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.hitchhikingapps.rainbowz/com.hitchhikingapps.rainbowz.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference 
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327) 
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                      at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:148) 
                      at android.app.ActivityThread.main(ActivityThread.java:5417) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
                     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference 
                      at android.app.Activity.findViewById(Activity.java:2090) 
                      at com.hitchhikingapps.rainbowz.MainActivity.<init>(MainActivity.java:22) 
                      at java.lang.Class.newInstance(Native Method) 
                      at android.app.Instrumentation.newActivity(Instrumentation.java:1067) 
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317) 
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  
                      at android.app.ActivityThread.-wrap11(ActivityThread.java)  
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  
                      at android.os.Handler.dispatchMessage(Handler.java:102)  
                      at android.os.Looper.loop(Looper.java:148)  
                      at android.app.ActivityThread.main(ActivityThread.java:5417)  
                      at java.lang.reflect.Method.invoke(Native Method)  
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  

Извините за большой блок кода, но я действительно не понимаю, что такое pro blem есть. Любая помощь будет признателен

+0

Добавить код операции и раскладку – piotrek1543

+0

Исключительное исключение указателя на указатель указывает, что нет представления с данным идентификатором, проверьте свои макеты – piotrek1543

+0

Я добавил свой код? Спасибо, ответив – Duncan

ответ

1

Проблема здесь состоит в том, что вы инициализирует свои взгляды как глобальные переменные:

EditText input = (EditText) findViewById(R.id.input); 
TextView output = (TextView) findViewById(R.id.output); 

Текущий контекст ваших взглядов здесь Window и не R.layout.activity_main.

Если вы хотите использовать input и output как глобальные переменные, вы только объявить их:

EditText input; 
TextView output; 

и инициализировать их в onCreate() после setContentView():

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

    input = (EditText) findViewById(R.id.input); 
    output = (TextView) findViewById(R.id.output); 
} 
+0

Спасибо большое! – Duncan

0

NPE это потому, что вы 'вызывающий findViewById() до onCreate() в жизненном цикле деятельности перед деятельностью имеет Window. Переместите вызовы findViewById() с инициализацией переменной-члена до onCreate() и после setContentView(), чтобы можно было вернуть ненулевое значение.