Android SharedPreferences getString - 必需的字符串,找到java.lang.String

时间:2015-09-22 17:51:25

标签: java android string

我正在学习如何在java中开发Android应用程序。我已经制作了自己的ArrayAdapter。在getView方法中,我想更改TextView使用的字符串。我想从SharedPreferences获取此字符串。

代码位于帖子的底部。

AndroidStudio告诉我这一行有错误:

String description = prefs.getString(title + "description", "missing description");

Incompatible types. Required: String, Found: java.lang.String

我知道这些事情是一回事。但由于此错误,我无法运行我的程序。我该如何摆脱它?

public class NiceAdapter<String> extends ArrayAdapter<String> {

    private SharedPreferences prefs;
    private final SharedPreferences.Editor editor;
    private ArrayList<String> items;

    public NiceAdapter(Context context, int resource, int textViewResourceId, ArrayList<String> passedItems) {
        super(context, resource, textViewResourceId, passedItems);

        items = passedItems;
        prefs = context.getSharedPreferences("NiceListPrefs", ListActivity.MODE_PRIVATE);
        editor = prefs.edit();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        convertView = super.getView(position,convertView,parent);

        TextView titleView = (TextView)convertView.findViewById(R.id.title);
        TextView descriptionView = (TextView)convertView.findViewById(R.id.description);

        String title = items.get(position);
        titleView.setText(title.toString());

        String description = prefs.getString(title + "description", "missing description");
        descriptionView.setText(description);

        return convertView;
    }
}

1 个答案:

答案 0 :(得分:2)

更改

public class NiceAdapter<String> extends ArrayAdapter<String> {

public class NiceAdapter extends ArrayAdapter<String> {

使用NiceAdapter<String>定义一个名为String的泛型类型,这不是SharedPreferences.getString期望的