简体   繁体   English

如何在SQLite数据库中存储和检索ApplicationInfo对象?

[英]How to Store and retrieve ApplicationInfo object in SQLite database?

I am developing an app which shows all the installed applications to user with checkboxes. 我正在开发一个应用程序,该应用程序通过复选框向用户显示所有已安装的应用程序。 I am succeed in doing so. 我这样做成功。 But I am having problem in saving and retrieving the selected apps by the user. 但是我在保存和检索用户选择的应用程序时遇到问题。 I have used ArrayList for storing selected apps, it works fine but when the app is shutdown all the items in arraylist gets remove. 我已经使用ArrayList来存储选定的应用程序,它工作正常,但是当应用程序关闭时,arraylist中的所有项目都会被删除。 Then I have switched to Storage via SharedPreferences but i didn't work. 然后,我已通过SharedPreferences切换到“存储”,但是我没有工作。 Last option is to store and retrieve the applicationInfo objects via SQLite database but I dont know how to insert and retrieve an ApplicationInfo object to/from database. 最后一个选择是通过SQLite数据库存储和检索applicationInfo对象,但是我不知道如何向数据库中插入ApplicationInfo对象和从数据库检索ApplicationInfo对象。 Below is my code(Storage via ArrayList): 下面是我的代码(通过ArrayList存储):

main_activity.xml: main_activity.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context="com.example.pc.fkidshell.Teen3Activity">

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    <Button
        android:id="@+id/btn_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_marginBottom="20dp"
        android:text="Add Selected Apps"
        android:width="170dp"
        android:layout_alignParentBottom="true"
        android:layout_gravity="center_horizontal" />

</LinearLayout>

row.xml: row.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="fill_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/app_icon"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:padding="3dp"
        android:scaleType="centerCrop" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:gravity="center_vertical"
        android:orientation="vertical"
        android:paddingLeft="5dp" >

        <TextView
            android:id="@+id/app_name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/app_paackage"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical" />
    </LinearLayout>

    <CheckBox
        android:id="@+id/cb_app"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

main_activity.java: main_activity.java:

public class Teen3Activity extends ListActivity {
        private PackageManager packageManager = null;
        private List<ApplicationInfo> applist = null;
        private ApplicationAdapter listadaptor = null;

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

