在非 Activity 类中引用 String 时出现 java.lang.NullPointerException,即使在传入 Context 时也是如此

标签 java android nullpointerexception android-context

<分区>

我想通过使用在我的非 Activity 类中引用字符串资源

context.getString(R.string.E_mc2)

知道这个类没有上下文,看完才知道this question我必须使用构造函数从具有上下文的类传递上下文。如以下构造函数所示,我将上下文作为非 Activity 类中的参数并将其分配给变量。

Context context;

    //constructor for class MyDataProvider
    public MyDataProvider(Context context){
        putInCommonMap();
        putInElectromagneticMap();
        this.context = context;
    }

然后我尝试通过使用它为它提供上下文来在我的 Activity 中创建一个实例:

MyDataProvider dp = new MyDataProvider(this);

虽然它允许我运行程序,但当我尝试将字符串包含在我的数据中时,我仍然得到 NullPointerException。我的 logcat 在下面,如果有帮助的话:

--------- beginning of crash
06-16 11:14:48.160 2900-2900/com.gmd.referenceapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.gmd.referenceapplication, PID: 2900
                                                                            java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gmd.referenceapplication/com.gmd.referenceapplication.CommonConstants}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getString(int)' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                                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 'java.lang.String android.content.Context.getString(int)' on a null object reference
                                                                                at com.gmd.referenceapplication.MyDataProvider.<init>(MyDataProvider.java:24)
                                                                                at com.gmd.referenceapplication.CommonConstants.onCreate(CommonConstants.java:37)
                                                                                at android.app.Activity.performCreate(Activity.java:6237)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                                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) 

我已经研究了这个问题,但似乎无法找到我做错了什么,所以我很感激任何和所有的帮助。谢谢!

编辑:

对不起大家,这是通用常量:

package com.gmd.referenceapplication;

import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ListView;

import com.gmd.referenceapplication.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;



public class CommonConstants extends AppCompatActivity {
    View view;


    //finds view and hashmap, passes to adapter to display
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_common_constants);


        MyDataProvider dp = new MyDataProvider(this);

        ExpandableListView view;
        view = (ExpandableListView) findViewById(R.id.expandableList);
        HashMap constantsHashMap;
        constantsHashMap = dp.getCommonMap();
        ArrayList constantsHashMapKeys = new ArrayList<String>(constantsHashMap.keySet());

        MyCustomAdapter adapter = new MyCustomAdapter(this, constantsHashMap, constantsHashMapKeys);
        view.setAdapter(adapter);


//creates toolbar
        Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(myToolbar);

    }



//manages app bar
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.overflow, menu);
    return true;
}




    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.constants:
                startActivity(new Intent(this, FundamentalPhysicalConstants.class));
                return true;

            case R.id.joes_rules:
                //go to rules
                //startActivity(new Intent(this, ExampleListView.class));
                return true;

            case R.id.home:
                //Go back to the home screen
                startActivity(new Intent(this, MainActivity.class));
                return true;

            case R.id.search:
                //open search
                return true;

            default:
                // If we got here, the user's action was not recognized.
                // Invoke the superclass to handle it.
                return super.onOptionsItemSelected(item);

        }
    }

}

这里是 MyDataProvider:

package com.gmd.referenceapplication;

import android.content.Context;

import java.util.HashMap;
import java.util.Map;


/**
 * Created by gmd on 6/13/2016.
 */

public class MyDataProvider {

    Context context;

    //constructor for class MyDataProvider
    public MyDataProvider(Context context1){
        context=context1;
        putInCommonMap();
        putInElectromagneticMap();

    }
    //strings for sub and superscript
    String test = context.getString(R.string.E_mc2);

