Android:即使应用程序关闭,如何保存ArrayList项目?
问题描述:
我正在开发一个应用程序,我必须在列表视图中显示所有安装的应用程序和复选框。每当用户从列表中选择应用程序信息对象(对应于选中的复选框)的任何复选框添加到我的全局类变量ArrayList added_apps)。我成功地这样做了。但问题是,每当我退出应用程序时,用户添加到added_apps ArrayList的所有项目都不会保存。我必须再次添加arraylist中的项目才能继续。我已经尝试过,这里是我的代码,但它不起作用。Android:即使应用程序关闭,如何保存ArrayList项目?
代码显示安装的应用,并加入全球类变量added_apps的ArrayList上checkboxClick监听器:
mainactivity.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:
<?xml version="1.0" encoding="utf-8"?>
<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>
Activitymain.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);
//teenadd=(Toolbar) findViewById(R.id.teenaddtb);
//setSupportActionBar(teenadd);
//getSupportActionBar().setTitle("Restrict Your APP's");
Button btn1=(Button) findViewById(R.id.btn_add);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
MyAddedapss.writeList(Teen3Activity.this,MyAddedapss.getAdded_apps()); //here i am storing ArrayList of Added applications to file
if(MyAddedapss.getAdded_apps().isEmpty())
{
Toast.makeText(getApplicationContext(), "Nothing to ADD!", Toast.LENGTH_LONG).show();
}
else
{
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);
}
}
}
应用适配器:
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:(包含写方法数组列表保存到文件环球类)
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);
}
public static ArrayList<ApplicationInfo> readList(Context c)
{
try
{
FileInputStream fis = c.openFileInput("NAME");
ObjectInputStream is = new ObjectInputStream(fis);
ArrayList<ApplicationInfo> list = (ArrayList<ApplicationInfo>)is.readObject();
is.close();
return list;
}
catch(Exception ex)
{
ex.printStackTrace();
return null;
}
}
public static void writeList(Context c, ArrayList<ApplicationInfo> list){
try
{
FileOutputStream fos = c.openFileOutput("NAME", Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(list);
os.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
答
将值永久存储在应用程序中的一种方法是使用SharedPreferences。基本上,您需要做的唯一事情就是在检查时将您的值存储在SharedPreferences中,并在取消选中时删除它们。
阅读更多:
https://developer.android.com/reference/android/content/SharedPreferences.html
也许我错过了,但我没有看到你打电话readList任何地方。你真的加载列表吗? – Slubberdegullion
是的,但我使用另一个acticvity readlist方法,我必须加载该应用程序列表,然后执行其他操作。 – Iqra
相关:http://stackoverflow.com/questions/7057845/save-arraylist-to-sharedpreferences – Joel