            Button btn1=(Button)  findViewById(R.id.btn_add);
            btn1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v)
                {

                    if(MyAddedapss.getAdded_apps().isEmpty())
                    {
                        Toast.makeText(getApplicationContext(), "Nothing to ADD!", Toast.LENGTH_LONG).show();
                    }
                    else
                    {
                        MyAddedapss.writeList(Teen3Activity.this,MyAddedapss.getAdded_apps());
                        Toast.makeText(getApplicationContext(), "Apps Added!", Toast.LENGTH_LONG).show();
                    }
                }
            });
            packageManager = getPackageManager();
            new LoadApplications().execute();
        }

        @Override
        protected void onListItemClick(ListView l, View v, int position, long id)
        {
            super.onListItemClick(l, v, position, id);

            ApplicationInfo app = applist.get(position);
            try {
                Intent intent = packageManager.getLaunchIntentForPackage(app.packageName);

                if (null != intent) {
                    startActivity(intent);
                }
            } catch (ActivityNotFoundException e) {
                Toast.makeText(Teen3Activity.this, e.getMessage(), Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(Teen3Activity.this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }

        private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list)
        {
            ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
            for (ApplicationInfo info : list) {
                try {
                    if (null != packageManager.getLaunchIntentForPackage(info.packageName))
                    {
                        applist.add(info);
                    }
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }

            return applist;
        }

        private class LoadApplications extends AsyncTask<Void, Void, Void>
        {
            private ProgressDialog progress = null;

            @Override
            protected Void doInBackground(Void... params)
            {
                applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
                listadaptor = new ApplicationAdapter(Teen3Activity.this, R.layout.row, applist);

                return null;
            }

            @Override
            protected void onCancelled()
            {
                super.onCancelled();
            }

            @Override
            protected void onPostExecute(Void result)
            {
                setListAdapter(listadaptor);
                progress.dismiss();
                super.onPostExecute(result);
            }

            @Override
            protected void onPreExecute()
            {
                progress = ProgressDialog.show(Teen3Activity.this, null, "Loading application info...");
                super.onPreExecute();
            }

            @Override
            protected void onProgressUpdate(Void... values)
            {
                super.onProgressUpdate(values);
            }
        }
    }

ApplicationAdapter.java:
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo>
{
    private List<ApplicationInfo> appsList = null;
    private Context context;
    private PackageManager packageManager;
    private ArrayList<Boolean> checkList = new ArrayList<Boolean>();

    public ApplicationAdapter(Context context, int textViewResourceId, List<ApplicationInfo> appsList)
    {
        super(context, textViewResourceId, appsList);
        this.context = context;
        this.appsList = appsList;
        packageManager = context.getPackageManager();
        for (int i = 0; i < appsList.size(); i++) {
            checkList.add(false);
        }
    }

    @Override
    public int getCount() {
        return ((null != appsList) ? appsList.size() : 0);
    }

    @Override
    public ApplicationInfo getItem(int position) {
        return ((null != appsList) ? appsList.get(position) : null);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (null == view) {
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.row, null);
        }

        ApplicationInfo data = appsList.get(position);
        if (null != data) {
            TextView appName = (TextView) view.findViewById(R.id.app_name);
            TextView packageName = (TextView) view.findViewById(R.id.app_paackage);
            ImageView iconview = (ImageView) view.findViewById(R.id.app_icon);

            CheckBox checkBox = (CheckBox) view.findViewById(R.id.cb_app);
            checkBox.setTag(Integer.valueOf(position)); // set the tag so we can identify the correct row in the listener
            checkBox.setChecked(checkList.get(position));// set the status as we stored it
            checkBox.setOnCheckedChangeListener(mListener); // set the listener

            appName.setText(data.loadLabel(packageManager));
            packageName.setText(data.packageName);
            iconview.setImageDrawable(data.loadIcon(packageManager));
        }
        return view;
    }
    CompoundButton.OnCheckedChangeListener mListener = new CompoundButton.OnCheckedChangeListener()
    {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            checkList.set((Integer)buttonView.getTag(),isChecked); // get the tag so we know the row and store the status
            if(isChecked)
            {
                int addapppos = (Integer) buttonView.getTag();
                ApplicationInfo p=appsList.get(addapppos);
                MyAddedapss.setAdded_apps(p);
                buttonView.setEnabled(false);
            }
        }
    };
}

MyAddedApps.java: (class for storing the selected Apps by user) MyAddedApps.java :(用于按用户存储所选应用程序的类)

public class MyAddedapss extends Application
{
    private static ArrayList<ApplicationInfo> added_apps=new ArrayList<ApplicationInfo>();


    public static void setAdded_apps(ApplicationInfo element)
    {

        added_apps.add(element);
    }

    public static ArrayList<ApplicationInfo> getAdded_apps()
    {
        return added_apps;
    }

    public static boolean remove_app(ApplicationInfo element)
    {
        return added_apps.remove(element);
    }
}

But I am having problem in saving and retrieving the selected apps by the user 但是我在保存和检索用户选择的应用程序时遇到问题

Save their package names to a SQLite database, SharedPreferences , or some other form of file (eg, JSON). 将其程序包名称保存到SQLite数据库, SharedPreferences或其他文件形式(例如JSON)。

Last option is to store and retrieve the applicationInfo objects via SQLite database but I dont know how to insert and retrieve an ApplicationInfo object to/from database 最后一个选择是通过SQLite数据库存储和检索applicationInfo对象,但是我不知道如何在数据库中插入和提取ApplicationInfo对象。

You can't. 你不能 You save their package names . 您保存他们的包名称 Then, on a future run of your app, you load those package names and get the ApplicationInfo objects from Android via PackageManager for those package names. 然后,在以后运行您的应用程序时,您将加载这些程序包名称,并通过PackageManager从Android获取这些程序包名称的ApplicationInfo对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM