简体   繁体   English

空指针异常android数组

[英]Null pointer exception android array

I am making an app that has 2 java classes: MainActivity and SecondActivity . 我正在制作一个有2个java类的应用程序: MainActivitySecondActivity MainActivity initiates the SecondActivity by using an onClick method. MainActivity通过使用onClick方法启动SecondActivity

The SecondActivity has 2 arrays stored in the strings.xml file. SecondActivity有两个存储在strings.xml文件中的数组。 The SecondActivity class wants to store all the array variables from strings.xml to itself, in order to use it for some methods. SecondActivity类希望将来自strings.xml的所有数组变量存储到自身,以便将其用于某些方法。 I think i am doing it the wrong way, as i tried storing the arrays directly in the SecondActivity and it worked but when i am storing the arrays in strings.xml it gives a NullPointerException . 我认为我这样做是错误的,因为我尝试将数组直接存储在SecondActivity并且它工作但是当我将数组存储在strings.xml中时它会产生NullPointerException

Here is the SecondActivity code: 这是SecondActivity代码:

package com.android.ict.seneca.androidpocketguide;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SecondActivity extends Activity {

    private final String CLASS_NAME = "SecondActivity";

    String [] Vocabularies = getResources().getStringArray(R.array.Vocabularies_array);
    String [] meanings = getResources().getStringArray(R.array.meanings_array);

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

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this,
                android.R.layout.simple_dropdown_item_1line, Vocabularies);

        //ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, meanings);

        AutoCompleteTextView textView =
                (AutoCompleteTextView) findViewById(R.id.vocabularies);

        textView.setThreshold(2); // minimum number of characters to be typed

        textView.setAdapter(adapter); // connect the list of suggestions to the View object

    }

    public void onStart(){
        super.onStart();
        Log.d( CLASS_NAME, "onStart invoked!" );
    }

    public void onPause(){
        super.onPause();
        Log.d( CLASS_NAME, "onPause invoked!!" );
    }

    public void onResume(){
        super.onResume();
        Log.d( CLASS_NAME, "onResume invoked!!" );
    }

    public void onStop(){
        super.onStop();
        Log.d( CLASS_NAME, "onStop invoked!!!" );
    }

    public void onDestroy(){
        super.onDestroy();
        Log.d( CLASS_NAME, "onDestroy INVOKED!!!" );
    }

    public void onRestart(){
        super.onRestart();
        Log.d( CLASS_NAME, "onRestart invoked!!" );
    }

    // event handler for the button
    public void onClick(View view) {


        Intent data = new Intent();

        EditText usr =
                (EditText) findViewById(R.id.vocabularies); // get user input

        // set the data part (an URI reference) of an intent
        data.setData(Uri.parse(usr.getText().toString()));
        String s = data.getData().toString();

        int flag = 0;

        for(int i=0; i<Vocabularies.length;i++)
        {
            if(s.equals(Vocabularies[i]))
            {
                flag = i;
            }
        }

        Toast.makeText(this, "YOU'VE ENTERED: " + s, Toast.LENGTH_LONG ).show();

        String m = meanings[flag];
        String disp = "Vocabulary: " + s + "\n" + "Meaning: " + m;

        TextView textViewObj1 = (TextView) findViewById(R.id.meaning);
        textViewObj1.setText(disp);

        //finish();   //--- close the activity AND RETURN CONTROL TO THE REQUESTING ACTIVITY


        //EditText txt_username = (EditText) findViewById(R.id.txt_username);
    } // end onClick
}

Here is the MainActivity code: 这是MainActivity代码:

