简体   繁体   English

Android 如何在课堂上访问资源?

[英]Android how can I access resources in class?

I am trying to get String app_name from resources but I keep getting a null object reference .我正在尝试从资源中获取 String app_name ,但我一直在获取空对象引用 How can I fix it?我该如何解决?

package com.testandroid;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import java.util.HashMap;


public class Test extends Activity {
    public Test() {
        try {
            String hello = getString(R.string.app_name);

        } catch (Exception e) {
            Log.d("myLogs", e.getMessage());
        }
      }
}


<resources>
    <string name = "app_name">Name</string>
</resources>
string hello = getResources().getString(R.string.app_name);

Never, never override activity's constructor, this can lead to serious problems.永远不要覆盖活动的构造函数,这会导致严重的问题。 If you need to initialise something at construction of activity, do it in onCreate, in constructor resources are NOT ready to use, so you cannot use them at this time.如果您需要在构建活动时初始化某些内容,请在 onCreate 中进行,在构造函数中资源尚未准备好使用,因此此时您无法使用它们。

public class Test extends Activity { 
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout_here);
        String hello = getString(R.string.app_name);
        Log.d("Log", hello);

}

Also this should be placed into strings.xml in values folder这也应该放在values文件夹中的strings.xml

<resources>
    <string name = "app_name">Name</string>
</resources>

Ok, the easiest way is to use Context.好的,最简单的方法是使用 Context。

public class Test extends Activity {
    public Test(Context context) {
        try {
            String hello = context.getResources().getString(R.string.app_name)

        } catch (Exception e) {
            Log.d("myLogs", e.getMessage());
        }
      }
}

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

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