使用TextView的数组访问TextView的setText方法时出现“ NullPointerException”

时间:2018-08-20 06:40:04

标签: android nullpointerexception textview

我创建了一个TextView数组,并使用findViewById对其进行了初始化。

声明:-

TextView varTextView1,varTextView2,varTextView3   //declaring the variables for textView components
TextView textViewArray [];
String textViewArrayString [] = new String [] {"varTextView1","varTextView2","varTextView3"}; //justfornames

 textViewArray = new TextView[] {varTextView1,varTextView2,varTextView3"};

初始化TextView数组:-

 for (TextView element:textViewArray) {
                String tempStringOriginal;
                tempStringOriginal = textViewArrayString[i].toString(); //getting and storing the textView variable name. not the variable
                String tempStringNew = tempStringOriginal.replace("varT","t");
                int resID = getResources().getIdentifier(tempStringNew, "id", getPackageName()); //getting the resource id number from the name  as android stores it as resource and give it a number
                textViewArray[i] = (TextView)findViewById(resID);
                i++;

            }//foreach loop

用于测试:-

int i=0;
 textViewArray[i].setVisibility(View.INVISIBLE); //noerror
 textViewArray[i].setVisibility(View.VISIBLE); //noerror

textViewArray[0].getText(); //not working NULLPOINTEREXCEPTION
textViewArray[0].setText("Test"); //not working NULLPOINTEREXCEPTION

我得到的错误:-

  java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.user.appeggtimer/com.example.user.appeggtimer.MainActivity}: java.lang.NullPointerException: Attempt to read from null array

我不知道这是什么错误,因为.setVisibility可以正常工作,但是.setText显示NullPointerException。
有人可以帮我吗?

===================================

粘贴整个代码

  package com.example.user.appeggtimer;

    import android.os.Handler;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.TextView;

    public class MainActivity extends AppCompatActivity {
            TextView varTextViewTimer,varTextViewPoints,varTextViewQuestion,varTextViewAnswerA,varTextViewAnswerB,varTextViewAnswerC,varTextViewAnswerD;   //declaring the variables for textView components
            TextView textViewArray [];
            String textViewArrayString [] = new String [] {"varTextViewTimer","varTextViewPoints","varTextViewQuestion","varTextViewAnswerA","varTextViewAnswerB","varTextViewAnswerC","varTextViewAnswerD" };
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
           functextViewarray();
            funcTextViewArrayPrint();
            functextViewarrayInit();
            funcVisibilityHideTextView();
           funcVisibilityShowTextView();
           funcTimeDisplay();
           // funcTimeSetAndDisplay();

        }
    //this function i am not using this was the old one
        protected int  funcTextViewInit(View view){//initializing the variables with textView
            varTextViewTimer = findViewById(R.id.textViewTimer);
            varTextViewPoints = findViewById(R.id.textViewPoints);
            varTextViewQuestion = findViewById(R.id.textViewQuestion);
            varTextViewAnswerA = findViewById(R.id.textViewAnswerA);
            varTextViewAnswerB = findViewById(R.id.textViewAnswerB);
            varTextViewAnswerC = findViewById(R.id.textViewAnswerC);
            varTextViewAnswerD = findViewById(R.id.textViewAnswerD);
            return 1;
        }//funcTextViewInit

        protected void onClickStart(){
            funcVisibilityShowTextView();
        }//funcOnClickStart

        // ==========================TextView=========================//
        protected int functextViewarray(){
            textViewArray = new TextView[] {varTextViewTimer,varTextViewPoints,varTextViewQuestion,varTextViewAnswerA,varTextViewAnswerB,varTextViewAnswerC,varTextViewAnswerD};
            Log.i("functextViewarray","success" );
            return 0;
        }

        protected int functextViewarrayInit(){
            int i=0;
            for (TextView element:textViewArray) {
                String tempStringOriginal;
                tempStringOriginal = textViewArrayString[i].toString(); //getting and storing the textView variable name. not the variable
                Log.i("regex output",tempStringOriginal );
                String tempStringNew = tempStringOriginal.replace("varT","t");
                int resID = getResources().getIdentifier(tempStringNew, "id", getPackageName()); //getting the resource id number from the name  as android stores it as resource and give it a number
                textViewArray[i] = (TextView)findViewById(resID);
                i++;

            }//foreach loop

            return 0;
        }//functextViewarrayInit

       // =======Hide/Show======
 //please_look_at this_func
        protected int funcVisibilityShowTextView(){
            int i=0;
           // varTextViewTimer.setVisibility(View.VISIBLE); without array for each text view
            for (TextView element:textViewArray) {

                textViewArray[0].setVisibility(View.VISIBLE);
                i++;
            }//funcVisibilityShowTextView

            return 0;
        }//funcVisibilityShowTextView
     //please_look_at this_func
        protected int funcVisibilityHideTextView(){
            int i=0;
            // varTextViewTimer.setVisibility(View.VISIBLE); without array for each text view
            for (TextView element:textViewArray) {

                textViewArray[i].setVisibility(View.INVISIBLE);
                i++;
            }//funcVisibilityHideTextView

            return 0;
        }//funcVisibilityHideTextView

        // ==========================Content display=========================//

        protected void funcTimerSet(){
           final Handler handler = new Handler();

            Runnable run =new Runnable() {
                @Override
                public void run() {
                    Log.i("Number of second passed","1");
                    handler.postDelayed(this,1000);
                }
            };
            handler.post(run);

        }//funcTimerSet
    //please_look_at this_func
        protected void funcTimeDisplay(){}{
            int i; //setting to 30 seconds
            for(i=30;i>=0;i--){
                Log.i("Timer for loop called",Integer.toString(i));
           // varTextViewTimer.setText(Integer.toString(i) + "S");
             //  textViewArray[0].setText(Integer.toString(i));// was getting nullpointer exception
                textViewArray[0].getText();
               // funcTimerSet();
            }//for loop
        }//funcTimeDisplay

        protected void funcTimeSetAndDisplay(){
            final Handler handler = new Handler();

            Runnable run =new Runnable() {
                @Override
                public void run() {
                    int i=30; //setting to 30 seconds
                   // for(i=30;i>=0;i--) {
                        Log.i("Timer for loop called", Integer.toString(i));
                       // Log.i("Number of second passed", "1");
                        handler.postDelayed(this, 1000);
                       // textViewArray[0].setText(Integer.toString(i));
                    }//forloop
               // }
            };
            handler.post(run);

        }
       // ==========================Test=========================//
        protected void funcTextViewArrayPrint(){
           Log.i("prnt 1 el of arr",textViewArrayString[0].toString());
        }//funcTextViewArrayPrint


    }

