为什么我的SQLite数据库再次加载我的两个图像?

时间:2014-12-06 13:33:43

标签: android database sqlite android-listview

我在drawable文件夹中有两个图像,并为我写的数据库程序插入标题。要更清楚,我将分享一些屏幕截图。

Image 1

退出并进入应用程序后,我再次显示相同的图像!!!

image2

这是我的代码。首先,我使用gettes和setter创建一个类......

  public class Restaurants {
   int _id;
   String _name;
   byte[] _image;

   public Restaurants(){

   }

   public Restaurants(int keyId,String name,byte[] image){
    this._id=keyId;
    this._name=name;
    this._image=image;
   }
   public Restaurants(String name,byte[] image){
    this._name=name;
    this._image=image;
   }

   public int getID() {
    return _id;
   }

   public void setID(int _id) {
    this._id = _id;
   }

   public String getName() {
    return _name;
   }

   public void setName(String _name) {
    this._name = _name;
   }

   public byte[] getImage() {
    return _image;
   }

   public void setImage(byte[] _image) {
    this._image = _image;
   }

 }

然后我创建一个创建数据库表的类。它还执行必要的查询。

 public class DataBaseHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME="restaurantsdb";
private static final String TABLE_RESTAURANTS ="restaurants";

private static final String KEY_ID = "id";
private static final String KEY_NAME="name";
private static final String KEY_IMAGE = "image";

public DataBaseHelper(Context context) {
    super(context,DATABASE_NAME,null,DATABASE_VERSION);
    // TODO Auto-generated constructor stub
}
//CREATE TABLE
@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    String CREATE_TABLE_RESTAURANTS = "CREATE TABLE " + TABLE_RESTAURANTS + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_IMAGE + " BLOB" + ")";
    db.execSQL(CREATE_TABLE_RESTAURANTS);
}
//upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    //DROP TABLE IF EXISTS

}
//Now it's time for CRUD operations!
public void addRestaurants(Restaurants restaurants){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, restaurants._name);
    values.put(KEY_IMAGE, restaurants._image);

    db.insert(TABLE_RESTAURANTS, null, values);
    db.close();
}
//getting single restaurant
Restaurants getRestaurants(int id){
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_RESTAURANTS,
            new String[]{KEY_ID,KEY_NAME,KEY_IMAGE},KEY_ID+"=?",
            new String[]{String.valueOf(id)},null,null,null,null);

            if(cursor!=null)
                cursor.moveToFirst();


            Restaurants r = new Restaurants(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getBlob(1));

                return contact;
}               
public List<Restaurants> getAllRestaurants(){
    List<Restaurants> restaurantsList = new ArrayList<Restaurants>();

    String selectQuery = "SELECT * FROM restaurants ORDER BY name";

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    if(cursor.moveToFirst()){
         do{
            Restaurants restaurants = new Restaurants();
        restaurants.setID(Integer.parseInt(cursor.getString(0)));
        restaurants.setName(cursor.getString(1));
        restaurants.setImage(cursor.getBlob(2));
          restaurantsList.add(contact);
     }while(cursor.moveToNext());
}
    db.close();
    return restaurantsList;
}
public int updateRestaurants(Restaurants restaurants) {
      SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName());
     values.put(KEY_IMAGE, contact.getImage());

    // updating row
    return db.update(TABLE_RESTAURANTS, values, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });

}

// Deleting single restaurant
public void deleteRestaurants(Restaurants restaurants) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_RESTAURANTS, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
    db.close();
}

// Getting Restaurants Count
public int getRestaurantsCount() {
    String countQuery = "SELECT  * FROM " + TABLE_RESTAURANTS;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

    // return count
    return cursor.getCount();
 }
}

最后我有一个主要的类,我在其中插入带有标题的图像,并将它们显示在自定义列表视图中。

public class RestaurantsActivity extends Activity implements OnItemClickListener {
ArrayList<Restaurants> imageArray = new ArrayList<Restaurants>();
RestaurantsImageAdapter adapter;
DataBaseHelper db = new DataBaseHelper(this);

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_restaurant);


    // get image from drawable
    Bitmap image = BitmapFactory.decodeResource(getResources(),
            R.drawable.daphnes_restaurant);

    Bitmap image1 = BitmapFactory.decodeResource(getResources(),
            R.drawable.alatsi);

    // convert bitmap to byte
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    byte imageInByte[] = stream.toByteArray();

    ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
    image1.compress(Bitmap.CompressFormat.JPEG, 100, stream1);
    byte imageInByte1[] = stream1.toByteArray();

    /**
     * CRUD Operations
     * */
    // Inserting Restaurants
    Log.d("Insert: ", "Inserting ..");
    db.addRestaurants(new Restaurants("Daphnes", imageInByte));
    db.addRestaurants(new Restaurants("Alatsi", imageInByte1));
    // display main List view bcard and contact name

    // Reading all restaurants from database
    List<Restaurants> restaurants = db.getAllRestaurants();
    for (Restaurants re : restaurants) {
        String log = "ID:" + cn.getID() + " Name: " + cn.getName()
                + " ,Image: " + cn.getImage();

        // Writing Restaurants to log
        Log.d("Result: ", log);
        //add restaurants data in arrayList
        imageArray.add(re);

    }
    adapter = new RestaurantsImageAdapter(this, R.layout.single_row,
            imageArray);
    ListView dataList = (ListView) findViewById(R.id.list);
    dataList.setAdapter(adapter);
    dataList.setOnItemClickListener(this);



}

  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
 // TODO Auto-generated method stub
 switch(position){
 case 0:
    Toast.makeText(this,"First row clicked ",Toast.LENGTH_SHORT).show();
    break;
case 1:
    Toast.makeText(this,"Second row clicked ",Toast.LENGTH_SHORT).show();
    break;
   }
  }
}

0 个答案:

没有答案