1

下面是我的代码。我在数据库中添加应用程序名称并在另一个屏幕中显示该应用程序,但问题是重复条目将显示主类帮助我。如何从数据库中删除重复条目。

public class SdcardAPkMgr extends ListActivity {
DatabaseHandler db;


       public Drawable getAPKDrawable(String filePath) {
    Drawable dr = null;
    if (filePath != null) {

        String PATH_PackageParser = "android.content.pm.PackageParser";
        String PATH_AssetManager = "android.content.res.AssetManager";
        try {
            Class pkgParserCls = Class.forName(PATH_PackageParser);
            Class[] typeArgs = new Class[1];
            typeArgs[0] = String.class;
            Constructor pkgParserCt = 
             pkgParserCls.getConstructor(typeArgs);
            Object[] valueArgs = new Object[1];
            valueArgs[0] = filePath;
            Object pkgParser = pkgParserCt.newInstance(valueArgs);
            DisplayMetrics metrics = new DisplayMetrics();
            metrics.setToDefaults();
            // PackageParser.Package mPkgInfo =
            // packageParser.parsePackage(new
            // File(apkPath), apkPath,
            // metrics, 0);
            typeArgs = new Class[4];
            typeArgs[0] = File.class;
            typeArgs[1] = String.class;
            typeArgs[2] = DisplayMetrics.class;
            typeArgs[3] = Integer.TYPE;
            Method pkgParser_parsePackageMtd = pkgParserCls
                    .getDeclaredMethod("parsePackage", 
                 typeArgs);
            valueArgs = new Object[4];
            valueArgs[0] = new File(filePath);
            valueArgs[1] = filePath;
            valueArgs[2] = metrics;
            valueArgs[3] = 0;
            Object pkgParserPkg = pkgParser_parsePackageMtd.invoke(
                    pkgParser, valueArgs);
            Field appInfoFld = 
       pkgParserPkg.getClass().getDeclaredField(
                    "applicationInfo");
            ApplicationInfo info = (ApplicationInfo) appInfoFld 
              .get(pkgParserPkg);

            Class assetMagCls = Class.forName(PATH_AssetManager);
            Constructor assetMagCt = assetMagCls
                    .getConstructor((Class[]) null);
            Object assetMag = assetMagCt.newInstance((Object[]) null);
            typeArgs = new Class[1];
            typeArgs[0] = String.class;
            Method assetMag_addAssetPathMtd = assetMagCls
                    .getDeclaredMethod("addAssetPath", 
              typeArgs);
            valueArgs = new Object[1];
            valueArgs[0] = filePath;
            assetMag_addAssetPathMtd.invoke(assetMag, valueArgs);
            Resources res = getResources();
            typeArgs = new Class[3];
            typeArgs[0] = assetMag.getClass();
            typeArgs[1] = res.getDisplayMetrics().getClass();
            typeArgs[2] = res.getConfiguration().getClass();
            Constructor resCt = 
            Resources.class.getConstructor(typeArgs);
            valueArgs = new Object[3];
            valueArgs[0] = assetMag;
            valueArgs[1] = res.getDisplayMetrics();
            valueArgs[2] = res.getConfiguration();
            res = (Resources) resCt.newInstance(valueArgs);
            String label = null;
            if (info.labelRes != 0) {
                label = (String) res.getText(info.labelRes);
                Log.d("Insert: ", "Inserting ..");
                db.addContact(new Contact(label));









                        public class MainActivity extends Activity implements 
                OnItemClickListener {

   /* whether or not to include system apps */
   private static final boolean INCLUDE_SYSTEM_APPS = false;
   DatabaseHandler db;




                         private List<App> loadInstalledApps(boolean includeSysApps) {
          List<App> apps = new ArrayList<App>();

          // the package manager contains the information about all installed 
    apps
          PackageManager packageManager = getPackageManager();

          List<PackageInfo> packs = packageManager.getInstalledPackages(0); 
        //PackageManager.GET_META_DATA 





          for(int i=0; i < packs.size(); i++) {
             PackageInfo p = packs.get(i);
             ApplicationInfo applicationInfo = p.applicationInfo;
             String name = 
      packageManager.getApplicationLabel(applicationInfo).toString();



             Log.d("Reading: ", "Reading all contacts..");
                List<Contact> contacts = db.getAllContacts();       

                for (Contact cn : contacts) {
                    String log = "Id: "+cn.getID()+" ,Name: " + 
      cn.getName() ;

                  //  String log = "Id: "+cn.getID()+" ,Name: " + 
      cn.getName() + " ,Phone: " + cn.getPhoneNumber();
                        // Writing Contacts to log
                Log.d("Name: ", log);



      //
             if ( ((name).contains(cn.getName())))
                     {
             App app = new App();

     app.setTitle(p.applicationInfo.loadLabel(packageManager).toString());
             app.setPackageName(p.packageName);
             app.setVersionName(p.versionName);
             app.setVersionCode(p.versionCode);
             CharSequence description = 
    p.applicationInfo.loadDescription(packageManager);
             app.setDescription(description != null ? description.toString() : 
        "");
             apps.add(app);
          }
          }}
          return apps;
       }







                         package com.gfsmart.filemanager;


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 = "contactsManager";

// 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_PH_NO = "phone_number";

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_PH_NO + " TEXT" + ")";

    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";

    db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@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
 */

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

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName()); // Contact Name
//  values.put(KEY_PH_NO, contact.getPhoneNumber()); // 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_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));
    // return contact
    return contact;
}

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

    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.setPhoneNumber(cursor.getString(2));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }

    // 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_PH_NO, contact.getPhoneNumber());

    // 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();
}

          }







                       public class Contact {

//private variables
int _id;
String _name;


// Empty constructor
public Contact(){

}
// constructor
public Contact(int id, String name){
    this._id = id;
    this._name = name;

}

// constructor
public Contact(String name){
    this._name = name;

}
// getting ID
public int getID(){
    return this._id;
}

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

// getting name
public String getName(){
    return this._name;
}

// setting name
public void setName(String name){
    this._name = name;
}
4

1 回答 1

0

发生这种情况是因为您每次在启动应用程序时都在数据库中插入条目。所以只需在将条目插入数据库之前调用以下方法。它用于从表中删除所有记录。

例子:

db.deleteContact();
db.addContact(new Contact(label));

在 DatabaseHandler 类中放入以下代码:

 public int deleteContact() {
            try {
               SQLiteDatabase db = this.getWritableDatabase();
                return db.delete(TABLE_CONTACTS, null, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return 0;
        }
于 2013-06-17T06:39:25.670 回答