=========================

堆栈跟踪

08-20 12:53:36.929 16470-16470/? I/art: Late-enabling -Xcheck:jni
08-20 12:53:36.959 16470-16470/? D/TidaProvider: TidaProvider()
08-20 12:53:37.149 16470-16470/com.example.user.appeggtimer I/InstantRun: starting instant run server: is main process
08-20 12:53:37.249 16470-16470/? I/Timer for loop called: 30
08-20 12:53:37.269 16470-16470/? D/AndroidRuntime: Shutting down VM
08-20 12:53:37.269 16470-16470/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.user.appeggtimer, PID: 16470
                                                   java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.user.appeggtimer/com.example.user.appeggtimer.MainActivity}: java.lang.NullPointerException: Attempt to read from null array
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2241)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
                                                       at android.app.ActivityThread.access$800(ActivityThread.java:154)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:135)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5273)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
                                                    Caused by: java.lang.NullPointerException: Attempt to read from null array
                                                       at com.example.user.appeggtimer.MainActivity.<init>(MainActivity.java:113)
                                                       at java.lang.reflect.Constructor.newInstance(Native Method)
                                                       at java.lang.Class.newInstance(Class.java:1606)
                                                       at android.app.Instrumentation.newActivity(Instrumentation.java:1069)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2231)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392) 
                                                       at android.app.ActivityThread.access$800(ActivityThread.java:154) 
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308) 
                                                       at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                       at android.os.Looper.loop(Looper.java:135) 
                                                       at android.app.ActivityThread.main(ActivityThread.java:5273) 
                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                       at java.lang.reflect.Method.invoke(Method.java:372) 
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908) 
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703) 
08-20 12:53:37.279 16470-16470/? I/Process: Sending signal. PID: 16470 SIG: 9

0 个答案:

没有答案