Java 在Android Studio中更改静态字符串
我正在从事一个编码项目,我一直遇到这个问题,我试图在Android Studio中创建一个静态文本作为当前日期,当我引用date()类时,当你尝试调试它时,应用程序会崩溃。它甚至在没有错误时崩溃Java 在Android Studio中更改静态字符串,java,android,Java,Android,我正在从事一个编码项目,我一直遇到这个问题,我试图在Android Studio中创建一个静态文本作为当前日期,当我引用date()类时,当你尝试调试它时,应用程序会崩溃。它甚至在没有错误时崩溃 public类MainActivity扩展了AppCompatActivity{ 日期=新日期(); int currentMonth=date.getMonth(); int currentDay=date.getDay(); int currentYear=date.getYear(); Strin
public类MainActivity扩展了AppCompatActivity{
日期=新日期();
int currentMonth=date.getMonth();
int currentDay=date.getDay();
int currentYear=date.getYear();
String str=getResources().getString(R.String.date\u text);
私有TextView textOut=(TextView)findViewById(R.id.date\u text);
//私人编辑文本日期=日期;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
str=currentMonth+“”+currentDay+currentYear;
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(右菜单菜单菜单主菜单);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//处理操作栏项目单击此处。操作栏将
//自动处理Home/Up按钮上的点击,只要
//在AndroidManifest.xml中指定父活动时。
int id=item.getItemId();
//noinspection SimplifiableIf语句
if(id==R.id.action\u设置){
返回true;
}
返回super.onOptionsItemSelected(项目);
}
}
请记住,strings.xml
文件中有一个名为date\u text的字符串
以下是logcat图像:
这很简单,因为您不能在方法之外调用
getResources()
。因此,以下代码不正确:
public class MainActivity extends AppCompatActivity {
...
// this is incorrect, because context for getResources() not yet initialized.
String str = getResources().getString(R.string.date_text);
...
// this incorrect, because you didn't have the context yet for finding the view.
private TextView textOut = (TextView) findViewById(R.id.date_text);
}
你需要这样的东西:
public class MainActivity extends AppCompatActivity {
...
String str;
private TextView textOut;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initializing the variables
str = getResources().getString(R.string.date_text);
// bind the view after setContentView method and before used.
textOut = (TextView) findViewById(R.id.date_text);
str = currentMonth + " " + currentDay + currentYear;
}
...
}
对于崩溃,重要的是要详细说明Android Studio的哪个版本、哪个操作系统、崩溃发生时您采取的步骤等。错误是什么,请发布LogCather。这里有一个指向Logcat的链接