Java 从SQLite获取数据到ListView';s ArrayList
我想制作一个报价应用程序,其中显示报价、作者和fav按钮 我有一个自定义的ListView,它有两个文本视图和一个切换按钮 我正在使用带有预填充数据的SQLite(因此我已经拥有了所有数据) 如何在不使用SimpleCursorAdapter的情况下向2个文本视图显示引用和作者 我想使用ArrayList和ArrayAdapter实现它 这是密码 数据库OpenHelper.javaJava 从SQLite获取数据到ListView';s ArrayList,java,android,sqlite,listview,android-studio,Java,Android,Sqlite,Listview,Android Studio,我想制作一个报价应用程序,其中显示报价、作者和fav按钮 我有一个自定义的ListView,它有两个文本视图和一个切换按钮 我正在使用带有预填充数据的SQLite(因此我已经拥有了所有数据) 如何在不使用SimpleCursorAdapter的情况下向2个文本视图显示引用和作者 我想使用ArrayList和ArrayAdapter实现它 这是密码 数据库OpenHelper.java public class DatabaseOpenHelper extends SQLiteAssetHelpe
public class DatabaseOpenHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "mqn.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "quote";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_QUOTES = "quotesText";
public static final String COLUMN_AUTHOR= "author";
public static final String COLUMN_FAV = "fav";
public static final String COLUMN_GENRE = "genre";
private SQLiteDatabase database;
private final Context context;
// database path
private static String DATABASE_PATH;
/** constructor (Menambil PATH ke file database) */
public DatabaseOpenHelper(Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
this.context = ctx;
DATABASE_PATH = context.getFilesDir().getParentFile().getPath()
+ "/databases/";
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void create() throws IOException {
boolean check = checkDataBase();
SQLiteDatabase db_Read = null;
// Creates empty database default system path
db_Read = this.getWritableDatabase();
db_Read.close();
try {
if (!check) {
copyDataBase();
}
} catch (IOException e) {
throw new Error("Error copying database");
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DATABASE_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = context.getAssets().open(DATABASE_NAME);
// Path to the just created empty db
String outFileName = DATABASE_PATH + DATABASE_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
/** Start DB from here */
/** open the database */
public void open() throws SQLException {
String myPath = DATABASE_PATH + DATABASE_NAME;
database = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
/** close the database */
@Override
public synchronized void close() {
if (database != null)
database.close();
super.close();
}
// insert a user into the database
public long insertUser(String quotesText, String author, String fav) {
ContentValues initialValues = new ContentValues();
initialValues.put(COLUMN_QUOTES, quotesText );
initialValues.put(COLUMN_AUTHOR, author);
initialValues.put(COLUMN_FAV, fav);
return database.insert(TABLE_NAME, null, initialValues);
}
// updates a user
public boolean updateUser(long rowId, String fav) {
ContentValues args = new ContentValues();
args.put(COLUMN_FAV, fav);
return database.update(TABLE_NAME, args, COLUMN_ID + "=" + rowId, null) > 0;
}
// retrieves a particular user
public Cursor getUser(long rowId) throws SQLException {
Cursor mCursor = database.query(true, TABLE_NAME, new String[] {
COLUMN_ID, COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV },
COLUMN_ID + " = " + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
// delete a particular user
public boolean deleteContact(long rowId) {
return database.delete(TABLE_NAME, COLUMN_ID + "=" + rowId, null) > 0;
}
// retrieves all users
public Cursor getAllUsers() {
return database.query(TABLE_NAME, new String[] { COLUMN_ID,
COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV }, null, null,
null, null, null);
}
public Cursor getCertain(String valueGenre) {
String WHERE = "genre = ?";
String[] VALUE = new String[] {valueGenre};
return database.query(TABLE_NAME, new String[]{COLUMN_ID,
COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV}, WHERE, VALUE,
null, null, null);
}
public class ListOfQuotes {
private String quote;
private String author;
private int fav;
public ListOfQuotes() {
}
public ListOfQuotes(String quote, String author, int fav) {
this.quote = quote;
this.author = author;
this.fav = fav;
}
public ListOfQuotes(String quote, String author) {
this.quote = quote;
this.author = author;
}
public String getQuote() {
return quote;
}
public void setQuote(String quote) {
this.quote = quote;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getFav() {
return fav;
}
public void setFav(int fav) {
this.fav = fav;
}
}
public class QuotesAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<ListOfQuotes> data;
private LayoutInflater inflater;
boolean isSelected = false;
ToggleButton imgHeart;
public QuotesAdapter(Activity activity, ArrayList<ListOfQuotes> data) {
this.activity = activity;
this.data = data;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ListOfQuotes loq = data.get(position);
if(convertView == null)
{
convertView = inflater.inflate(R.layout.quotes_listview, null);
}
TextView txtQuotes = (TextView) convertView.findViewById(R.id.txtQuote);
TextView txtAuthors = (TextView) convertView.findViewById(R.id.txtAuthor);
imgHeart = (ToggleButton) convertView.findViewById(R.id.heartImage);
txtQuotes.setText(loq.getQuote());
txtAuthors.setText(loq.getAuthor());
return convertView;
}
}
public class QuotesActivity extends AppCompatActivity {
ListView quotesList;
DatabaseOpenHelper myDbHelper;
ArrayList<ListOfQuotes> arrQuotes;
QuotesAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes);
myDbHelper = new DatabaseOpenHelper(this);
try {
// check if database exists in app path, if not copy it from assets
myDbHelper.create();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
// open the database
myDbHelper.open();
myDbHelper.getWritableDatabase();
} catch (SQLException sqle) {
throw sqle;
}
arrQuotes = new ArrayList<ListOfQuotes>();
quotesList = (ListView) findViewById(R.id.quotesList);
adapter = new QuotesAdapter(QuotesActivity.this, arrQuotes);
quotesList.setAdapter(adapter);
public class ListViewActivity extends Activity
{
ListView listCustom;
private SQLiteDatabase db;
ProductDatabase customerDB;
ProductAdapter customAdapter;
static final String DATABASE_NAME = "login.db";
public static String DB_PATH;
private ArrayList<LevelList> results = new ArrayList<LevelList>();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.product_list);
levelLists = new ArrayList<LevelList>();
customerDB = new ProductDatabase(getApplicationContext());
customerDB = customerDB.open();
listCustom = (ListView) findViewById(R.id.listView1);
mainMenu();
}
public void mainMenu()
{
results.clear();
DB_PATH = "/data/data/com.gt.invoicemaker/databases/";
String myPath = DB_PATH + DATABASE_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READONLY);
final Cursor c = db.rawQuery("SELECT ID AS _id, USERID, INAME, IPRICE FROM ITEM, null);
// Note: Master is the one table in External db. Here we trying to access the records of table from external db.
if (c != null ) {
if (c.moveToFirst()) {
do {
LevelList results1 = new LevelList();
int _id = c.getInt(c.getColumnIndex("_id"));
String userName = c.getString(c.getColumnIndex("INAME"));
results1.id = _id;
results1.item = userName;
results.add(results1);
}while (c.moveToNext());
}
}
customAdapter = new ProductAdapter(getApplicationContext(), results);
listCustom.setAdapter(customAdapter);
}
}
}
public class ProductAdapter extends BaseAdapter {
private Context mContext;
private List<LevelList> listItem;
public ProductAdapter(Context c,List<LevelList> listItem) {
mContext = c;
this.listItem = listItem;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return listItem.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listItem;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView=inflater.inflate(R.layout.singleproduct, null,true);
TextView textView = (TextView) rowView.findViewById(R.id.single_product);
textView.setText(listItem.get(position).item);
return rowView;
}
}
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
@Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(ProductDatabase.DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
@Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
// Create a new one.
onCreate(_db);
}
}
引用\u列表视图(自定义列表视图)
quoteAdapter.java
public class DatabaseOpenHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "mqn.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "quote";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_QUOTES = "quotesText";
public static final String COLUMN_AUTHOR= "author";
public static final String COLUMN_FAV = "fav";
public static final String COLUMN_GENRE = "genre";
private SQLiteDatabase database;
private final Context context;
// database path
private static String DATABASE_PATH;
/** constructor (Menambil PATH ke file database) */
public DatabaseOpenHelper(Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
this.context = ctx;
DATABASE_PATH = context.getFilesDir().getParentFile().getPath()
+ "/databases/";
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void create() throws IOException {
boolean check = checkDataBase();
SQLiteDatabase db_Read = null;
// Creates empty database default system path
db_Read = this.getWritableDatabase();
db_Read.close();
try {
if (!check) {
copyDataBase();
}
} catch (IOException e) {
throw new Error("Error copying database");
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DATABASE_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = context.getAssets().open(DATABASE_NAME);
// Path to the just created empty db
String outFileName = DATABASE_PATH + DATABASE_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
/** Start DB from here */
/** open the database */
public void open() throws SQLException {
String myPath = DATABASE_PATH + DATABASE_NAME;
database = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
/** close the database */
@Override
public synchronized void close() {
if (database != null)
database.close();
super.close();
}
// insert a user into the database
public long insertUser(String quotesText, String author, String fav) {
ContentValues initialValues = new ContentValues();
initialValues.put(COLUMN_QUOTES, quotesText );
initialValues.put(COLUMN_AUTHOR, author);
initialValues.put(COLUMN_FAV, fav);
return database.insert(TABLE_NAME, null, initialValues);
}
// updates a user
public boolean updateUser(long rowId, String fav) {
ContentValues args = new ContentValues();
args.put(COLUMN_FAV, fav);
return database.update(TABLE_NAME, args, COLUMN_ID + "=" + rowId, null) > 0;
}
// retrieves a particular user
public Cursor getUser(long rowId) throws SQLException {
Cursor mCursor = database.query(true, TABLE_NAME, new String[] {
COLUMN_ID, COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV },
COLUMN_ID + " = " + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
// delete a particular user
public boolean deleteContact(long rowId) {
return database.delete(TABLE_NAME, COLUMN_ID + "=" + rowId, null) > 0;
}
// retrieves all users
public Cursor getAllUsers() {
return database.query(TABLE_NAME, new String[] { COLUMN_ID,
COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV }, null, null,
null, null, null);
}
public Cursor getCertain(String valueGenre) {
String WHERE = "genre = ?";
String[] VALUE = new String[] {valueGenre};
return database.query(TABLE_NAME, new String[]{COLUMN_ID,
COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV}, WHERE, VALUE,
null, null, null);
}
public class ListOfQuotes {
private String quote;
private String author;
private int fav;
public ListOfQuotes() {
}
public ListOfQuotes(String quote, String author, int fav) {
this.quote = quote;
this.author = author;
this.fav = fav;
}
public ListOfQuotes(String quote, String author) {
this.quote = quote;
this.author = author;
}
public String getQuote() {
return quote;
}
public void setQuote(String quote) {
this.quote = quote;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getFav() {
return fav;
}
public void setFav(int fav) {
this.fav = fav;
}
}
public class QuotesAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<ListOfQuotes> data;
private LayoutInflater inflater;
boolean isSelected = false;
ToggleButton imgHeart;
public QuotesAdapter(Activity activity, ArrayList<ListOfQuotes> data) {
this.activity = activity;
this.data = data;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ListOfQuotes loq = data.get(position);
if(convertView == null)
{
convertView = inflater.inflate(R.layout.quotes_listview, null);
}
TextView txtQuotes = (TextView) convertView.findViewById(R.id.txtQuote);
TextView txtAuthors = (TextView) convertView.findViewById(R.id.txtAuthor);
imgHeart = (ToggleButton) convertView.findViewById(R.id.heartImage);
txtQuotes.setText(loq.getQuote());
txtAuthors.setText(loq.getAuthor());
return convertView;
}
}
public class QuotesActivity extends AppCompatActivity {
ListView quotesList;
DatabaseOpenHelper myDbHelper;
ArrayList<ListOfQuotes> arrQuotes;
QuotesAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes);
myDbHelper = new DatabaseOpenHelper(this);
try {
// check if database exists in app path, if not copy it from assets
myDbHelper.create();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
// open the database
myDbHelper.open();
myDbHelper.getWritableDatabase();
} catch (SQLException sqle) {
throw sqle;
}
arrQuotes = new ArrayList<ListOfQuotes>();
quotesList = (ListView) findViewById(R.id.quotesList);
adapter = new QuotesAdapter(QuotesActivity.this, arrQuotes);
quotesList.setAdapter(adapter);
public class ListViewActivity extends Activity
{
ListView listCustom;
private SQLiteDatabase db;
ProductDatabase customerDB;
ProductAdapter customAdapter;
static final String DATABASE_NAME = "login.db";
public static String DB_PATH;
private ArrayList<LevelList> results = new ArrayList<LevelList>();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.product_list);
levelLists = new ArrayList<LevelList>();
customerDB = new ProductDatabase(getApplicationContext());
customerDB = customerDB.open();
listCustom = (ListView) findViewById(R.id.listView1);
mainMenu();
}
public void mainMenu()
{
results.clear();
DB_PATH = "/data/data/com.gt.invoicemaker/databases/";
String myPath = DB_PATH + DATABASE_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READONLY);
final Cursor c = db.rawQuery("SELECT ID AS _id, USERID, INAME, IPRICE FROM ITEM, null);
// Note: Master is the one table in External db. Here we trying to access the records of table from external db.
if (c != null ) {
if (c.moveToFirst()) {
do {
LevelList results1 = new LevelList();
int _id = c.getInt(c.getColumnIndex("_id"));
String userName = c.getString(c.getColumnIndex("INAME"));
results1.id = _id;
results1.item = userName;
results.add(results1);
}while (c.moveToNext());
}
}
customAdapter = new ProductAdapter(getApplicationContext(), results);
listCustom.setAdapter(customAdapter);
}
}
}
public class ProductAdapter extends BaseAdapter {
private Context mContext;
private List<LevelList> listItem;
public ProductAdapter(Context c,List<LevelList> listItem) {
mContext = c;
this.listItem = listItem;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return listItem.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listItem;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView=inflater.inflate(R.layout.singleproduct, null,true);
TextView textView = (TextView) rowView.findViewById(R.id.single_product);
textView.setText(listItem.get(position).item);
return rowView;
}
}
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
@Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(ProductDatabase.DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
@Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
// Create a new one.
onCreate(_db);
}
}
公共类QuoteAdapter扩展了BaseAdapter{
私人活动;
私有数组列表数据;
私人充气机;
布尔值=假;
切换按钮imgHeart;
公共QuotesAdapter(活动、ArrayList数据){
这个。活动=活动;
这个数据=数据;
this.inflater=(LayoutInflater)activity.getSystemService(Context.LAYOUT\u inflater\u SERVICE);
}
@凌驾
public int getCount(){
返回data.size();
}
@凌驾
公共对象getItem(int位置){
返回数据。获取(位置);
}
@凌驾
公共长getItemId(int位置){
返回位置;
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
ListOfQuotes loq=data.get(位置);
if(convertView==null)
{
convertView=充气机。充气(R.layout.quotes\u listview,null);
}
TextView txtQuotes=(TextView)convertView.findViewById(R.id.txtQuote);
TextView txtAuthors=(TextView)convertView.findViewById(R.id.txtAuthor);
imgHeart=(ToggleButton)convertView.findViewById(R.id.heartImage);
setText(loq.getQuote());
setText(loq.getAuthor());
返回视图;
}
}
quoteActivity.java
public class DatabaseOpenHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "mqn.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "quote";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_QUOTES = "quotesText";
public static final String COLUMN_AUTHOR= "author";
public static final String COLUMN_FAV = "fav";
public static final String COLUMN_GENRE = "genre";
private SQLiteDatabase database;
private final Context context;
// database path
private static String DATABASE_PATH;
/** constructor (Menambil PATH ke file database) */
public DatabaseOpenHelper(Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
this.context = ctx;
DATABASE_PATH = context.getFilesDir().getParentFile().getPath()
+ "/databases/";
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void create() throws IOException {
boolean check = checkDataBase();
SQLiteDatabase db_Read = null;
// Creates empty database default system path
db_Read = this.getWritableDatabase();
db_Read.close();
try {
if (!check) {
copyDataBase();
}
} catch (IOException e) {
throw new Error("Error copying database");
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DATABASE_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = context.getAssets().open(DATABASE_NAME);
// Path to the just created empty db
String outFileName = DATABASE_PATH + DATABASE_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
/** Start DB from here */
/** open the database */
public void open() throws SQLException {
String myPath = DATABASE_PATH + DATABASE_NAME;
database = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
/** close the database */
@Override
public synchronized void close() {
if (database != null)
database.close();
super.close();
}
// insert a user into the database
public long insertUser(String quotesText, String author, String fav) {
ContentValues initialValues = new ContentValues();
initialValues.put(COLUMN_QUOTES, quotesText );
initialValues.put(COLUMN_AUTHOR, author);
initialValues.put(COLUMN_FAV, fav);
return database.insert(TABLE_NAME, null, initialValues);
}
// updates a user
public boolean updateUser(long rowId, String fav) {
ContentValues args = new ContentValues();
args.put(COLUMN_FAV, fav);
return database.update(TABLE_NAME, args, COLUMN_ID + "=" + rowId, null) > 0;
}
// retrieves a particular user
public Cursor getUser(long rowId) throws SQLException {
Cursor mCursor = database.query(true, TABLE_NAME, new String[] {
COLUMN_ID, COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV },
COLUMN_ID + " = " + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
// delete a particular user
public boolean deleteContact(long rowId) {
return database.delete(TABLE_NAME, COLUMN_ID + "=" + rowId, null) > 0;
}
// retrieves all users
public Cursor getAllUsers() {
return database.query(TABLE_NAME, new String[] { COLUMN_ID,
COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV }, null, null,
null, null, null);
}
public Cursor getCertain(String valueGenre) {
String WHERE = "genre = ?";
String[] VALUE = new String[] {valueGenre};
return database.query(TABLE_NAME, new String[]{COLUMN_ID,
COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV}, WHERE, VALUE,
null, null, null);
}
public class ListOfQuotes {
private String quote;
private String author;
private int fav;
public ListOfQuotes() {
}
public ListOfQuotes(String quote, String author, int fav) {
this.quote = quote;
this.author = author;
this.fav = fav;
}
public ListOfQuotes(String quote, String author) {
this.quote = quote;
this.author = author;
}
public String getQuote() {
return quote;
}
public void setQuote(String quote) {
this.quote = quote;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getFav() {
return fav;
}
public void setFav(int fav) {
this.fav = fav;
}
}
public class QuotesAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<ListOfQuotes> data;
private LayoutInflater inflater;
boolean isSelected = false;
ToggleButton imgHeart;
public QuotesAdapter(Activity activity, ArrayList<ListOfQuotes> data) {
this.activity = activity;
this.data = data;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ListOfQuotes loq = data.get(position);
if(convertView == null)
{
convertView = inflater.inflate(R.layout.quotes_listview, null);
}
TextView txtQuotes = (TextView) convertView.findViewById(R.id.txtQuote);
TextView txtAuthors = (TextView) convertView.findViewById(R.id.txtAuthor);
imgHeart = (ToggleButton) convertView.findViewById(R.id.heartImage);
txtQuotes.setText(loq.getQuote());
txtAuthors.setText(loq.getAuthor());
return convertView;
}
}
public class QuotesActivity extends AppCompatActivity {
ListView quotesList;
DatabaseOpenHelper myDbHelper;
ArrayList<ListOfQuotes> arrQuotes;
QuotesAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes);
myDbHelper = new DatabaseOpenHelper(this);
try {
// check if database exists in app path, if not copy it from assets
myDbHelper.create();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
// open the database
myDbHelper.open();
myDbHelper.getWritableDatabase();
} catch (SQLException sqle) {
throw sqle;
}
arrQuotes = new ArrayList<ListOfQuotes>();
quotesList = (ListView) findViewById(R.id.quotesList);
adapter = new QuotesAdapter(QuotesActivity.this, arrQuotes);
quotesList.setAdapter(adapter);
public class ListViewActivity extends Activity
{
ListView listCustom;
private SQLiteDatabase db;
ProductDatabase customerDB;
ProductAdapter customAdapter;
static final String DATABASE_NAME = "login.db";
public static String DB_PATH;
private ArrayList<LevelList> results = new ArrayList<LevelList>();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.product_list);
levelLists = new ArrayList<LevelList>();
customerDB = new ProductDatabase(getApplicationContext());
customerDB = customerDB.open();
listCustom = (ListView) findViewById(R.id.listView1);
mainMenu();
}
public void mainMenu()
{
results.clear();
DB_PATH = "/data/data/com.gt.invoicemaker/databases/";
String myPath = DB_PATH + DATABASE_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READONLY);
final Cursor c = db.rawQuery("SELECT ID AS _id, USERID, INAME, IPRICE FROM ITEM, null);
// Note: Master is the one table in External db. Here we trying to access the records of table from external db.
if (c != null ) {
if (c.moveToFirst()) {
do {
LevelList results1 = new LevelList();
int _id = c.getInt(c.getColumnIndex("_id"));
String userName = c.getString(c.getColumnIndex("INAME"));
results1.id = _id;
results1.item = userName;
results.add(results1);
}while (c.moveToNext());
}
}
customAdapter = new ProductAdapter(getApplicationContext(), results);
listCustom.setAdapter(customAdapter);
}
}
}
public class ProductAdapter extends BaseAdapter {
private Context mContext;
private List<LevelList> listItem;
public ProductAdapter(Context c,List<LevelList> listItem) {
mContext = c;
this.listItem = listItem;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return listItem.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listItem;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView=inflater.inflate(R.layout.singleproduct, null,true);
TextView textView = (TextView) rowView.findViewById(R.id.single_product);
textView.setText(listItem.get(position).item);
return rowView;
}
}
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
@Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(ProductDatabase.DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
@Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
// Create a new one.
onCreate(_db);
}
}
public class quotes活动扩展了appcompative活动{
ListView引用列表;
数据库OpenHelper myDbHelper;
arraylistarrquotes;
QuotesAdapter适配器;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes);
myDbHelper=新数据库OpenHelper(此);
试一试{
//检查应用程序路径中是否存在数据库,如果不存在,请从资产复制数据库
myDbHelper.create();
}捕获(ioe异常ioe){
抛出新错误(“无法创建数据库”);
}
试一试{
//打开数据库
myDbHelper.open();
myDbHelper.getWritableDatabase();
}捕获(SQLException sqle){
抛出sqle;
}
arrQuotes=newarraylist();
quotesList=(ListView)findViewById(R.id.quotesList);
适配器=新的QuotesAdapter(QuotesActivity.this,arrQuotes);
quotesList.setAdapter(适配器);
我不知道在这之后怎么做。尝试使用这段代码,并将您的额外字段放在.xml文件和.java文件中 ListViewActivity.java
public class DatabaseOpenHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "mqn.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "quote";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_QUOTES = "quotesText";
public static final String COLUMN_AUTHOR= "author";
public static final String COLUMN_FAV = "fav";
public static final String COLUMN_GENRE = "genre";
private SQLiteDatabase database;
private final Context context;
// database path
private static String DATABASE_PATH;
/** constructor (Menambil PATH ke file database) */
public DatabaseOpenHelper(Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
this.context = ctx;
DATABASE_PATH = context.getFilesDir().getParentFile().getPath()
+ "/databases/";
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void create() throws IOException {
boolean check = checkDataBase();
SQLiteDatabase db_Read = null;
// Creates empty database default system path
db_Read = this.getWritableDatabase();
db_Read.close();
try {
if (!check) {
copyDataBase();
}
} catch (IOException e) {
throw new Error("Error copying database");
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DATABASE_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = context.getAssets().open(DATABASE_NAME);
// Path to the just created empty db
String outFileName = DATABASE_PATH + DATABASE_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
/** Start DB from here */
/** open the database */
public void open() throws SQLException {
String myPath = DATABASE_PATH + DATABASE_NAME;
database = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
/** close the database */
@Override
public synchronized void close() {
if (database != null)
database.close();
super.close();
}
// insert a user into the database
public long insertUser(String quotesText, String author, String fav) {
ContentValues initialValues = new ContentValues();
initialValues.put(COLUMN_QUOTES, quotesText );
initialValues.put(COLUMN_AUTHOR, author);
initialValues.put(COLUMN_FAV, fav);
return database.insert(TABLE_NAME, null, initialValues);
}
// updates a user
public boolean updateUser(long rowId, String fav) {
ContentValues args = new ContentValues();
args.put(COLUMN_FAV, fav);
return database.update(TABLE_NAME, args, COLUMN_ID + "=" + rowId, null) > 0;
}
// retrieves a particular user
public Cursor getUser(long rowId) throws SQLException {
Cursor mCursor = database.query(true, TABLE_NAME, new String[] {
COLUMN_ID, COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV },
COLUMN_ID + " = " + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
// delete a particular user
public boolean deleteContact(long rowId) {
return database.delete(TABLE_NAME, COLUMN_ID + "=" + rowId, null) > 0;
}
// retrieves all users
public Cursor getAllUsers() {
return database.query(TABLE_NAME, new String[] { COLUMN_ID,
COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV }, null, null,
null, null, null);
}
public Cursor getCertain(String valueGenre) {
String WHERE = "genre = ?";
String[] VALUE = new String[] {valueGenre};
return database.query(TABLE_NAME, new String[]{COLUMN_ID,
COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV}, WHERE, VALUE,
null, null, null);
}
public class ListOfQuotes {
private String quote;
private String author;
private int fav;
public ListOfQuotes() {
}
public ListOfQuotes(String quote, String author, int fav) {
this.quote = quote;
this.author = author;
this.fav = fav;
}
public ListOfQuotes(String quote, String author) {
this.quote = quote;
this.author = author;
}
public String getQuote() {
return quote;
}
public void setQuote(String quote) {
this.quote = quote;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getFav() {
return fav;
}
public void setFav(int fav) {
this.fav = fav;
}
}
public class QuotesAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<ListOfQuotes> data;
private LayoutInflater inflater;
boolean isSelected = false;
ToggleButton imgHeart;
public QuotesAdapter(Activity activity, ArrayList<ListOfQuotes> data) {
this.activity = activity;
this.data = data;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ListOfQuotes loq = data.get(position);
if(convertView == null)
{
convertView = inflater.inflate(R.layout.quotes_listview, null);
}
TextView txtQuotes = (TextView) convertView.findViewById(R.id.txtQuote);
TextView txtAuthors = (TextView) convertView.findViewById(R.id.txtAuthor);
imgHeart = (ToggleButton) convertView.findViewById(R.id.heartImage);
txtQuotes.setText(loq.getQuote());
txtAuthors.setText(loq.getAuthor());
return convertView;
}
}
public class QuotesActivity extends AppCompatActivity {
ListView quotesList;
DatabaseOpenHelper myDbHelper;
ArrayList<ListOfQuotes> arrQuotes;
QuotesAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes);
myDbHelper = new DatabaseOpenHelper(this);
try {
// check if database exists in app path, if not copy it from assets
myDbHelper.create();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
// open the database
myDbHelper.open();
myDbHelper.getWritableDatabase();
} catch (SQLException sqle) {
throw sqle;
}
arrQuotes = new ArrayList<ListOfQuotes>();
quotesList = (ListView) findViewById(R.id.quotesList);
adapter = new QuotesAdapter(QuotesActivity.this, arrQuotes);
quotesList.setAdapter(adapter);
public class ListViewActivity extends Activity
{
ListView listCustom;
private SQLiteDatabase db;
ProductDatabase customerDB;
ProductAdapter customAdapter;
static final String DATABASE_NAME = "login.db";
public static String DB_PATH;
private ArrayList<LevelList> results = new ArrayList<LevelList>();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.product_list);
levelLists = new ArrayList<LevelList>();
customerDB = new ProductDatabase(getApplicationContext());
customerDB = customerDB.open();
listCustom = (ListView) findViewById(R.id.listView1);
mainMenu();
}
public void mainMenu()
{
results.clear();
DB_PATH = "/data/data/com.gt.invoicemaker/databases/";
String myPath = DB_PATH + DATABASE_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READONLY);
final Cursor c = db.rawQuery("SELECT ID AS _id, USERID, INAME, IPRICE FROM ITEM, null);
// Note: Master is the one table in External db. Here we trying to access the records of table from external db.
if (c != null ) {
if (c.moveToFirst()) {
do {
LevelList results1 = new LevelList();
int _id = c.getInt(c.getColumnIndex("_id"));
String userName = c.getString(c.getColumnIndex("INAME"));
results1.id = _id;
results1.item = userName;
results.add(results1);
}while (c.moveToNext());
}
}
customAdapter = new ProductAdapter(getApplicationContext(), results);
listCustom.setAdapter(customAdapter);
}
}
}
public class ProductAdapter extends BaseAdapter {
private Context mContext;
private List<LevelList> listItem;
public ProductAdapter(Context c,List<LevelList> listItem) {
mContext = c;
this.listItem = listItem;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return listItem.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listItem;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView=inflater.inflate(R.layout.singleproduct, null,true);
TextView textView = (TextView) rowView.findViewById(R.id.single_product);
textView.setText(listItem.get(position).item);
return rowView;
}
}
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
@Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(ProductDatabase.DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
@Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
// Create a new one.
onCreate(_db);
}
}
将
自定义列表视图
与基本适配器一起使用
。是的,已将自定义列表视图与基本适配器一起使用,我只是不知道如何显示它[已编辑我的帖子]@HendraSetiawan--看起来你已经完成了80%的编码!这里发生了什么问题?你有没有收到任何错误,或者ListView工作不正常?我只是不知道如何使用arrayList和arrayAdapter来显示它。我只知道如何使用SimpleCrsorAdapter来显示它,但是如果我使用SimpleCrsorAdapter,我会无法编辑我的ToggleButton您已经做了:)您还想做什么?:)这段代码正常吗?您测试过了吗?