2017-01-20 9 views
-1

私はアンドロイドに新しく、チュートリアルを使ってアプリケーションのSQLiteデータベースについて教えています。 DatabaseHelperイメージとSQLiteデータベース

public class DatabaseHelper extends SQLiteOpenHelper { 

// Table Name 
public static final String TABLE_NAME = "COUNTRIES"; 

// Table columns 
public static final String _ID = "_id"; 
public static final String SUBJECT = "subject"; 
public static final String DESC = "description"; 
public static final String KEY_IMAGE = "image"; 

// Database Information 
static final String DB_NAME = "JOURNALDEV_COUNTRIES.DB"; 

// database version 
static final int DB_VERSION = 5; 

// Creating table query 
private static final String CREATE_TABLE = "create table " + TABLE_NAME + "(" + _ID 
     + " INTEGER PRIMARY KEY AUTOINCREMENT, " + SUBJECT + " TEXT NOT NULL, " + DESC + " TEXT," + 
     KEY_IMAGE + " BLOB);"; 

public DatabaseHelper(Context context) { 
    super(context, DB_NAME, null, DB_VERSION); 
} 

@Override 
public void onCreate(SQLiteDatabase db) { 
    db.execSQL(CREATE_TABLE); 
} 

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); 
    onCreate(db); 
} 

public void insertBitmap(Bitmap bm) { 

    // Convert the image into byte array 
    ByteArrayOutputStream out = new ByteArrayOutputStream(); 
    bm.compress(Bitmap.CompressFormat.JPEG, 100, out); 
    byte[] buffer=out.toByteArray(); 
    // Open the database for writing 
    SQLiteDatabase db = this.getWritableDatabase(); 
    // Start the transaction. 
    db.beginTransaction(); 
    ContentValues values; 

    try 
    { 
     values = new ContentValues(); 
     values.put("image", buffer); 
     // Insert Row 
     long i = db.insert(TABLE_NAME, null, values); 
     Log.i("Insert", i + ""); 
     // Insert into database successfully. 
     db.setTransactionSuccessful(); 

    } 
    catch (SQLiteException e) 
    { 
     e.printStackTrace(); 

    } 
    finally 
    { 
     db.endTransaction(); 
     // End the transaction. 
     db.close(); 
     // Close database 
    } 
} 

public Bitmap getBitmap(int id){ 
    Bitmap bitmap = null; 
    // Open the database for reading 
    SQLiteDatabase db = this.getReadableDatabase(); 
    // Start the transaction. 
    db.beginTransaction(); 

    try 
    { 
     String selectQuery = "SELECT * FROM "+ TABLE_NAME+" WHERE id = " + id; 
     Cursor cursor = db.rawQuery(selectQuery, null); 
     if(cursor.getCount() >0) 
     { 
      while (cursor.moveToNext()) { 
       // Convert blob data to byte array 
       byte[] blob = cursor.getBlob(cursor.getColumnIndex("image")); 
       // Convert the byte array to Bitmap 
       bitmap= BitmapFactory.decodeByteArray(blob, 0, blob.length); 

      } 

     } 
     db.setTransactionSuccessful(); 

    } 
    catch (SQLiteException e) 
    { 
     e.printStackTrace(); 

    } 
    finally 
    { 
     db.endTransaction(); 
     // End the transaction. 
     db.close(); 
     // Close database 
    } 
    return bitmap; 

} } 

のDatabaseManager

現在、私はSQLiteの内の画像に対処する方法に問題があるとのTextViewの説明とリストビューでそれを示しています...これらは私のクラスであります

public class DBManager { 

    private DatabaseHelper dbHelper; 

private Context context; 

private SQLiteDatabase database; 

public DBManager(Context c) { 
    context = c; 
} 

public DBManager open() throws SQLException { 
    dbHelper = new DatabaseHelper(context); 
    database = dbHelper.getWritableDatabase(); 
    return this; 
} 

public void close() { 
    dbHelper.close(); 
} 

public void insert(String name, String desc, String image) { 
    ContentValues contentValue = new ContentValues(); 
    contentValue.put(DatabaseHelper.SUBJECT, name); 
    contentValue.put(DatabaseHelper.DESC, desc); 
    contentValue.put(DatabaseHelper.KEY_IMAGE, image); 
    database.insert(DatabaseHelper.TABLE_NAME, null, contentValue); 
} 

public Cursor fetch() { 
    String[] columns = new String[] { DatabaseHelper._ID, DatabaseHelper.SUBJECT, DatabaseHelper.DESC, 
      DatabaseHelper.KEY_IMAGE }; 
    Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null); 
    if (cursor != null) { 
     cursor.moveToFirst(); 
    } 
    return cursor; 
} 

