【问题标题】:The method putString(String, String) in the type SharedPreferences.Editor is not applicable for the arguments (String, InputStream)SharedPreferences.Editor 类型中的 putString(String, String) 方法不适用于参数 (String, InputStream)
【发布时间】:2014-01-08 22:02:09
【问题描述】:

我正在尝试找出一种方法来保存我的 InputStream 中的数据并将其用于另一个活动。到目前为止,我已尝试按以下方式使用 sharedPreferences - 但我收到一条错误消息:

"The method putString(String, String) in the type SharedPreferences.Editor is not applicable for the arguments (String, InputStream)"

上线:

editor.putString("fileName", attachment);

如何避免这种情况?

来源:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // get the attachment's filename
    Intent theIntent = getIntent();
    String attachmentFileName = "No file name found";
    if (theIntent != null && theIntent.getData() != null) {
        Cursor c = getContentResolver().query(theIntent.getData(), null,
                null, null, null);
        c.moveToFirst();
        final int fileNameColumnId = c
                .getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
        if (fileNameColumnId >= 0)
            attachmentFileName = c.getString(fileNameColumnId);

        try {

            InputStream attachment = getContentResolver().openInputStream(
                    getIntent().getData());
            SharedPreferences preferences = PreferenceManager
                    .getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("fileName", attachment);
            editor.commit();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

【问题讨论】:

    标签: java android attachment email-attachments fileoutputstream


    【解决方案1】:

    您不能将InputStream 存储在SharedPreferences 中,因为只有原始数据(intbooleanString 等)可以这样保存。

    您应该做的是读取数据,将其保存到String,然后您可以存储字符串(see here)

    BufferedReader reader = new BufferedReader(new InputStreamReader(attachment));
    StringBuilder out = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        out.append(line);
    }
    

    那你就可以了

    editor.putString("fileName", out.toString());
    

    如果您真的想将实际的InputStream 发送到另一个活动(这很奇怪,但我该判断谁),但是,您可以使用intent.putSerializableExtra(attachment) 来做到这一点。

    【讨论】:

    【解决方案2】:

    共享首选项是一个 XML 文件,旨在存储少量信息。您正在尝试将附件文件保存到其中。这并不是共享首选项的真正设计目的。您应该将文件保存在外部或内部存储上。查看更多here

    至于你的具体错误,putString()方法的第二个参数是String。您必须将 InputStream 读入字节数组,然后将其转换为字符串(以 64 为基数?记得附件可以是二进制的),可以保存到共享首选项中。但正如我上面所说,我不认为这是你应该做的。

    【讨论】:

    【解决方案3】:

    就像其他人说的那样,Sharedpreferences 无法做到这一点,保持简单:

    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("fileName", attachmentFileName);
    editor.commit();
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 2011-12-03
    • 2013-08-20
    • 1970-01-01
    相关资源
    最近更新 更多