错误。尝试调用虚拟方法.getResources()

时间:2018-07-04 09:55:55

标签: android

请您帮我找出以下错误: 我有一些字符串资源,但我已将其重命名。我的重命名是否可能导致错误? 在错误下方。

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:89)
        at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:127)
        at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:121)
        at android.support.v7.app.AppCompatActivity.getResources(AppCompatActivity.java:542)
        at com.andersen.dogsapp.dogs.DogsApp.<init>(DogsApp.java:12)

代码:

public class DogsApp extends AppCompatActivity {
// This line below has called an error
    String owner[] = getResources().getStringArray(R.array.owners);

    LayoutInflater layoutInflater;
    private LinearLayout scrollinlayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dogs_app);
        scrollinlayout = findViewById(R.id.scroll_child_linlayout);
        layoutInflater = getLayoutInflater();
        for(int i = 0; i< owner.length; i++){
            View inflatedView = layoutInflater.inflate(R.layout.owners_item, scrollinlayout, false);
            TextView textViewName = inflatedView.findViewById(R.id.owner_name);
            textViewName.setText(owner[i]);
        }
    }
}

非常感谢!

1 个答案:

答案 0 :(得分:2)

您需要在 onCreate 中执行该操作。同样,您以错误的方式定义数组。

错误

String owner[] = getResources().getStringArray(R.array.owners);

String[] owner;

这样。

public class DogsApp extends AppCompatActivity {
// This line below has called an error
    String[] owner;

    LayoutInflater layoutInflater;
    private LinearLayout scrollinlayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dogs_app);
        scrollinlayout = findViewById(R.id.scroll_child_linlayout);
        owner = getResources().getStringArray(R.array.owners);
        layoutInflater = getLayoutInflater();
        for(int i = 0; i< owner.length; i++){
            View inflatedView = layoutInflater.inflate(R.layout.owners_item, scrollinlayout, false);
            TextView textViewName = inflatedView.findViewById(R.id.owner_name);
            textViewName.setText(owner[i]);
        }
    }


}