public int update(long _id, String name, String desc, String image) { 
    ContentValues contentValues = new ContentValues(); 
    contentValues.put(DatabaseHelper.SUBJECT, name); 
    contentValues.put(DatabaseHelper.DESC, desc); 
    contentValues.put(DatabaseHelper.KEY_IMAGE, image); 
    int i = database.update(DatabaseHelper.TABLE_NAME, contentValues, DatabaseHelper._ID + " = " + _id, null); 
    return i; 
} 

public void delete(long _id) { 
    database.delete(DatabaseHelper.TABLE_NAME, DatabaseHelper._ID + "=" + _id, null); 
} 

} 

CountryListActivity

public class CountryListActivity extends ActionBarActivity { 

private DBManager dbManager; 

private ListView listView; 

private SimpleCursorAdapter adapter; 


final String[] from = new String[] { 
     DatabaseHelper.SUBJECT, DatabaseHelper.DESC, DatabaseHelper.KEY_IMAGE }; 

final int[] to = new int[] { R.id.title, R.id.desc, R.id.ivSlika }; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.fragment_emp_list); 

    dbManager = new DBManager(this); 
    dbManager.open(); 
    Cursor cursor = dbManager.fetch(); 

    listView = (ListView) findViewById(R.id.list_view); 
    listView.setEmptyView(findViewById(R.id.empty)); 

    adapter = new SimpleCursorAdapter(this, R.layout.activity_view_record, cursor, from, to, 0); 
    adapter.notifyDataSetChanged(); 

    listView.setAdapter(adapter); 

    // OnCLickListiner For List Items 
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long viewId) { 
      //TextView idTextView = (TextView) view.findViewById(R.id.id); 
      TextView titleTextView = (TextView) view.findViewById(R.id.title); 
      TextView descTextView = (TextView) view.findViewById(R.id.desc); 
      ImageView slikaImageView = (ImageView) findViewById(R.id.ivSlika); 

      //String id = idTextView.getText().toString(); 
      String title = titleTextView.getText().toString(); 
      String desc = descTextView.getText().toString(); 
      String image = slikaImageView.toString(); 

      //ByteArrayOutputStream blob = new ByteArrayOutputStream(); 
      //byte[] bitmapdata = blob.toByteArray(); 
      //Bitmap bm = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length); 

      Intent modify_intent = new Intent(getApplicationContext(), ModifyCountryActivity.class); 
      modify_intent.putExtra("title", title); 
      modify_intent.putExtra("desc", desc); 
      //modify_intent.putExtra("id", id); 
      modify_intent.putExtra("image", image); 


      startActivity(modify_intent); 
     } 
    }); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 

    int id = item.getItemId(); 
    if (id == R.id.add_record) { 

     Intent add_mem = new Intent(this, AddCountryActivity.class); 
     startActivity(add_mem); 

    } 
    return super.onOptionsItemSelected(item); 
} 

} 

私はListViewに画像を入れようとしましたが、ListViewだけがテキストを表示するので動作しているようには見えません。私は上記のコードを使ってみましたが、うまくいきませんでした。

ListViewに画像を表示してSQLiteに保存すると、アプリを再起動した後に再び表示されるようにするにはどうすればよいですか?

ありがとうございます!

+0

いいえ、してください。 **データベースに画像を保存してはいけません。あなたが望む場所に保存しますが、 'database'と' sharedpreferences' – Ekalips

+0

データベースに画像を保存しないでください。アプリのプライベートストレージに画像を保存し、パスをデータベーステーブルに保存します。 2ndカスタムアダプタを使って 'ListView'で画像を表示する –

+0

@SharpEdge自分のコードを修正するのに役立つでしょうか? – Subject

答えて

0

まず、イメージをデータベースに保存しないでください。アプリケーションのディレクトリやキャッシュに画像をファイルとして保存し、URIをデータベースのファイルに保存する必要があります。または、アプリケーションにリソースとして含めてください。

第2に、画像はどこから来ますか?彼らはアプリ自体によって生成されたものなのでしょうか、あるいはあなたのサーバーからそれらをダウンロードしていますか?後者の場合は、ライブラリを調べてそれを処理するのを助けてください。Picassoのようにうまくいくでしょう。

最後に、ListViewを使用して、あなたの人生をもっと難しくしないでください。より良いAPIとして、RecyclerViewをご覧ください。

+0

こんにちはvkislicins、私はすぐに上記のあなたの答えのすべての最初のについては、Base64に画像をエンコードし、データベースに文字列を格納することについて尋ねることができますか?それは何か大丈夫ですか? – chirag90

+1

ちょっと@ chirag90。それをやりたい理由がありますか? Base64エンコーディングは、ファイル表現をdbに格納しているという事実を変更しません。私の意見では、ファイルではなく参照を保管してください。データベースとの間であまりにも多くのデータを読み書きする必要はありません。また、通常はAndroidによってバックアップされるため、データベースの膨大化を避けます。 – vkislicins

+0

こんにちは、それは私が知りたいと思っただけの完璧な意味がありません。説明してくれてありがとう。 – chirag90

関連する問題