2014-06-18 105 views
0

我想創建一個關於與sqllite database.I連接的自定義視圖的應用程序也由圖像組成。自定義列表視圖與圖像和數據庫連接

問題是:當我試圖在模擬器中執行程序時,它顯示圖標(圖像)在每次執行程序時都會重複出現。例如,我的程序由facebook.png組成。第一次執行時,只有一個圖像正在顯示。再次嘗試執行時兩個Facebook圖標即將到來。如何刪除解決這個問題

的代碼如下:

MainActivity.java

package com.example.sqlliteimagedemo; 

import java.io.ByteArrayOutputStream; 
import java.util.ArrayList; 
import java.util.List; 

import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.Bundle; 
import android.support.v7.app.ActionBarActivity; 
import android.util.Log; 
import android.widget.ListView; 

public class MainActivity extends ActionBarActivity 
{ 

    ArrayList<Contact> imageArry = new ArrayList<Contact>(); 
    ContactImageAdapter adapter; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     DataBaseHandler db = new DataBaseHandler(this); 
     // get image from drawable 
     Bitmap image = BitmapFactory.decodeResource(getResources(),R.drawable.facebook); 

     // convert bitmap to byte 
       ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
       image.compress(Bitmap.CompressFormat.JPEG, 50, stream); 
       byte imageInByte[] = stream.toByteArray(); 
       /** 
       * CRUD Operations 
       * */ 
       // Inserting Contacts 
       Log.d("Insert: ", "Inserting .."); 
       db.addContact(new Contact("FaceBook", imageInByte)); 
       // display main List view bcard and contact name 

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

        // Writing Contacts to log 
        Log.d("Result: ", log); 
        //add contacts data in arrayList 
        imageArry.add(cn); 

       } 
       adapter = new ContactImageAdapter(this, R.layout.screen_list, 
         imageArry); 
       ListView dataList = (ListView) findViewById(R.id.list); 
       dataList.setAdapter(adapter); 

      } 

     } 

ContactImageAdapter.java

package com.example.sqlliteimagedemo; 

    import java.io.ByteArrayInputStream; 
    import java.util.ArrayList; 
    import android.app.Activity; 
    import android.content.Context; 
    import android.graphics.Bitmap; 
    import android.graphics.BitmapFactory; 
    import android.view.LayoutInflater; 
    import android.view.View; 
    import android.view.ViewGroup; 
    import android.widget.ArrayAdapter; 
    import android.widget.ImageView; 
    import android.widget.TextView; 

    public class ContactImageAdapter extends ArrayAdapter<Contact> 
    { 

     Context context; 
     int layoutResourceId; 
     // BcardImage data[] = null; 
     ArrayList<Contact> data=new ArrayList<Contact>(); 
     public ContactImageAdapter(Context context,int layoutResourceId, ArrayList<Contact> data) { 
      super(context, layoutResourceId, data); 

      this.layoutResourceId = layoutResourceId; 
       this.context = context; 
       this.data = data; 
      } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
      View row = convertView; 
      ImageHolder holder = null; 

      if(row == null) 
      { 
       LayoutInflater inflater = ((Activity) context).getLayoutInflater(); 
       row = inflater.inflate(layoutResourceId, parent, false); 

       holder = new ImageHolder(); 
       holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle); 
       holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon); 
       row.setTag(holder); 
      } 
      else 
      { 
       holder = (ImageHolder)row.getTag(); 
      } 

      Contact picture = data.get(position); 
      holder.txtTitle.setText(picture._name); 
      //convert byte to bitmap take from contact class 

      byte[] outImage=picture._image; 
      ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage); 
      Bitmap theImage = BitmapFactory.decodeStream(imageStream); 
      holder.imgIcon.setImageBitmap(theImage); 
      return row; 

     } 

     static class ImageHolder 
     { 
      ImageView imgIcon; 
      TextView txtTitle; 
     } 
    } 

DataBaseHandler.java

package com.example.sqlliteimagedemo; 

import java.util.ArrayList; 
import java.util.List; 

import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 

public class DataBaseHandler extends SQLiteOpenHelper 
{ 
    // All Static variables 
     // Database Version 
     private static final int DATABASE_VERSION = 1; 

     // Database Name 
     private static final String DATABASE_NAME = "imagedb"; 

     // Contacts table name 
     private static final String TABLE_CONTACTS = "contacts"; 

     // Contacts Table Columns names 
     private static final String KEY_ID = "id"; 
     private static final String KEY_NAME = "name"; 
     private static final String KEY_IMAGE = "image"; 

     public DataBaseHandler(Context context) { 
      super(context, DATABASE_NAME, null, DATABASE_VERSION); 
     } 

     //creating tables 
    @Override 
    public void onCreate(SQLiteDatabase db) 
    { 
     String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" 
       + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," 
       + KEY_IMAGE + " BLOB" + ")"; 
     db.execSQL(CREATE_CONTACTS_TABLE); 

    } 

    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    { 

     //Drop older table if existed 
     db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS); 

