检查包名称是否存在于数据库中

时间:2013-07-09 01:47:42

标签: android

我的主要课程显示所有应用程序在下面我已经制作了一个onclick监听器来选择一个应用程序,然后发送检查它是否存在于数据库中

public class MainActivity extends ListActivity implements OnItemClickListener {

    private ArrayList<String> application_name = new ArrayList<String>();

    List<ResolveInfo> list;

    String[] myapps_name= new String[application_name.size()];
    ResolveInfo rInfo;
    String error;
    String packagename;
    String returnedPackageName;
    public boolean myappisindatabase=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PackageManager pm = this.getPackageManager();

        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        list = pm.queryIntentActivities(intent, PackageManager.PERMISSION_GRANTED);
        for (ResolveInfo rInfo: list) {
            application_name.add((String) rInfo.activityInfo.applicationInfo.loadLabel(pm));
            Log.w("Installed Applications", rInfo.activityInfo.applicationInfo.loadLabel(pm).toString());
        }

        getListView().setOnItemClickListener(this);
        myapps_name = application_name.toArray(myapps_name);
        setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, myapps_name));
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        final ActivityInfo info = list.get(arg2).activityInfo;
        packagename = info.packageName;

        checkifindatabase();

        if(!myappisindatabase) {
            AlertDialog.Builder a = new AlertDialog.Builder(MainActivity.this);
            a.setMessage("Do you want to lock this app");
            a.setCancelable(true);
            a.setPositiveButton("Yes, lock my app", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    boolean diditwork = true;
                    try {
                        Mylockedapps entry = new Mylockedapps(MainActivity.this);
                        entry.open();
                        entry.createEntry(packagename);
                        entry.close();
                    } catch(Exception e) {
                        diditwork = false;
                        error = e.toString();
                        Intent didntwork= new Intent(MainActivity.this, MainActivity.class);
                        startActivity(didntwork);
                    } finally {
                        if (diditwork) {
                            Intent databaseadd= new Intent(MainActivity.this, DatabaseView.class);
                            startActivity(databaseadd);
                        }
                    }
                }
            });

            AlertDialog alert= a.create();
            a.show();
        }

        if (myappisindatabase) {
            AlertDialog.Builder a= new AlertDialog.Builder(MainActivity.this);
            a.setMessage("Do you want to unlock this app");
            a.setCancelable(true);
            a.setPositiveButton("Yes, unlock my app", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    boolean diditdelete= true;
                    try {
                        Mylockedapps entry= new Mylockedapps(MainActivity.this);
                        entry.open();
                        entry.deleteEntry(packagename);
                        entry.close();
                    } catch(Exception e) {
                        diditdelete = false;
                        error = e.toString();
                        Intent didntwork = new Intent(MainActivity.this, MainActivity.class);
                        startActivity(didntwork);
                    } finally {
                        if (diditdelete) {
                            Intent deleted = new Intent(MainActivity.this, Deleted.class);
                            startActivity(deleted);
                        }
                    }
                }
            });

            AlertDialog alert = a.create();
            a.show();
        }
    }

    public boolean checkifindatabase() {
        boolean diditfind = true;
        try {
            Mylockedapps myapp = new Mylockedapps(this);
            myapp.open();
            returnedPackageName = myapp.getPackageName(packagename);
            myapp.close();
        } catch(Exception e) {
            diditfind = false;
            error = e.toString();
            Intent didntwork = new Intent(MainActivity.this, Found.class);
            startActivity(didntwork);
        }

        if(packagename.equals(returnedPackageName))
            myappisindatabase=true;
        else
            myappisindatabase=false;

        return true;
    }
}

我的数据库类是

public class Mylockedapps {
    public static final String KEY_ROWID = "_id";
    public static final String APPS_PACKAGENAME = "apps_packagename";

    private static final String DATABASE_NAME = "MyLockedApps";
    private static final String DATABASE_TABLE = "AppsTable";
    private static final int DATABASE_VERSION = 1;

    private DbHelper ourHelper;
    private final Context ourContext;
    private SQLiteDatabase ourDatabase;

    private static class DbHelper extends SQLiteOpenHelper {

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

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + DATABASE_TABLE + "(" +
                        KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                        APPS_PACKAGENAME + " TEXT NOT NULL);");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion,
                              int newVersion) {
            // TODO Auto-generated method stub
            db.execSQL("DROP TABLE IF EXITS " + DATABASE_TABLE);
            onCreate(db);
        }
    }

    public Mylockedapps(Context c) {
        ourContext = c;
    }

    public Mylockedapps open() throws SQLException {
        ourHelper = new DbHelper(ourContext);
        ourDatabase = ourHelper.getWritableDatabase();
        return this;
    }

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

    public long createEntry(String packagename) {
        ContentValues cv = new ContentValues();
        cv.put(APPS_PACKAGENAME, packagename);
        return ourDatabase.insert(DATABASE_TABLE, null, cv);
    }

    public String getData() {
        String[] columns = new String[]{KEY_ROWID,APPS_PACKAGENAME};
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null, null);
        String result = "";
        int iRow = c.getColumnIndex(KEY_ROWID);
        int iApps = c.getColumnIndex(APPS_PACKAGENAME);

        for(c.moveToFirst();!c.isAfterLast();c.moveToNext()) {
            result= result + c.getString(iRow) + " " + c.getString(iApps) + "\n";
        }
        return result;
    } 

    public String getPackageName(String findthisapp) throws SQLException {
        String[] columns = new String[]{KEY_ROWID,APPS_PACKAGENAME};
        Cursor c = ourDatabase.query(DATABASE_TABLE, columns, APPS_PACKAGENAME , null, null, null, null, null);

        if (c != null) {
            c.moveToFirst();
            String packagename = c.getString(1);

            if (packagename.equals(findthisapp))
                return packagename;
            else 
                return null;
        }
        return null;
    }

    public void deleteEntry (String packagename)throws SQLException {
        ourDatabase.delete(DATABASE_TABLE, APPS_PACKAGENAME + "=" + packagename, null);
    }
}

我的错误是

close() was never explicitly called on database '/data/data/com.ku.installedapps/databases/MyLockedApps' 
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the      cursor or database object that was opened here

和其他类似的错误...... 我发现我收到错误,我发送一个字符串来检查它是否与部分数据库中存储的包名称中的任何一个匹配

public String getPackageName(String findthisapp) throws SQLException{

2 个答案:

答案 0 :(得分:0)

由于您在这里没有完整的LogCat,我从给定的错误中猜测的是,您在某处调用了myapp.open();,但是您没有调用myapp.close();。我猜测的是,如果你的函数myapp.getPackageName(packagename);返回错误,那么你myapp.close()永远不会被调用,从而导致你看到的错误。 只需尝试在try-catch块外调用open(),close()。

将它放在OnCreate()函数中:

Mylockedapps myapp = new Mylockedapps(this);
try{
    myapp.open();

}catch(SQLException e){

}

保留checkifindatabase()函数,如下所示:

public boolean checkifindatabase() {
    boolean diditfind = true;

    try {
        returnedPackageName = myapp.getPackageName(packagename);
    } catch(Exception e) {
        diditfind = false;
        error = e.toString();
        Intent didntwork = new Intent(MainActivity.this, Found.class);
        startActivity(didntwork);
    }
    if(packagename.equals(returnedPackageName))
        myappisindatabase=true;
    else
        myappisindatabase=false;

    return true;
}

在onPause()函数调用中:

myapp.close();

这将确保您始终关闭它。希望这会有所帮助。

答案 1 :(得分:0)

你必须以这种方式关闭光标

public String getPackageName(String findthisapp) throws SQLException{
        // TODO Auto-generated method stub
        String[] columns= new String[]{KEY_ROWID,APPS_PACKAGENAME};
        Cursor c= ourDatabase.query(DATABASE_TABLE, columns, APPS_PACKAGENAME , null, null, null, null, null);
        if(c.getCount()!=0){
            c.moveToFirst();
            String packagename= c.getString(1);
            if(packagename.equals(findthisapp)){
                c.close();
                return packagename;
            }else{
                c.close();
                return null;
            }
        }
        c.close();
        return null;
    }