本文介绍了的android我如何删除数据库中重复的条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我的code。我在数据库中添加应用程序的名称,并显示在另一个屏幕的应用,但问题是重复的条目将显示主阶级帮我PLZ。我如何从数据库中删除重复的条目。
公共类SdcardAPkMgr扩展ListActivity {
数据库处理器分贝;
公众可绘制getAPKDrawable(字符串文件路径){
可绘制博士= NULL;
如果(文件路径!= NULL){ 字符串PATH_PackageParser =android.content.pm.PackageParser;
字符串PATH_AssetManager =android.content.res.AssetManager;
尝试{
类pkgParserCls =的Class.forName(PATH_PackageParser);
类[] = typeArgs新类[1];
typeArgs [0] =为String.class;
构造pkgParserCt =
pkgParserCls.getConstructor(typeArgs);
[对象] valueArgs =新对象[1];
valueArgs [0] =文件路径;
对象pkgParser = pkgParserCt.newInstance(valueArgs);
DisplayMetrics指标=新DisplayMetrics();
metrics.setToDefaults();
// PackageParser.Package mPkgInfo =
// packageParser.parsePackage(新
//文件(apkPath),apkPath,
//度量,0);
typeArgs =新类[4];
typeArgs [0] = File.class;
typeArgs [1] =为String.class;
typeArgs [2] = DisplayMetrics.class;
typeArgs [3] = Integer.TYPE;
方法pkgParser_parsePackageMtd = pkgParserCls
.getDeclaredMethod(parsePackage
typeArgs);
valueArgs =新对象[4];
valueArgs [0] =新的文件(文件路径);
valueArgs [1] =文件路径;
valueArgs [2] =度量;
valueArgs [3] = 0;
对象pkgParserPkg = pkgParser_parsePackageMtd.invoke(
pkgParser,valueArgs);
现场appInfoFld =
pkgParserPkg.getClass()。getDeclaredField(
applicationInfo);
ApplicationInfo信息=(ApplicationInfo)appInfoFld
获得(pkgParserPkg); 类assetMagCls =的Class.forName(PATH_AssetManager);
构造assetMagCt = assetMagCls
.getConstructor((类[])NULL);
对象assetMag = assetMagCt.newInstance((Object []对象),NULL);
typeArgs =新类[1];
typeArgs [0] =为String.class;
方法assetMag_addAssetPathMtd = assetMagCls
.getDeclaredMethod(addAssetPath
typeArgs);
valueArgs =新对象[1];
valueArgs [0] =文件路径;
assetMag_addAssetPathMtd.invoke(assetMag,valueArgs);
资源解析度= getResources();
typeArgs =新类[3];
typeArgs [0] = assetMag.getClass();
。typeArgs [1] = res.getDisplayMetrics()的getClass();
typeArgs [2] = res.getConfiguration()的getClass();
构造resCt =
Resources.class.getConstructor(typeArgs);
valueArgs =新对象[3];
valueArgs [0] = assetMag;
valueArgs [1] = res.getDisplayMetrics();
valueArgs [2] = res.getConfiguration();
RES =(资源)resCt.newInstance(valueArgs);
字符串标签= NULL;
如果(info.labelRes!= 0){
标签=(字符串)res.getText(info.labelRes);
Log.d(插入,插入..);
db.addContact(新联系(标签)); 公共类MainActivity扩展活动器具
OnItemClickListener { / *是否要包括系统应用* /
私有静态最终布尔INCLUDE_SYSTEM_APPS = FALSE;
数据库处理器分贝;
私人列表<应用> loadInstalledApps(布尔includeSysApps){
清单<应用>应用=新的ArrayList<应用>(); //包管理器包含所有已安装的信息
应用
软件包管理系统软件包管理系统= getPackageManager(); 清单< PackageInfo>包= packageManager.getInstalledPackages(0);
//PackageManager.GET_META_DATA 的for(int i = 0; I< packs.size();我++){
PackageInfo p值= packs.get(ⅰ);
ApplicationInfo applicationInfo = p.applicationInfo;
字符串名称=
packageManager.getApplicationLabel(applicationInfo)的ToString(); Log.d(读,读所有联系人..);
清单<联系与GT;接触= db.getAllContacts(); 对于(联系CN:触点){
字符串日志=ID:+ cn.getID()+,产品名称:+
cn.getName(); //字符串日志=ID:+ cn.getID()+,产品名称:+
cn.getName()+,电话:+ cn.getPhoneNumber();
//写入联系人登录
Log.d(姓名,日志); //
如果(((名称)。载(cn.getName())))
{
应用程序=新的App(); app.setTitle(p.applicationInfo.loadLabel(软件包管理系统)的ToString());
app.setPackageName(p.packageName);
app.setVersionName(p.versionName);
app.setVersion code(p.version code);
CharSequence的说明=
p.applicationInfo.loadDescription(软件包管理系统);
app.setDescription(说明= NULL description.toString()!?
);
apps.add(应用);
}
}}
返回应用程序;
} 包com.gfsmart.filemanager;
进口android.database.sqlite.SQLiteOpenHelper; 公共类数据库处理器扩展SQLiteOpenHelper {//所有静态变量
//数据库版本
私有静态最终诠释DATABASE_VERSION = 1;//数据库名称
私有静态最后弦乐DATABASE_NAME =contactsManager;//联系人表名
私有静态最后弦乐TABLE_CONTACTS =接触;//联系方式表列名
私有静态最后弦乐KEY_ID =ID;
私有静态最后弦乐KEY_NAME =名;
//私有静态最后弦乐KEY_PH_NO =PHONE_NUMBER;公共数据库处理器(上下文的背景下){
超(背景下,DATABASE_NAME,空,DATABASE_VERSION);
}//创建表
@覆盖
公共无效的onCreate(SQLiteDatabase DB){
//字符串CREATE_CONTACTS_TABLE =CREATE TABLE+ TABLE_CONTACTS +(+ KEY_ID +INTEGER PRIMARY KEY,+ KEY_NAME +TEXT+ KEY_PH_NO +TEXT+); 字符串CREATE_CONTACTS_TABLE =CREATE TABLE+ TABLE_CONTACTS +(+ KEY_ID +INTEGER PRIMARY KEY,+ KEY_NAME +TEXT); db.execSQL(CREATE_CONTACTS_TABLE);
}//数据库升级
@覆盖
公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
如果存在//删除旧的表
db.execSQL(DROP TABLE IF EXISTS+ TABLE_CONTACTS); //再次创建表
的onCreate(DB);
}/ **
*所有CRUD(创建,读取,更新,删除)操作
* ///添加新联系人
无效的addContact(联系方式联系我们){
SQLiteDatabase分贝= this.getWritableDatabase(); ContentValues值=新ContentValues();
values.put(KEY_NAME,contact.getName()); // 联系人姓名
// values.put(KEY_PH_NO,contact.getPhoneNumber()); // 联系电话 //插入行
db.insert(TABLE_CONTACTS,空,价值);
db.close(); //关闭数据库连接
}//获取单触点
联系getContact(INT ID){
SQLiteDatabase分贝= this.getReadableDatabase(); 光标光标= db.query(TABLE_CONTACTS,新的String [] {KEY_ID,
KEY_NAME},KEY_ID +=?,
新的String [] {将String.valueOf(ID)},NULL,NULL,NULL,
空值);
如果(指针!= NULL)
cursor.moveToFirst(); 联系方式联系我们=新的联系人(的Integer.parseInt(cursor.getString(0)),
cursor.getString(1));
//返回接触
返回接触;
}//获取所有联系人
公开名单<联系与GT; getAllContacts(){
清单<联系与GT; contactList =新的ArrayList<联系与GT;();
//选择所有查询
字符串selectQuery =SELECT * FROM+ TABLE_CONTACTS; SQLiteDatabase分贝= this.getWritableDatabase();
光标光标= db.rawQuery(selectQuery,NULL); //通过所有行循环,并增加列表
如果(cursor.moveToFirst()){
做{
联系方式联系我们=新的联系人();
contact.setID(的Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
//contact.setPhoneNumber(cursor.getString(2));
//添加联系人名单
contactList.add(接触);
}而(cursor.moveToNext());
} //返回联系人列表
返回contactList;
}//更新单触点
公众诠释updateContact(联系方式联系我们){
SQLiteDatabase分贝= this.getWritableDatabase(); ContentValues值=新ContentValues();
values.put(KEY_NAME,contact.getName());
// values.put(KEY_PH_NO,contact.getPhoneNumber()); //更新行
返回db.update(TABLE_CONTACTS,价值观,KEY_ID +=?,
新的String [] {将String.valueOf(contact.getID())});
}//删除单个联系人
公共无效deleteContact(联系方式联系我们){
SQLiteDatabase分贝= this.getWritableDatabase();
db.delete(TABLE_CONTACTS,KEY_ID +=?,
新的String [] {将String.valueOf(contact.getID())});
db.close();
}
//获取联系人计数
公众诠释getContactsCount(){
字符串countQuery =SELECT * FROM+ TABLE_CONTACTS;
SQLiteDatabase分贝= this.getReadableDatabase();
光标光标= db.rawQuery(countQuery,NULL);
cursor.close(); //返回计数
返回cursor.getCount();
} } 公共类联系{//私有变量
INT _id;
字符串_name;
//空的构造
公共联系(){}
//构造
公共联系(INT ID,字符串名称){
this._id = ID;
this._name =名称;}//构造
公众联系(字符串名称){
this._name =名称;}
//获取ID
公众诠释的getID(){
返回this._id;
}//设置ID
公共无效SETID(INT ID){
this._id = ID;
}//获取名称
公共字符串的getName(){
返回this._name;
}//设置名称
公共无效setname可以(字符串名称){
this._name =名称;
}
解决方案
这是因为你在启动应用程序插入数据库,每次入境。所以插入进入数据库之前,只需调用下面的方法。它删除表中的所有记录。
例如:
db.deleteContact();
db.addContact(新联系(标签));
下面放code在数据库处理器类:
公众诠释deleteContact(){
尝试{
SQLiteDatabase分贝= this.getWritableDatabase();
返回db.delete(TABLE_CONTACTS,NULL,NULL);
}赶上(例外五){
e.printStackTrace();
}
返回0;
}
Below is my code. I add application name in database and show that application in another screen but the problem is duplicate entry will show Main class help me plz. How do I remove duplicate entry from database.
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;
}
解决方案
it happens because you are inserting entry in database everytime at starting application. so just call below method before inserting entry into database. its for delete all the records from table.
Example:
db.deleteContact();
db.addContact(new Contact(label));
put below code in DatabaseHandler class:
public int deleteContact() {
try {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_CONTACTS, null, null);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
这篇关于的android我如何删除数据库中重复的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!