    //data for common constants
    ListViewItem constant_common_data[] = new ListViewItem[]
            {
                    new ListViewItem(R.drawable.star, "Atomic Mass Constant", "1.660 539 040 e-27", "kg", "0.000 000 020 e-27"),
                    new ListViewItem(R.drawable.star, "Avogadro Constant", "6.022 140 857 e23"," mol^-1", "0.000 000 074 x e23"),
                    new ListViewItem(R.drawable.star, "Boltzmann Constant", "1.380 648 52 e-23", "K^-1", "0.000 000 79 e-23"),
                    new ListViewItem(R.drawable.star, "Conductance Quantum", "7.748 091 7310 e-5", "s","0.000 000 0018 e-5"),
                    new ListViewItem(R.drawable.star, "Electric Constant", "8.854 187 817... e-12", "F m^-1", "(exact)"),

                    new ListViewItem(R.drawable.star, "Electron mass", "9.109 383 56 e-31", "kg", "0.000 000 11 e-31"),
                    new ListViewItem(R.drawable.star, "Electron volt", "1.602 176 6208 e-19"," J", "0.000 000 0098 e-19"),
                    new ListViewItem(R.drawable.star, "Elementary charge ", "1.602 176 6208 e-19", "C", "0.000 000 0098 e-19"),
                    new ListViewItem(R.drawable.star, "Faraday constant ", "96 485.332 89 e-5", "C mol^-1", "0.000 59"),
                    new ListViewItem(R.drawable.star, "Fine-structure constant ", "7.297 352 5664 e-3", "  ", "0.000 000 0017 e-3"),

                    new ListViewItem(R.drawable.star, "Inverse fine-structure constant", "137.035 999 139", "  ", "0.000 000 031"),
                    new ListViewItem(R.drawable.star, "Magnetic constant", "4pi e-7 = 12.566 370 614... e-7"," N A^-2", "(exact)"),
                    new ListViewItem(R.drawable.star, "Magnetic Flux Quantum", "2.067 833 831 e-15", "Wb", "0.000 000 013 e-15"),
                    new ListViewItem(R.drawable.star, "Molar Gas constant", "8.314 4598", "J mol^-1 K^-1", "0.000 0048"),
                    new ListViewItem(R.drawable.star, "Newtonian constant of gravitation ", "6.674 08 e-11", "m^3 kg^-1 s^-2", "0.000 31 e-11"),

                    new ListViewItem(R.drawable.star, "Planck constant", "6.626 070 040 e-34", "J s", "0.000 000 081 e-34"),
                    new ListViewItem(R.drawable.star, "Planck constant over 2 pi", "1.054 571 800 e-34"," J s", "0.000 000 013 e-34"),
                    new ListViewItem(R.drawable.star, "Proton Mass", "1.672 621 898 e-27", "kg", "0.000 000 021 e-27"),
                    new ListViewItem(R.drawable.star, "Proton-Electron Mass Ratio", "1836.152 673 89", "  ", "0.000 000 17"),
                    new ListViewItem(R.drawable.star, "Rydberg constant", "10 973 731.568 508", "m^-1", "0.000 065"),

                    new ListViewItem(R.drawable.star, "Speed of Light in Vacuum", "299 792 458", "m s^-1", "(exact)"),
                    new ListViewItem(R.drawable.star, "Stefan-Boltzmann constant", "5.670 367 e-8", "Wm^-2 K^-4", "0.000 013 e-8"),

                    new ListViewItem(R.drawable.star, "Bohr Radius", "0.529 177 210 67 e-10", "m", "0.000 000 000 12 e-10"),
                    new ListViewItem(R.drawable.star, "Bohr Magneton ", "927.400 9994 e-26"," J T^-1", "0.000 0057 e-26"),
                    new ListViewItem(R.drawable.star, "Josephson constant", "483 597.8525 e9", "Hz V^-1", "0.0030 e9"),
                    new ListViewItem(R.drawable.star, "Von Klitzing constant", "25 812.807 4555", "Ohm", "0.000 0059"),
                    new ListViewItem(R.drawable.star, "Unified Atomic Mass Unit", "1.660 539 040 e-27"+ test , "kg", "0.000 000 020 e-27")
            };
    HashMap<String,ListViewItem> commonMap = new HashMap<String, ListViewItem>();

//data entry for electromagnetic constants
    ListViewItem constant_electromagnetic_data[] = new ListViewItem[]
            {
                    new ListViewItem(R.drawable.star, "Bohr Magneton ", "927.400 9994 e-26"," J T^-1", "0.000 0057 e-26"),
                    new ListViewItem(R.drawable.star, "Bohr magneton in (eV)/T", "5.788 381 8012 e-5", "(eV)/T", "0.000 000 0026 e-5"),
                    new ListViewItem(R.drawable.star, "Bohr magneton in Hz/T", "13.996 245 042 e9"," Hz T^-1", "0.000 000 086 e9"),
                    new ListViewItem(R.drawable.star, "Bohr magneton in inverse meters per tesla", "46.686 448 14", "m^-1 T^-1", "0.000 000 29"),
                    new ListViewItem(R.drawable.star, "Bohr magneton in K/T", "0.671 714 05", "K T^-1","0.000 000 39"),
                    new ListViewItem(R.drawable.star, "Conductance Quantum", "7.748 091 7310 e-5", "s","0.000 000 0018 e-5"),

                    new ListViewItem(R.drawable.star, "Elementary charge ", "1.602 176 6208 e-19", "C", "0.000 000 0098 e-19"),
                    new ListViewItem(R.drawable.star, "Electron volt", "1.602 176 6208 e-19"," J", "0.000 000 0098 e-19"),
                    new ListViewItem(R.drawable.star, "Elementary charge ", "1.602 176 6208 e-19", "C", "0.000 000 0098 e-19"),
                    new ListViewItem(R.drawable.star, "elementary charge over h", "2.417 989 262 e14", "A J^-1", "0.000 000 015 e14"),
                    new ListViewItem(R.drawable.star, "inverse of conductance quantum", "12 906.403 7278", "Ohms", "0.000 0029"),

                    new ListViewItem(R.drawable.star, "Josephson constant", "483 597.8525 e9", "Hz V^-1", "0.0030 e9"),
                    new ListViewItem(R.drawable.star, "Magnetic Flux Quantum", "2.067 833 831 e-15", "Wb", "0.000 000 013 e-15"),
                    new ListViewItem(R.drawable.star, "nuclear magneton", "5.050 783 699 e-27", "J T^-1", "0.000 000 031 e-27"),
                    new ListViewItem(R.drawable.star, "nuclear magneton in (eV)/T ", "3.152 451 2550 e-8", "(eV)/T", "0.000 000 0015 e-8"),

                    new ListViewItem(R.drawable.star, "nuclear magneton in inverse meters per tesla", "2.542 623 432 e-2", "m^-1 T^-1", "0.000 000 016 e-2"),
                    new ListViewItem(R.drawable.star, "nuclear magneton in K/T", "3.658 2690 e-4","K T^-1", "0.000 0021"),
                    new ListViewItem(R.drawable.star, "nuclear magneton in MHz/T ", "7.622 593 285", "MHz T^-1", "0.000 000 047"),
                    new ListViewItem(R.drawable.star, "Von Klitzing constant", "25 812.807 4555", "Ohm", "0.000 0059")
            };