package com.android.ict.seneca.androidpocketguide;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private final String CLASS_NAME = "FirstActiviy";
    private int request_Code = 1;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d( CLASS_NAME, "onCreate invoked!" );
    }

    public void onStart(){
        super.onStart();
        Log.d( CLASS_NAME, "onStart invoked!" );
    }

    public void onPause(){
        super.onPause();
        Log.d( CLASS_NAME, "onPause invoked!!" );
    }

    public void onResume(){
        super.onResume();
        Log.d( CLASS_NAME, "onResume invoked!!" );
    }

    public void onStop(){
        super.onStop();
        Log.d( CLASS_NAME, "onStop invoked!!!" );
    }

    public void onDestroy(){
        super.onDestroy();
        Log.d( CLASS_NAME, "onDestroy INVOKED!!!" );
    }

    public void onRestart(){
        super.onRestart();
        Log.d( CLASS_NAME, "onRestart invoked!!" );
    }


    // event handler for the button (activity 2)
    public void onClick(View view) {

        startActivityForResult( new Intent(
                        "com.android.ict.seneca.androidpocketguide.second"), // declared  by an intent filter
                request_Code);   // (requesting) activity ID

        Log.d( CLASS_NAME, "after startActivityForResult" );
//intent.setData(Uri.parse("com.seneca.lab2b.abbas"));
        //startActivity(intent);
    }

    /*
    public void onActivityResult( int requestCode,   // used to match the REQUESTING activity ID
                                  int resultCode,    // result code set by the sender (i.e. the TARGET activity)
                                  Intent data )      // an intent passed by the sender (i.e. the TARGET activity)
    {
        if (requestCode == request_Code) {
            if (resultCode == RESULT_OK) {


                //TextToSpeech(data.getData().toString());

                Intent intent = getIntent();

                String s = data.getData().toString();

                TextView textViewObj1 = (TextView) findViewById(R.id.line);
                textViewObj1.setText(s);


                Toast.makeText(
                        this,
                        "MESSAGE RECEIVED: " + s,  // retrieve data from the intent
                        // API Question: What is the  return type of getData()?
                        Toast.LENGTH_LONG ).show();
            }
        }
        Log.d( CLASS_NAME, "onActivityResult: what is next?" );
    }


    // event handler for a button (activity 3)
    public void onClick3(View view) {

        Intent dataIntent = new Intent( this, ThirdActivity.class );//"com.seneca.lab2b.third"); // explicit intent

        // the putExtra( ) method
        dataIntent.putExtra( "greeting", "Good morning  Android!" );
        dataIntent.putExtra( "number", 123 );

        // create a Bundle object
        Bundle bundle = new Bundle();
        bundle.putString( "My name", "Abbas Zoeb" );
        bundle.putInt( "Student ID", 56789  );

        // putExtras( ): store the bundle in the intent
        dataIntent.putExtras( bundle );

        // launch the third activity
        startActivity( dataIntent );

        //startActivity( new Intent( this, ThirdActivity.class ) );

    }
    */

}

Here is the error log: 这是错误日志:

09-21 23:43:19.907 26183-26183/com.android.ict.seneca.androidpocketguide E/AndroidRuntime: FATAL EXCEPTION: main Process: com.android.ict.seneca.androidpocketguide, PID: 26183 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.android.ict.seneca.androidpocketguide/com.android.ict.seneca.androidpocketguide.SecondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' 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 09-21 23:43:19.907 26183-26183 / com.android.ict.seneca.androidpocketguide E / AndroidRuntime:FATAL EXCEPTION:main进程:com.android.ict.seneca.androidpocketguide,PID:26183 java.lang.RuntimeException:无法实例化活动ComponentInfo {com.android.ict.seneca.androidpocketguide / com.android.ict.seneca.androidpocketguide.SecondActivity}:java.lang.NullPointerException:尝试调用虚拟方法'android.content.res.Resources android。在android.app.ActivityThread的android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)的android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)上的null对象引用上的content.Context.getResources()'。 -wrap11(ActivityThread.java)在android.app.A活动上运行android.app.A.运行时在Android.os.Handler.dispatchMessage(Handler.java:102)的android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1344)。(Looper。 java:148)在android.app.ActivityThread.main(ActivityThread.java:5417)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.content.res.Resources android.content.Context.getResources()' on a null object reference at android.content.ContextWrapper.getResources(ContextWrapper.java:87) at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81) at com.android.ict.seneca.androidpocketguide.SecondActivity.(SecondActivity.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.dispatchM 方法)com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:726)at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)引起:java.lang.NullPointerException :尝试在android.view.ContextThemeWrapper上的android.content.ContextWrapper.getResources(ContextWrapper.java:87)上的空对象引用上调用虚拟方法'android.content.res.Resources android.content.Context.getResources()' .getResources(ContextThemeWrapper.java:81)位于android.app.Instrumentation.newActivity的java.lang.Class.newInstance(Native Method)中的com.android.ict.seneca.androidpocketguide.SecondActivity。(SecondActivity.java:22)。 Instrumentation.java:1067)在Android.app.A活动中的android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)以及android.app.ActivityThread.-wrap11(ActivityThread.java)的android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)在android.app.Handler.dispatchM的android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1344) essage(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) 在android.app.Looper.loop(Looper.java:148)的android.app.ActivityThread.main(ActivityThread.java:5417)的java.lang.reflect.Method.invoke上的essage(Handler.java:102)方法)com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:726)com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Here is the string.xml file: 这是string.xml文件:

<resources>
    <string name="app_name">Android Pocket Guide</string>
    <string-array name="Vocabularies_array">
        <item>activity</item>
        <item>AVD</item>
        <item>ART</item>
        <item>Dalvik</item>
        <item>intent</item>
        <item>intent filter</item>
        <item>explicit intent</item>
        <item>implicit intent</item>
        <item>LogCat</item>
        <item>bundle</item>
        <item>Gradle</item>
        <item>Android Device Monitor</item>
        <item>SDK manager</item>
        <item>minSdkVersion</item>
    </string-array>

    <string-array name="meanings_array">
        <item>An activity represents a single screen with a user interface just like window or frame of Java</item>
        <item>An Android Virtual Device (AVD) is an emulator configuration that lets you model an actual device by defining hardware and software options to be emulated by the Android Emulator.</item>
        <item>Android Runtime (ART) is an application runtime environment used by the Android operating system.</item>
        <item>Dalvik is a part of the software stack that makes up the Android platform.</item>
        <item>Intent can be defined as a simple message objects which is used to communicate from 1 activity to another.</item>
        <item>Specifies the types of intents that an activity, service, or broadcast receiver can respond to</item>
        <item>An explicit intent is one that you use to launch a specific app component, such as a particular activity or service in your app</item>
        <item>Implicit intents do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it.</item>
        <item>Logcat is a command-line tool that dumps a log of system messages, including stack traces when the device throws an error and messages that you have written from your app with the Log class.</item>
        <item>A Bundle is a set of key/value pairs, where it implements an interface called Parcelable.</item>
        <item>Gradle is a custom build tool used to build android packages (apk files) by managing dependencies and providing custom build logic.</item>
        <item>Android Device Monitor is a standalone tool that provides a UI for several Android application debugging and analysis tools.</item>
        <item>A software development kit that enables developers to create applications for the Android platform.</item>
        <item>An integer designating the minimum API Level required for the application to run.</item>
    </string-array>


</resources>

Try this way 试试这种方式

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        Vocabularies = getResources().getStringArray(R.array.Vocabularies_array);
        meanings = getResources().getStringArray(R.array.meanings_array);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this,
                android.R.layout.simple_dropdown_item_1line, Vocabularies);

        //ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, meanings);

        AutoCompleteTextView textView =
                (AutoCompleteTextView) findViewById(R.id.vocabularies);

        textView.setThreshold(2); // minimum number of characters to be typed

        textView.setAdapter(adapter); // connect the list of suggestions to the View object

    }

Try declaring your arrays in the global context, then assigning them some value during one of the activity's lifecycle stages (ie onCreate(), onResume(), etc.). 尝试在全局上下文中声明您的数组,然后在其中一个活动的生命周期阶段(即onCreate(),onResume()等)中为它们分配一些值。

The issue you're having is with getResources() . 你遇到的问题是getResources() I would create a global variable of type Context . 我将创建一个Context类型的全局变量。 Then, what I would do in onCreate() is this: 那么,我在onCreate()会做的是:

context = this;
vocabularies = context.getResources().getStringArray(R.array.Vocabularies_array);
meanings = context.getResources().getStringArray(R.array.meanings_array);

Hope that helps! 希望有所帮助!

These variable initializations... 这些变量初始化......

String [] Vocabularies = getResources().getStringArray(R.array.Vocabularies_array);
String [] meanings = getResources().getStringArray(R.array.meanings_array);

...probably need to go in a constructor, or even more likely in onCreate(...) , specifically after ...可能需要进入构造函数,甚至更有可能进入onCreate(...) ,特别是之后

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

Initialization of the variables in some method like oncreate/onPostcreated eg 在某些方法中初始化变量,如oncreate / onPostcreated,例如

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Vocabularies = getResources().getStringArray(R.array.Vocabularies_array);
    meanings = getResources().getStringArray(R.array.meanings_array);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_dropdown_item_1line, Vocabularies);

    //ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, meanings);

    AutoCompleteTextView textView =
            (AutoCompleteTextView) findViewById(R.id.vocabularies);

    textView.setThreshold(2); // minimum number of characters to be typed

    textView.setAdapter(adapter); // connect the list of suggestions to the View object

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM