- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用自定义 BaseAdapter ListView 来显示已安装应用程序的列表,旁边有一个复选框。在尝试使用 SharedPreferences 之后,我试图将每个 ListView 项和复选框状态保存在 SQLite 数据库中。
我希望它在 ListView 关闭后以及应用程序关闭后存储复选框的状态。
我已经做了很多研究并且已经研究了一个多星期,但一直无法产生或找到适合我的解决方案。
How to save state of checkboxes in database (both true and false states)
Storing the state of checkbox in listview while using custom BaseAdapter in android?
这是我的 BaseAdapter 类:
package com.ibc.android.demo.appslist.app;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import com.spicycurryman.getdisciplined10.app.R;
import java.util.List;
public class ApkAdapter extends BaseAdapter {
//Pastebin link: http://pastebin.com/LGRicg4U , http://pastebin.com/c4WfmhMK http://pastebin.com/gFuuM4dY
SharedPreferences sharedPrefs;
List<PackageInfo> packageList;
Activity context;
PackageManager packageManager;
boolean[] itemChecked;
String PACKAGE_NAME;
public ApkAdapter(Activity context, List<PackageInfo> packageList,
PackageManager packageManager) {
super();
this.context = context;
this.packageList = packageList;
this.packageManager = packageManager;
itemChecked = new boolean[packageList.size()];
}
private class ViewHolder {
TextView apkName;
CheckBox ck1;
}
public int getCount() {
return packageList.size();
}
public Object getItem(int position) {
return packageList.get(position);
}
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.installed_apps, null);
holder = new ViewHolder();
holder.apkName = (TextView) convertView
.findViewById(R.id.appname);
holder.ck1 = (CheckBox) convertView
.findViewById(R.id.checkBox1);
convertView.setTag(holder);
//holder.ck1.setTag(packageList.get(position));
} else {
holder = (ViewHolder) convertView.getTag();
}
// ViewHolder holder = (ViewHolder) convertView.getTag();
PackageInfo packageInfo = (PackageInfo) getItem(position);
Drawable appIcon = packageManager
.getApplicationIcon(packageInfo.applicationInfo);
PACKAGE_NAME = packageInfo.packageName;
final String appName = packageManager.getApplicationLabel(
packageInfo.applicationInfo).toString();
appIcon.setBounds(0, 0, 80, 80);
holder.apkName.setCompoundDrawables(appIcon, null, null, null);
holder.apkName.setCompoundDrawablePadding(15);
holder.apkName.setText(appName);
holder.ck1.setChecked(false);
if (itemChecked[position])
holder.ck1.setChecked(true);
else
holder.ck1.setChecked(false);
Log.d("just loaded??", appName);
Log.d("just loaded 2?", appName);
holder.ck1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
/* sharedPrefs = context.getSharedPreferences("apps", Context.MODE_PRIVATE);
holder.ck1.setChecked(sharedPrefs.getBoolean(appName,false));
SharedPreferences.Editor editor = context.getSharedPreferences(appName, Context.MODE_PRIVATE).edit();*/
if (holder.ck1.isChecked()) {
itemChecked[position] = true;
holder.ck1.setChecked(true);
Log.i("This is", " checked: " + position);
//editor.putBoolean(appName, true);
Log.d("put true", appName);
//editor.apply();
} else {
itemChecked[position] = false;
holder.ck1.setChecked(false);
Log.i("This is", " not checked: " + position);
//editor.putBoolean(appName, false);
Log.d("put false", appName);
//editor.apply();
}
}
});
return convertView;
}
}
这是我的 DataBaseHandler 类:
package com.ibc.android.demo.appslist.app;
/**
* Created by Spicycurryman on 8/5/14.
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
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 = "packagenameManager";
// Packagename table name
private static final String TABLE_PACKAGE_NAME = "packagenames";
// Contacts Table Columns names
private static final String KEY_PACKAGE_NAME = "packagenames";
private static final String KEY_STATE = "state";
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_PACKAGE_NAME + "("
+ KEY_PACKAGE_NAME + " STRING PRIMARY KEY," + KEY_STATE + " INT,"
+ ")";
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_PACKAGE_NAME);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new packagename
void addPackageName(PackageName packageName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATE, packageName.getPACKAGENAME()); // Packagename
// Inserting Row
db.insert(TABLE_PACKAGE_NAME, null, values);
db.close(); // Closing database connection
}
// Getting single package
PackageName getPackageName(String packagename) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_PACKAGE_NAME, new String[] {KEY_PACKAGE_NAME,
KEY_STATE }, KEY_PACKAGE_NAME + "=?",
new String[] { packagename }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
PackageName packageName = new PackageName((cursor.getString(0)),
cursor.getInt(1));
// return packagename
return packageName;
}
// Getting All packagenames
public List<PackageName> getAllPackageNames() {
List<PackageName> packageNameList = new ArrayList<PackageName>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_PACKAGE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
PackageName packageName = new PackageName();
packageName.setPACKAGENAME(cursor.getString(0));
packageName.setState(cursor.getInt(1));
// Adding contact to list
packageNameList.add(packageName);
} while (cursor.moveToNext());
}
// return packagename list
return packageNameList;
}
// Updating single packagename
public int updatePackageName(PackageName packageName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATE, packageName.getState());
// updating row
return db.update(TABLE_PACKAGE_NAME, values, KEY_PACKAGE_NAME + " = ?",
new String[] { String.valueOf(packageName.getPACKAGENAME()) });
}
// Deleting single packagename
public void deletePackageName(PackageName packageName) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_PACKAGE_NAME, KEY_PACKAGE_NAME + " = ?",
new String[] { String.valueOf(packageName.getPACKAGENAME()) });
db.close();
}
// Getting packagename Count
public int getPackageNameCount() {
String countQuery = "SELECT * FROM " + TABLE_PACKAGE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
最后这是我的对象类:
package com.ibc.android.demo.appslist.app;
/**
* Created by Spicycurryman on 8/5/14.
*/
public class PackageName {
//private variables
String _packagename;
int _state;
// Empty constructor
public PackageName(){
}
// constructor
public PackageName(String packagename, int state){
this._packagename = packagename;
this._state = state;
}
// constructor
public PackageName(int state){
this._state = state;
}
// getting PACKAGENAME
public String getPACKAGENAME(){
return this._packagename;
}
// setting packagename
public void setPACKAGENAME(String packagename){
this._packagename = packagename;
}
// getting state
public int getState(){
return this._state;
}
// setting state
public void setState(int state){
this._state = state;
}
}
我将如何实现这一目标?
最佳答案
ListView_CheckBoxActivity 类
@SuppressLint("NewApi")
public class ListView_CheckBoxActivity extends Activity {
CheckboxAdapter listItemAdapter;
DataHandler handler;
Button cancel;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
handler=new DataHandler(getBaseContext());
handler.open();
System.out.println("Entered in the checked box");
Button getValue=(Button)findViewById(R.id.get_value);
cancel=(Button) findViewById(R.id.cancel);
getValue.setOnClickListener(listener);
//listview
ListView list = (ListView) findViewById(R.id.list);
ArrayList<HashMap<String, Object>> listData=new ArrayList<HashMap<String,Object>>();
int size=0;
Cursor getSize=handler.CategoryNameLength();
getSize.moveToFirst();
size=getSize.getInt(0);
String[] name=new String[size];
int catgoryIndex=0;
Cursor getCategoryName=handler.CategoryName();
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
if(getCategoryName.moveToFirst())
{
do
{
name[catgoryIndex]=getCategoryName.getString(0);
System.out.println("Strng"+name[catgoryIndex]);
catgoryIndex++;
}while(getCategoryName.moveToNext());
}
for(int i=0;i<size;i++){
HashMap<String, Object> map=new HashMap<String, Object>();
System.out.println("Line1");
map.put("friend_image", R.drawable.icon);
map.put("friend_username", name[i]);
listData.add(map);
}
listItemAdapter = new CheckboxAdapter(this, listData);
list.setAdapter(listItemAdapter);
}
OnClickListener listener=new OnClickListener() {
@Override
public void onClick(View v) {
HashMap<Integer, Boolean> state =listItemAdapter.state;
String options="***Selected***";
for(int j=0;j<listItemAdapter.getCount();j++){
System.out.println("state.get("+j+")=="+state.get(j));
//checking the state is on , if on i,m updating my table
if(state.get(j)!=null){
@SuppressWarnings("unchecked")
HashMap<String, Object> map=(HashMap<String, Object>) listItemAdapter.getItem(j);
String username=map.get("friend_username").toString();
Cursor getID=handler.getIdForCategory(username);
getID.moveToFirst();
int id=getID.getInt(0);
System.out.println("ID=="+id);
handler.updateDefaulttable_flag_1(id);//updating my table
options+="\n"+username;
}
//same as checking sate is off, if off updating my database table
if(state.get(j)== null){
@SuppressWarnings("unchecked")
HashMap<String, Object> map=(HashMap<String, Object>) listItemAdapter.getItem(j);
String username=map.get("friend_username").toString();
Cursor getID=handler.getIdForCategory(username);
getID.moveToFirst();
int id=getID.getInt(0);
System.out.println("ID=="+id);
handler.updateDefaulttable_flag_0(id);
}
}
Toast.makeText(getApplicationContext(), options, Toast.LENGTH_LONG).show();
finish();
}
};
}
项目.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="4dip"
android:paddingRight="12dip" >
<ImageView android:id="@+id/friend_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="2dip"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true" />
<TextView android:id="@+id/friend_username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18dip"
android:textColor="#ccc"
android:paddingTop="6dip"
android:paddingRight="2dip"
android:layout_toRightOf="@id/friend_image" />
<TextView android:id="@+id/friend_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/friend_username"
android:layout_marginRight="36dip"
android:paddingRight="2dip"
android:layout_toRightOf="@id/friend_image"
android:textColor="#fff"
android:maxLines="2" />
<CheckBox android:id="@+id/selected"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="36dip"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:focusable="false" />
</RelativeLayout>
复选框适配器类
public class CheckboxAdapter extends BaseAdapter {
DataHandler handler;
SQLiteDatabase db;
Context context;
ArrayList<HashMap<String, Object>> listData;
HashMap<Integer, Boolean> state = new HashMap<Integer, Boolean>();
public CheckboxAdapter(Context context, ArrayList<HashMap<String, Object>> listData) {
this.context = context;
this.listData = listData;
}
@Override
public int getCount() {
return listData.size();
}
@Override
public Object getItem(int position) {
return listData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = LayoutInflater.from(context);
convertView = mInflater.inflate(R.layout.item, null);
ImageView image = (ImageView) convertView.findViewById(R.id.friend_image);
image.setBackgroundResource((Integer) listData.get(position).get("friend_image"));
TextView username = (TextView) convertView.findViewById(R.id.friend_username);
username.setText((String) listData.get(position).get("friend_username"));
CheckBox check = (CheckBox) convertView.findViewById(R.id.selected);
boolean isChecked=true;
handler=new DataHandler(context);
handler.open();
Cursor setUserFlag = handler.setCheckFlagID();
if(setUserFlag.moveToFirst())
{
do
{
int getid = setUserFlag.getInt(0);
getid = getid - 1;
state.put(getid , isChecked);
}while(setUserFlag.moveToNext());
}
check.setChecked((state.get(position) == null ? false : true));
handler.close();
check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
state.put(position, isChecked);
} else {
state.remove(position);
}
}
});
check.setChecked((state.get(position) == null ? false : true));
return convertView;
}
}
数据处理器
public Cursor setCheckFlagID() {
return db.rawQuery("select _id from default_category_table where flag=1;", null);
}
public void updateDefaulttable_flag_1(int id) {
String selectQuery = "UPDATE default_category_table SET flag=1 WHERE _id='"+id+"'";
Cursor cursor = db.rawQuery(selectQuery, null);
System.out.print("Count"+cursor.getCount());
}
public void updateDefaulttable_flag_0(int id) {
String selectQuery = "UPDATE default_category_table SET flag=0 WHERE _id='"+id+"'";
Cursor cursor = db.rawQuery(selectQuery, null);
System.out.print("Count"+cursor.getCount());
}
public Cursor getIdForCategory(String username) {
return db.rawQuery("select _id from default_category_table where category='"+username+"';", null);
}
public Cursor CategoryNameLength() {
return db.rawQuery("select count(category) from Default_Category_Table", null);
}
主.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="272dp"
android:layout_weight="5.16" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/get_value"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="23dp"
android:paddingRight="20dp"
android:text="Save" />
<Button
android:id="@+id/cancel"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="34dp"
android:text="Cancel" />
</RelativeLayout>
</LinearLayout>
关于java - 使用 SQlite 数据库在自定义 baseadapter ListView 中存储复选框状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25247224/
好的,所以我编辑了以下... 只需将以下内容放入我的 custom.css #rt-utility .rt-block {CODE HERE} 但是当我尝试改变... 与 #rt-sideslid
在表格 View 中,我有一个自定义单元格(在界面生成器中高度为 500)。在该单元格中,我有一个 Collection View ,我按 (10,10,10,10) 固定到边缘。但是在 tablev
对于我的无能,我很抱歉,但总的来说,我对 Cocoa、Swift 和面向对象编程还很陌生。我的主要来源是《Cocoa Programming for OS X》(第 5 版),以及 Apple 的充满
我正在使用 meta-tegra 为我的 NVIDIA Jetson Nano 构建自定义图像。我需要 PyTorch,但没有它的配方。我在设备上构建了 PyTorch,并将其打包到设备上的轮子中。现
在 jquery 中使用 $.POST 和 $.GET 时,有没有办法将自定义变量添加到 URL 并发送它们?我尝试了以下方法: $.ajax({type:"POST", url:"file.php?
Traefik 已经默认实现了很多中间件,可以满足大部分我们日常的需求,但是在实际工作中,用户仍然还是有自定义中间件的需求,为解决这个问题,官方推出了一个 Traefik Pilot[1] 的功
我想让我的 CustomTextInputLayout 将 Widget.MaterialComponents.TextInputLayout.OutlinedBox 作为默认样式,无需在 XML 中
我在 ~/.emacs 中有以下自定义函数: (defun xi-rgrep (term) (grep-compute-defaults) (interactive "sSearch Te
我有下表: 考虑到每个月的权重,我的目标是在 5 个月内分散 10,000 个单位。与 10,000 相邻的行是我最好的尝试(我在这上面花了几个小时)。黄色是我所追求的。 我试图用来计算的逻辑如下:计
我的表单中有一个字段,它是文件类型。当用户点击保存图标时,我想自然地将文件上传到服务器并将文件名保存在数据库中。我尝试通过回显文件名来测试它,但它似乎不起作用。另外,如何将文件名添加到数据库中?是在模
我有一个 python 脚本来发送电子邮件,它工作得很好,但问题是当我检查我的电子邮件收件箱时。 我希望该用户名是自定义用户名,而不是整个电子邮件地址。 最佳答案 发件人地址应该使用的格式是: You
我想减小 ggcorrplot 中标记的大小,并减少文本和绘图之间的空间。 library(ggcorrplot) data(mtcars) corr <- round(cor(mtcars), 1)
GTK+ noob 问题在这里: 是否可以自定义 GtkFileChooserButton 或 GtkFileChooserDialog 以删除“位置”部分(左侧)和顶部的“位置”输入框? 我实际上要
我正在尝试在主页上使用 ajax 在 magento 中使用 ajax 显示流行的产品列表,我可以为 5 或“N”个产品执行此操作,但我想要的是将分页工具栏与结果集一起添加. 这是我添加的以显示流行产
我正在尝试使用 PasswordResetForm 内置函数。 由于我想要自定义表单字段,因此我编写了自己的表单: class FpasswordForm(PasswordResetForm):
据我了解,新的 Angular 7 提供了拖放功能。我搜索了有关 DnD 的 Tree 组件,但没有找到与树相关的内容。 我在 Stackblitz 上找到的一个工作示例.对比drag'ndrop功能
我必须开发一个自定义选项卡控件并决定使用 WPF/XAML 创建它,因为我无论如何都打算学习它。完成后应该是这样的: 到目前为止,我取得了很好的进展,但还有两个问题: 只有第一个/最后一个标签项应该有
我要定制xtable用于导出到 LaTeX。我知道有些问题是关于 xtable在这里,但我找不到我要找的具体东西。 以下是我的表的外观示例: my.table <- data.frame(Specif
用ejs在这里显示日期 它给我结果 Tue Feb 02 2016 16:02:24 GMT+0530 (IST) 但是我需要表现为 19th January, 2016 如何在ejs中执行此操作?
我想问在 JavaFX 中使用自定义对象制作 ListView 的最佳方法,我想要一个每个项目如下所示的列表: 我搜了一下,发现大部分人都是用细胞工厂的方法来做的。有没有其他办法?例如使用客户 fxm
我是一名优秀的程序员,十分优秀!