    HashMap<String,ListViewItem> electromagneticMap = new HashMap<String, ListViewItem>();


    //data entry for Atomic and nuclear constants :(
    ListViewItem constant_atomic_data[] = new ListViewItem[]
            {
                    new ListViewItem(R.drawable.star, "alpha particle mass", "6.644 657 230 e-27"," kg", "0.000 000 082 e-27"),
                    new ListViewItem(R.drawable.star, "alpha particle mass energy equivalent", "5.971 920 097 e-10", "J", "0.000 000 073 e-10"),
                    new ListViewItem(R.drawable.star, "alpha particle mass energy equivalent in MeV ", "3727.379 378"," MeV", "0.000 023"),
                    new ListViewItem(R.drawable.star, "alpha particle mass in u", "4.001 506 179 127", "u", "0.000 000 000 063"),
                    new ListViewItem(R.drawable.star, "alpha particle molar mass", "4.001 506 179 127 e-3", "mol^-1","0.000 000 000 063 e-3"),
                    new ListViewItem(R.drawable.star, "alpha particle-electron mass ratio", "7294.299 541 36", "(none)","0.000 000 24"),

                    new ListViewItem(R.drawable.star, "alpha particle-proton mass ratio ", "3.972 599 689 07", "(none)", "0.000 000 000 36"),
                    new ListViewItem(R.drawable.star, "Bohr Radius", "0.529 177 210 67 e-10", "m", "0.000 000 000 12 e-10"),
                    new ListViewItem(R.drawable.star, "classical electron radius", "2.817 940 3227 e-15","m", "0.000 000 0019 e-15"),
                    new ListViewItem(R.drawable.star, "Compton wavelength", "2.426 310 2367 e-12", "m", "0.000 000 0011 e-12"),

                    new ListViewItem(R.drawable.star, "Compton wavelength over 2 pi", "386.159 267 64 e-15", "m", "0.000 000 18 e-15"),
                    new ListViewItem(R.drawable.star, "deuteron g factor ", "0.857 438 2311", "(none)", "0.000 000 0048"),

                    new ListViewItem(R.drawable.star, "deuteron magnetic moment ", "0.433 073 5040 e-26", "J T^-1", "0.000 000 0036 e-26"),
                    new ListViewItem(R.drawable.star, "deuteron magnetic moment to Bohr magneton ratio ", "0.466 975 4554 e-3", "(none)", "0.000 000 0026 e-3"),
                    new ListViewItem(R.drawable.star, "deuteron magnetic moment to nuclear magneton ratio", "0.857 438 2311", "(none)", "0.000 000 0048"),
                    new ListViewItem(R.drawable.star, "deuteron mass ", "3.343 583 719 e-27", "kg", "0.000 000 041 e-27"),

                    new ListViewItem(R.drawable.star, "deuteron mass energy equivalent ", "3.005 063 183 e-10", "J", "0.000 000 037 e-10"),
                    new ListViewItem(R.drawable.star, "deuteron mass energy equivalent in MeV", " 1875.612 928","MeV", "0.000 012"),
                    new ListViewItem(R.drawable.star, "deuteron mass in u", "2.013 553 212 745", "u", "0.000 000 000 040"),
                    new ListViewItem(R.drawable.star, "deuteron molar mass", "2.013 553 212 745 e-3", "kg mol ^-1", "0.000 000 000 040 e-3"),

                    //resume data entry here
                    new ListViewItem(R.drawable.star, "Bohr Magneton ", "927.400 9994 e-26"," J T^-1", "0.000 0057 e-26"),
                    new ListViewItem(R.drawable.star, "Bohr magneton in (eV)/T", "5.788 381 8012 e-5", "(eV)/T", "0.000 000 0026 e-5"),
                    new ListViewItem(R.drawable.star, "Bohr magneton in Hz/T", "13.996 245 042 e9"," Hz T^-1", "0.000 000 086 e9"),
                    new ListViewItem(R.drawable.star, "Bohr magneton in inverse meters per tesla", "46.686 448 14", "m^-1 T^-1", "0.000 000 29"),
                    new ListViewItem(R.drawable.star, "Bohr magneton in K/T", "0.671 714 05", "K T^-1","0.000 000 39"),
                    new ListViewItem(R.drawable.star, "Conductance Quantum", "7.748 091 7310 e-5", "s","0.000 000 0018 e-5"),

                    new ListViewItem(R.drawable.star, "Elementary charge ", "1.602 176 6208 e-19", "C", "0.000 000 0098 e-19"),
                    new ListViewItem(R.drawable.star, "Electron volt", "1.602 176 6208 e-19"," J", "0.000 000 0098 e-19"),
                    new ListViewItem(R.drawable.star, "Elementary charge ", "1.602 176 6208 e-19", "C", "0.000 000 0098 e-19"),
                    new ListViewItem(R.drawable.star, "elementary charge over h", "2.417 989 262 e14", "A J^-1", "0.000 000 015 e14"),
                    new ListViewItem(R.drawable.star, "inverse of conductance quantum", "12 906.403 7278", "Ohms", "0.000 0029"),

                    new ListViewItem(R.drawable.star, "Josephson constant", "483 597.8525 e9", "Hz V^-1", "0.0030 e9"),
                    new ListViewItem(R.drawable.star, "Magnetic Flux Quantum", "2.067 833 831 e-15", "Wb", "0.000 000 013 e-15"),
                    new ListViewItem(R.drawable.star, "nuclear magneton", "5.050 783 699 e-27", "J T^-1", "0.000 000 031 e-27"),
                    new ListViewItem(R.drawable.star, "nuclear magneton in (eV)/T ", "3.152 451 2550 e-8", "(eV)/T", "0.000 000 0015 e-8"),

                    new ListViewItem(R.drawable.star, "nuclear magneton in inverse meters per tesla", "2.542 623 432 e-2", "m^-1 T^-1", "0.000 000 016 e-2"),
                    new ListViewItem(R.drawable.star, "nuclear magneton in K/T", "3.658 2690 e-4","K T^-1", "0.000 0021"),
                    new ListViewItem(R.drawable.star, "nuclear magneton in MHz/T ", "7.622 593 285", "MHz T^-1", "0.000 000 047"),
                    new ListViewItem(R.drawable.star, "Von Klitzing constant", "25 812.807 4555", "Ohm", "0.000 0059")
            };

