我正在
Incompatible Types. Required java.lang.String Found int
这是我正在使用的:
private String[] items = {R.string.name_1, R.string.name_2};
然后我想做这样的事情:
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
strName = items[which];
if(strName.equalsIgnoreCase(R.string.name_1))
{
// call activity
}
....
}
按照@Eran
的建议更新了 private String[] items = {
getResources().getString(R.string.name_1),
getResources().getString(R.string.name_2)
};
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
strName = items[which];
if(strName.equalsIgnoreCase(getResources().getString(R.string.name_1)))
{
// call activity
}
.......
}
仍然面临如下所示的问题, FYI 我没有使用英语作为字符串
日志说:
Caused by: java.lang.NullPointerException at android.content.ContextWrapper.getResources(ContextWrapper.java:81) at com.lingual.game.MainActivity.<init>(MainActivity.java:46)
答案 0 :(得分:8)
R.string.name_1
是引用int
资源的String
标识符,您无法将其与String
进行比较。要获得String
,请参阅getResources().getString(R.string.name_1)
。
因此
if(strName.equalsIgnoreCase(R.string.name_1))
应该是
if(strName.equalsIgnoreCase(getResources().getString(R.string.name_1)))
类似地
private String[] items = {R.string.name_1, R.string.name_2};
应该是
private String[] items = {getResources().getString(R.string.name_1), getResources().getString(R.string.name_2)};
编辑:
根据您获得的以下异常,当活动尚未初始化时,看起来此代码会出现在您的活动类的构造函数中。您应该将其移至onCreate(Bundle savedInstanceState)
。
答案 1 :(得分:2)
R是所有整数值。你需要使用
getResources().getString(R.string.value);
如果你想存储整数并动态检索字符串,请使用
private int[] items = {R.string.x ..., R.string.z);
并使用
getResources().getString(items[i])
答案 2 :(得分:2)
对于字符串数组,在<string-array name="my_string_array">
<item>Name1</item>
<item>Name2</item>
<item>Name3</item>
</string-array>
中创建一个字符串数组,例如:
String[] items = getResources().getStringArray(R.array.my_string_array);
然后将其分配给您的变量,
$user = new User;
$user->fname = 'joe';
$user->lname = 'joe';
$user->email = 'joe@gmail.com';
$user->password = Hash::make('123456');
if ( ! ($user->save()))
{
dd('user is not being saved to database properly - this is the problem');
}
if ( ! (Hash::check('123456', Hash::make('123456'))))
{
dd('hashing of password is not working correctly - this is the problem');
}
if ( ! (Auth::attempt(array('email' => 'joe@gmail.com', 'password' => '123456'))))
{
dd('storage of user password is not working correctly - this is the problem');
}
else
{
dd('everything is working when the correct data is supplied - so the problem is related to your forms and the data being passed to the function');
}
答案 3 :(得分:1)
使用R.string.key返回给定键的资源ID。
你应该使用
private String[] items = {getResources().getString(R.string.name_1), getResources().getString(R.string.name_2)};