gpt4 book ai didi

java - 使用 SQlite 数据库在自定义 baseadapter ListView 中存储复选框状态

转载 作者:行者123 更新时间:2023-11-30 09:04:24 24 4
gpt4 key购买 nike

我正在使用自定义 BaseAdapter ListView 来显示已安装应用程序的列表,旁边有一个复选框。在尝试使用 SharedPreferences 之后,我试图将每个 ListView 项和复选框状态保存在 SQLite 数据库中。

我希望它在 ListView 关闭后以及应用程序关闭后存储复选框的状态。

enter image description here

我已经做了很多研究并且已经研究了一个多星期,但一直无法产生或找到适合我的解决方案。

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com