    HashMap<String,ListViewItem> AtomicMap = new HashMap<String, ListViewItem>();





//enters all data in common array into the common HashMap
    public void putInCommonMap(){
        for(ListViewItem i : constant_common_data) commonMap.put(i.getKey(),i);
    }

    public void putInElectromagneticMap(){
        for(ListViewItem i : constant_electromagnetic_data) electromagneticMap.put(i.getKey(),i);
    }
    //returns common hashmap
    public HashMap getCommonMap(){
        return commonMap;
    }


    //returns electromagnetic hashmap
    public HashMap getElectromagneticMap(){
        return electromagneticMap;
    }


}

这是我正在使用的适配器:

package com.gmd.referenceapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by gmd on 6/13/2016.
 */
public class MyCustomAdapter extends BaseExpandableListAdapter {

    private Context context;
    private HashMap<String,ListViewItem> constantsHashMap;
    private List<String> constantList;

    public MyCustomAdapter(Context context, HashMap<String, ListViewItem> hashMap, List<String> list){

        constantsHashMap = hashMap;
        this.context = context;
        this.constantList = list;

    }



    public View getChildView(int groupPosition,
                             int childPosition,
                             boolean isLastChild,View convertView, ViewGroup parent)  {
        String childTitle = (String) getChild(groupPosition, childPosition).toString();
        if(convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.child_layout, parent, false);
        }
        TextView childTextView = (TextView) convertView.findViewById(R.id.textViewChild);
        childTextView.setText(childTitle);
        return convertView;


    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }

    @Override
    public int getGroupCount() {
        return this.constantList.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return 1;
    }

    @Override
    public String getGroup(int groupPosition) {
        return constantList.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return constantsHashMap.get(this.constantList.get(groupPosition));
                }


    @Override
    public long getGroupId(int groupPosition) {
        return 0;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return 0;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        String groupTitle = (String) getGroup(groupPosition);
        if (convertView == null) {
            LayoutInflater inflater =
                    (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.parent_layout, parent, false);
        }
        TextView parentTextView = (TextView) convertView.findViewById(R.id.textViewParent);
        parentTextView.setText(groupTitle);
        return convertView;
        }
    }

最佳答案

您应该在分配上下文后分配您的字符串。

Context context;
String test;

public MyDataProvider(Context context){
    this.context = context;
    test = context.getString(R.string.E_mc2);
    putInCommonMap();
    putInElectromagneticMap();
}

关于在非 Activity 类中引用 String 时出现 java.lang.NullPointerException,即使在传入 Context 时也是如此,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37865575/

相关文章:

java - 如何在Java中将两个整数打包成4位short?

android - 如何解决这个 : 'Running android lint' issue

java - 如何从另一个类中的ArrayList <List> 获取数据?

java - JDK 8 错误 : Can not start NetBeans 7. 3

java - Collections.sort 排序错误列表

java - 快速修复字符串开关后的 Android 错误

java - Android WebView 未在输入类型文件上打开文件选择器或相机

android - DialogFragment圆角-如何设置透明度

android - NullPointerException when inflating ,在图形设计器中

java - 多重测试 TestNG.xml 文件导致 java.lang.NullPointerException