     // Create tables again 
     onCreate(db); 
    } 

    /** 
    * All CRUD(Create, Read, Update, Delete) Operations 
    */ 

    public// Adding new contact 
    void addContact(Contact contact) { 
     SQLiteDatabase db = this.getWritableDatabase(); 

     ContentValues values = new ContentValues(); 
     values.put(KEY_NAME, contact._name); // Contact Name 
     values.put(KEY_IMAGE, contact._image); // Contact Phone 

     // Inserting Row 
     db.insert(TABLE_CONTACTS, null, values); 
     db.close(); // Closing database connection 
    } 

    // Getting single contact 
    Contact getContact(int id) { 
     SQLiteDatabase db = this.getReadableDatabase(); 

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

     Contact contact = new Contact(Integer.parseInt(cursor.getString(0)), 
       cursor.getString(1), cursor.getBlob(1)); 

     // return contact 
     return contact; 

    } 

    // Getting All Contacts 
    public List<Contact> getAllContacts() { 
     List<Contact> contactList = new ArrayList<Contact>(); 
     // Select All Query 
     String selectQuery = "SELECT * FROM contacts ORDER BY name"; 

     SQLiteDatabase db = this.getWritableDatabase(); 
     Cursor cursor = db.rawQuery(selectQuery, null); 
     // looping through all rows and adding to list 
     if (cursor.moveToFirst()) { 
      do { 
       Contact contact = new Contact(); 
       contact.setID(Integer.parseInt(cursor.getString(0))); 
       contact.setName(cursor.getString(1)); 
       contact.setImage(cursor.getBlob(2)); 
       // Adding contact to list 
       contactList.add(contact); 
      } while (cursor.moveToNext()); 
     } 
     // close inserting data from database 
     db.close(); 
     // return contact list 
     return contactList; 

    } 

    // Updating single contact 
    public int updateContact(Contact contact) { 
     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_CONTACTS, values, KEY_ID + " = ?", 
       new String[] { String.valueOf(contact.getID()) }); 

    } 

    // Deleting single contact 
    public void deleteContact(Contact contact) { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     db.delete(TABLE_CONTACTS, KEY_ID + " = ?", 
       new String[] { String.valueOf(contact.getID()) }); 
     db.close(); 
    } 

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

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

} 

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <ListView 
     android:id="@+id/list" 
     android:layout_width="fill_parent" 
     android:layout_height="0dp" 
     android:layout_weight="0.55" > 
    </ListView> 

</LinearLayout> 

screen_list.xml

<?xml version="1.0" encoding="UTF-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="horizontal" 
    android:padding="10dp" > 

    <ImageView 
     android:id="@+id/imgIcon" 
     android:layout_width="0dp" 
     android:layout_height="100dp" 
     android:layout_weight="0.71" 
     android:gravity="center_vertical" /> 

    <TextView 
     android:id="@+id/txtTitle" 
     android:layout_width="80dp" 
     android:layout_height="fill_parent" 
     android:gravity="center_vertical" 
     android:textSize="14dp" 
     android:layout_marginLeft="7dp" /> 

</LinearLayout> 

請幫助..

回答

1

你加入Facebook的接觸Log.d("Insert: ", "Inserting .."); db.addContact(new Contact("FaceBook", imageInByte));

您運行的代碼是這樣的: - 低於參考點

  • 當你第一次執行,一個Facebook的加入。
  • 再次執行該程序時,添加了新的Facebook聯繫人。所以它顯示了兩個聯繫人。
  • 像明智的將其添加和打印,當你執行程序

更新的代碼: - `

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    DataBaseHandler db = new DataBaseHandler(this); 
    // get image from drawable 
    Bitmap image = BitmapFactory.decodeResource(getResources(),R.drawable.facebook); 

    // convert bitmap to byte 
      ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
      image.compress(Bitmap.CompressFormat.JPEG, 50, stream); 
      byte imageInByte[] = stream.toByteArray(); 
      /** 
      * CRUD Operations 
      * */ 
      // Inserting Contacts 
      Log.d("Insert: ", "Inserting .."); 

      //Added Code below 
      SharedPreferences preferences = getSharedPreferences("SETTINGS_PREF", Context.MODE_PRIVATE); 
      if(preferences.getBoolean("isFirstLaunch", true)){ 
       db.addContact(new Contact("FaceBook", imageInByte)); 

       SharedPreferences.Editor editor = preferences.edit(); 
       editor.putBoolean("isFirstLaunch", false); 
       editor.commit(); 
      } 

      // display main List view bcard and contact name 

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

       // Writing Contacts to log 
       Log.d("Result: ", log); 
       //add contacts data in arrayList 
       imageArry.add(cn); 

      } 
      adapter = new ContactImageAdapter(this, R.layout.screen_list, 
        imageArry); 
      ListView dataList = (ListView) findViewById(R.id.list); 
      dataList.setAdapter(adapter); 

     } 
+0

我只想要一個圖標。我只想添加一個Facebook圖標 – user3736518

+0

然後使用SharedPrefrences,使用它可以在第一次執行時設置isFirstLaunched = true。在第二次執行時,您可以檢查isFirstLaunched是true還是false。如果它錯誤,你不需要添加。 –

+0

更新您的代碼以使用sharedPreferences。 –

0

嘗試顯示列表前使用此

// Inserting Contacts 
       Log.d("Insert: ", "Inserting .."); 
       db.addContact(new Contact("FaceBook", imageInByte)); 
       // display main List view bcard and contact name 


       // ArrayList clear() operation removes all elements 
       imageArry.clear(); 


       // Reading all contacts from database 
       List<Contact> contacts = db.getAllContacts(); 
+0

imageArry.add(CN);發生在onCreate上,清除onCreate沒用。如果它在onResume。 imageArry.clear()是一個好習慣。 –

+1

是的你的想法是好的...我希望也創造我們也可以去那裏只有他正試圖添加項目,所以在添加最好的清除數組列表之前。所以我建議像那樣...我們可以在簡歷上使用 – Android

相關問題