1

コンテンツ プロバイダに大きなファイル (ビットマップ) を保存しようとしていますが、方法がわかりません。レコードに「_data」フィールドを追加し、コンテンツ プロバイダーの openFile() メソッドをオーバーライドしました。

public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table contact ( _id integer primary key autoincrement, NAME text collate nocase, IMAGE text, _data text );");
}

public ParcelFileDescriptor openFile(Uri uri, String mode)
    throws FileNotFoundException {

    String rowID = uri.getPathSegments().get(1);
    String dir = Environment.DIRECTORY_PICTURES;

    File file = new File(getContext().getExternalFilesDir(dir), rowID);
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    int fileMode = 0;
    if (mode.contains("w"))
        fileMode |= ParcelFileDescriptor.MODE_WRITE_ONLY;
    if (mode.contains("r"))
        fileMode |= ParcelFileDescriptor.MODE_READ_ONLY;
    if (mode.contains("+"))
        fileMode |= ParcelFileDescriptor.MODE_APPEND;
    return ParcelFileDescriptor.open(file, fileMode);
}

Content Resolver の openOutputStream() メソッドを使用してビットマップを挿入しています。

ContentValues values = new ContentValues();
values.put("NAME", "abc");
Uri rowUri = cr.insert(MyContentProvider.CONTENT_URI, values);
values.put("IMAGE", rowUri.toString());
cr.update(rowUri, values, null, null);

InputStream inputStream = httpConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
try {
    Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://www.xyz.com/abc.jpg").getContent());
    bitmap.compress(Bitmap.CompressFormat.JPEG, 80, cr.openOutputStream(rowUri));
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

このようにやっていると、ファイルはSDカードに保存されますが、「_data」フィールドは空のままです。私が間違っていることは何ですか?

「_data」フィールドは自分で書く必要がありますか? このチュートリアルによると、答えは「はい」のようです。「_data」フィールドは、そのファイルのデバイス上の正確なファイル パスを使用して、insert() メソッド内に書き込まれます。レコード内の URI 参照 IMAGE は必要ありません。しかし、チュートリアルはもう何年も前のもので、このように "_data" が直接記述されている例は他に見つかりませんでした。誰かが良い例を知っていますか?

4

1 に答える 1

1

上記のチュートリアルで提案された解決策は機能します。

于 2012-12-19T17:29:08.373 に答える