hey guys currently Im studying recyclerview and sqlite on how to fetch data from sqlite then show it to recyclerview. I made it working but Im not confident that it is the right way. here is my code.
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Toolbar mToolBar;
private NavigationView mDrawer;
private ActionBarDrawerToggle mdrawerToggle;
private DrawerLayout mDrawerLayout;
private Button alarmButton;
private AlarmManager alarmManager;
private PendingIntent sender;
private RecyclerView listReminder;
private RemindersAdapter adapter;
List<ListInfo> data;
ListInfo infoData;
Button addReminderBtn;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_PROGRESS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initDrawer();
initView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mdrawerToggle.onConfigurationChanged(newConfig);
}
public void initDrawer(){
mToolBar = (Toolbar) findViewById(R.id.app_bar);
mDrawer = (NavigationView) findViewById(R.id.main_drawer);
setSupportActionBar(mToolBar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mdrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
mToolBar,
R.string.drawer_open,
R.string.drawer_close);
mDrawerLayout.setDrawerListener(mdrawerToggle);
// indicator based on whether the drawerlayout is in open or closed
mdrawerToggle.syncState();
}
public void initView(){
listReminder = (RecyclerView) findViewById(R.id.listData);
dbHandler = new MyDBHandler(this);
adapter = new RemindersAdapter(this, dbHandler.getAllData_a());
listReminder.setAdapter(adapter);
listReminder.setLayoutManager(new LinearLayoutManager(this));
addReminderBtn = (Button) findViewById(R.id.addBtn);
addReminderBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.addBtn:
Intent addReminder = new Intent(this, AddReminderActivity.class);
startActivity(addReminder);
break;
}
}
}
MyDBHandler.java
public class MyDBHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 6;
private static final String DATABASE_NAME = "paroah.db";
public static final String TABLE_REMINDER = "reminders";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TITLE_REMINDER = "title";
public static final String COLUMN_DESC_REMINDER = "desc";
public static final String COLUMN_DATE_REMINDER = "date_created";
public MyDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = " CREATE TABLE "
+TABLE_REMINDER+ "(" +
COLUMN_ID +" INTEGER PRIMARY KEY AUTOINCREMENT,"+
COLUMN_TITLE_REMINDER + " TEXT ,"+
COLUMN_DESC_REMINDER + " TEXT ,"+
COLUMN_DATE_REMINDER + " TEXT "+
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// db.execSQL("DROP TABLE IF EXIST " + TABLE_REMINDER); // onCreate(db);
Log.d("aoi", "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
try {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_REMINDER);
onCreate(db);
} catch (SQLException e) {
Log.d("aoi", "getting exception "
+ e.getLocalizedMessage().toString());
}
}
public void addReminder(ListInfo reminder ){
ContentValues values = new ContentValues();
values.put(COLUMN_TITLE_REMINDER, reminder.getTitle());
values.put(COLUMN_DESC_REMINDER, reminder.getDesc());
values.put(COLUMN_DATE_REMINDER, reminder.getDate());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_REMINDER, null, values);
db.close();
}
public void printDatabase(){
SQLiteDatabase db = getWritableDatabase();
}
public List<ListInfo> getAllData_a(){
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM "+TABLE_REMINDER;
Cursor cursor=db.rawQuery(query, null);
List<ListInfo> data=new ArrayList<>();
while (cursor.moveToNext()){
int _id=cursor.getInt(cursor.getColumnIndex(COLUMN_ID));
String title = cursor.getString(cursor.getColumnIndex(COLUMN_TITLE_REMINDER));
String desc = cursor.getString(cursor.getColumnIndex(COLUMN_DESC_REMINDER));
String date = cursor.getString(cursor.getColumnIndex(COLUMN_DATE_REMINDER));
ListInfo current = new ListInfo();
current.set_id(_id);
current.title = title;
current.desc = desc;
current.date = date;
data.add(current);
}
return data;
}
}
RemindersAdapter.java
public class RemindersAdapter extends RecyclerView.Adapter<RemindersAdapter.ItemViewHolder> {
private final LayoutInflater inflater;
List<ListInfo> data = Collections.emptyList();
public RemindersAdapter(Context context, List<ListInfo> data){
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.reminder_item, parent, false);
ItemViewHolder holder = new ItemViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
ListInfo current = data.get(position);
holder.title.setText(current.title);
}
#Override
public int getItemCount() {
return data.size();
}
class ItemViewHolder extends RecyclerView.ViewHolder{
TextView title;
public ItemViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.reminderTitle);
}
}
}
is there any other way to make this code clean? What I need are the concepts and examples if you do have, or what I need to learn to make it clean. TIA!!
Related
Whenever I run the code application crashes after instantiating the helper class. I am new at this and can't figure out the error.
My contract class
public final class PetContract {
private PetContract(){}
public static class PetEntry implements BaseColumns{
public static final String TABLE_NAME = "pets";
public static final String _ID = BaseColumns._ID;
public static final String COLUMN_NAME = "name";
public static final String COLUMN_BREED = "breed";
public static final String COLUMN_GENDER = "gender";
public static final String COLUMN_WEIGHT = "weight";
// constants for gender
public static final int GENDER_UNKNOWN = 0;
public static final int GENDER_MALE = 1;
public static final int GENDER_FEMALE = 2;
}
}
My SQLiteHelperClass
public class PetDbHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "pets.db";
public static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + PetEntry.TABLE_NAME + " ( "
+ PetEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ PetEntry.COLUMN_NAME + " TEXT NOT NULL, "
+ PetEntry.COLUMN_BREED + " TEXT NOT NULL, "
+ PetEntry.COLUMN_GENDER + " INTEGER NOT NULL, "
+ PetEntry.COLUMN_WEIGHT + " FLOAT NOT NULL "
+ ")";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + PetEntry.TABLE_NAME;
public PetDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
onCreate(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Main activity
public class CatalogActivity extends AppCompatActivity {
PetDbHelper mDbHelper = new PetDbHelper(this);
public void insertDummyData(){
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
String name = "DOG";
String breed = "dkdsbk";
float weight = (float) 55.5;
values.put(PetEntry.COLUMN_NAME,name);
values.put(PetEntry.COLUMN_BREED, breed);
values.put(PetEntry.COLUMN_GENDER,PetEntry.GENDER_MALE);
values.put(PetEntry.COLUMN_WEIGHT,weight);
long newRowId = db.insert(PetEntry.TABLE_NAME,null,values);
}
public Cursor displayRowCount(){
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {PetEntry._ID};
String selection = PetEntry.TABLE_NAME;
return db.query(PetEntry.TABLE_NAME,projection,null,null,null,null,null);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(CatalogActivity.this,EditorialActivity.class );
startActivity(intent);
}
});
Cursor c = displayRowCount();
TextView view = (TextView) findViewById(R.id.text);
view.setText("The row count is" + c.getCount());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_catalog, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch (id){
case R.id.delete_all_the_pets:
break;
case R.id.insert_dummy_data:
insertDummyData();
break;
}
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
onCreate(db);
}
this is A recursive function!!
don't call onCreate Inside onCreate
I have implemented a recyclerView and a SQLite database to save/retrieve data for the recylerview, but the data I get on the recyclerView is not the data that should show. The recyclerView worked as it should without the SQLite db.
When the plus sign is clicked, a dialog will popup with editext fields, where the user can type the information:
Here is the DialogFragment class where the user shall write their information:
public class DialogAdd extends DialogFragment {
private Button okButton;
private EditText name, quantity, location, normalPrice, offerPrice;
private List<ShopListItem> shopListItem;
private Context context;
DatabaseHelper dbHelper;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbHelper = new DatabaseHelper(getContext());
shopListItem = new ArrayList<>();
context = getActivity();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.add_productdialog,container, false);
getDialog().setCanceledOnTouchOutside(false);
getDialog().setTitle("Add to shoplist");
name = (EditText) rootView.findViewById(R.id.dialog_productname);
quantity = (EditText) rootView.findViewById(R.id.dialog_qantity);
location = (EditText) rootView.findViewById(R.id.dialog_location);
normalPrice = (EditText) rootView.findViewById(R.id.dialog_normalPrice);
offerPrice = (EditText) rootView.findViewById(R.id.dialog_offerPrice);
okButton = (Button) rootView.findViewById(R.id.dialog_okButton);
okButton.getBackground().setColorFilter(Color.parseColor("#2fbd4b"), PorterDuff.Mode.MULTIPLY);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (name.getText().toString().isEmpty()) {
Toast.makeText(context, "You must add a name", Toast.LENGTH_LONG).show();
} else {
dbHelper.insertData(name.toString() ,quantity.toString(),location.toString(),normalPrice.toString(),offerPrice.toString());
getDialog().dismiss();
}
}
});
return rootView;
}
This is the mainActivity class where I create the recylerview, adapters and Database:
public class MainActivity extends AppCompatActivity{
private ImageButton addbutton;
private DialogAdd dialogAdd;
public static RecyclerView recyclerView;
private List<ShopListItem> shopListItems;
private SQLiteDatabase db;
private Cursor cursor;
private DatabaseHelper databaseHelper;
private ShoplistAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shoppinglist_mainactivity);
databaseHelper = new DatabaseHelper(this);
addbutton = (ImageButton) findViewById(R.id.addbtn);
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogAdd = new DialogAdd();
dialogAdd.show(getSupportFragmentManager(), "addDialog");
}
});
//RecyclerView
recyclerView = (RecyclerView)findViewById(R.id.rv_shoppinglist);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(App.getAppContex());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
initializeData();
adapter = new ShoplistAdapter(shopListItems);
recyclerView.setAdapter(adapter);
}
private void initializeData(){
shopListItems = new ArrayList<>();
Cursor resultset = databaseHelper.getAllData();
if (resultset.moveToFirst()){
while(!resultset.isAfterLast()){
shopListItems.add(new ShopListItem(resultset.getString(1), resultset.getString(2), resultset.getString(3), resultset.getString(4), resultset.getString(5)));
resultset.moveToNext();
}
}
resultset.close();
shopListItems.add(new ShopListItem("Potato", "2 KG", "MALL", "7 kr", ""));
}
This class is where the database is defined:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME ="dbshoplist.db";
public static final String TABLE_NAME ="product_table";
public static final String COL_ID = "ID";
public static final String COL_NAME ="NAME";
public static final String COL_QTY ="QUANTITY";
public static final String COL_LOCATION ="LOCATION";
public static final String COL_PRICE1 ="PRICE1";
public static final String COL_PRICE2 ="PRICE2";
/*
This constructor creates the database
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,QUANTITY TEXT,LOCATION TEXT,PRICE1 TEXT,PRICE2 TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String qty, String location, String price1, String price2){
SQLiteDatabase db = this.getWritableDatabase();
// content value is a row, and we fill it with the put();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
contentValues.put(COL_QTY, qty);
contentValues.put(COL_LOCATION, location);
contentValues.put(COL_PRICE1, price1);
contentValues.put(COL_PRICE2, price2);
long result = db.insert(TABLE_NAME, null,contentValues);
if(result == -1) {
return false;
}else{
return true;
}
}
public Cursor getAllData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursorResults = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return cursorResults;
}
My recyclerView adapter class:
public class ShoplistAdapter extends RecyclerView.Adapter<ShoplistAdapter.ViewHolder>{
List<ShopListItem> shopListItems;
public ShoplistAdapter(List<ShopListItem> shopListItems) {
this.shopListItems = shopListItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View shoplist_itemView = inflater.inflate(R.layout.shop_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(shoplist_itemView);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.location.setText(shopListItems.get(position).location.toString());
holder.normalPrice.setText(shopListItems.get(position).normalprice.toString());
holder.offerPrice.setText(shopListItems.get(position).offerprice.toString());
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(shopListItems.get(position).quantity + " " + shopListItems.get(position).name);
holder.productname.setText(stringBuilder);
if(!shopListItems.get(position).offerprice.toString().isEmpty()){
holder.normalPrice.setPaintFlags(holder.normalPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
if(shopListItems.get(position).normalprice.isEmpty()){
holder.normalPrice.setVisibility(View.GONE);
}
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true){
holder.productname.setPaintFlags(holder.productname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.productname.setTextColor(Color.parseColor("#40000000"));
}else{
holder.productname.setPaintFlags(0 | Paint.ANTI_ALIAS_FLAG);
holder.productname.setTextColor(Color.BLACK);
}
}
});
}
#Override
public int getItemCount() {
return shopListItems.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
private CheckBox checkBox;
private TextView productname, quantity, location, normalPrice, offerPrice;
private ImageButton edit_icon, delete_icon;
public ViewHolder(View itemView) {
super(itemView);
productname = (TextView)itemView.findViewById(R.id.product_name);
location = (TextView)itemView.findViewById(R.id.product_location);
normalPrice = (TextView)itemView.findViewById(R.id.product_price);
offerPrice = (TextView)itemView.findViewById(R.id.product_offer_price);
edit_icon = (ImageButton)itemView.findViewById(R.id.editShopItem_Icon);
delete_icon = (ImageButton)itemView.findViewById(R.id.shopitem_delete_icon);
checkBox = (CheckBox) itemView.findViewById(R.id.bought_checkbox);
}
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
This is happening because you're calling the toString() method of fields of the ShopListItem object: shopListItems.get(position).location.toString().
Instead, create getter methods for the fields of your ShopListItem class, e.g.
public getLocation() {
return location;
}
and just call these to get the data.
ANSWER
#Override
public void categoryLoadComplete(Cursor cursor) {
data = cursor;
categoryAdapter.swapCursor(cursor);
categoryAdapter.notifyDataSetChanged();
}
#Override
public void transactionLoadComplete(Cursor cursor) {
data = cursor;
categoryAdapter.swapCursor(cursor);
categoryAdapter.notifyDataSetChanged();
}
ORIGINAL POST
I've been at this for hours now and I can't seem to figure it out, but I have narrowed the problem down to the fact that my Cursor object is returning null. I can't figure out why and was hoping to enlist the help of more experienced coders on this site.
I borrowed a Database package from this tutorial on SQLite: http://partisanapps.com/2015/08/really-useful-notes-saving-and-loading-with-a-local-database-i/
I added a second table as well as added Add, Load, Delete, and Save classes for the new table.
I can confirm that there is data in the database by exporting the file and viewing it in SQLite Broweser.
I'm attempting to populate a a spinner with data from the database as you can see in AddTransaction.class
Thank you for your time.
AddTransaction.class:
public class AddTransaction extends AppCompatActivity
implements CategoryLoad.categoryLoadComplete,
TransactionLoad.LoadComplete {
Spinner currencySpinner, recurringSpinner;
EditText itemName, itemPrice, itemNote;
Time today = new Time(Time.getCurrentTimezone());
Snackbar snackbar;
private Cursor data = null;
LinearLayout transactionLayout;
SimpleCursorAdapter categoryAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_transaction);
transactionLayout = (LinearLayout) findViewById(R.id.transactionLayout);
itemName = (EditText) findViewById(R.id.itemName);
itemPrice = (EditText) findViewById(R.id.itemPrice);
itemNote = (EditText) findViewById(R.id.note);
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Add a Transaction");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
CategoryLoad categoryLoad = new CategoryLoad(this);
categoryLoad.execute();
categoryAdapter = new SimpleCursorAdapter(getBaseContext(),
android.R.layout.simple_spinner_item,
data,
new String[] {DatabaseHelper.CATEGORY_NAME},
new int[] {android.R.id.text1},
0);
final Spinner categorySpinner = (Spinner) findViewById(R.id.categorySpinner);
categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categoryAdapter.swapCursor(data);
categoryAdapter.notifyDataSetChanged();
categorySpinner.setAdapter(categoryAdapter);
currencySpinner = (Spinner) findViewById(R.id.currencySpinner);
ArrayAdapter<CharSequence> currencyAdapter = ArrayAdapter.createFromResource(this,
R.array.currency, android.R.layout.simple_spinner_item);
currencyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
currencySpinner.setAdapter(currencyAdapter);
recurringSpinner = (Spinner) findViewById(R.id.recurringSpinner);
ArrayAdapter<CharSequence> recurringAdapter = ArrayAdapter.createFromResource(this,
R.array.recurring, android.R.layout.simple_spinner_item);
recurringAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
recurringSpinner.setAdapter(recurringAdapter);
if (data == null) {
snackbar.make(transactionLayout, "Category data failed to load", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_add_category, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
itemPrice = (EditText) findViewById(R.id.itemPrice);
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.delete) {
Toast.makeText(getBaseContext(), "Transaction data lost!", Toast.LENGTH_LONG).show();
NavUtils.navigateUpFromSameTask(this);
return true;
}
if (id == R.id.save) {
if (TextUtils.isEmpty(itemPrice.getText().toString())) {
snackbar.make(transactionLayout, "Please input a price.", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
} else {
today.setToNow();
TransactionAdd transactionAdd = new TransactionAdd(this);
transactionAdd.execute(
itemName.getText().toString(),
itemPrice.getText().toString(),
// categorySpinner.getSelectedItem().toString(),
null,
currencySpinner.getSelectedItem().toString(),
recurringSpinner.getSelectedItem().toString(),
itemNote.getText().toString(),
today.format("%Y-%m-%d %H:%M:%S")
);
Toast.makeText(getBaseContext(), "Transaction added!", Toast.LENGTH_LONG).show();
NavUtils.navigateUpFromSameTask(this);
}
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void categoryLoadComplete(Cursor cursor) {
data = cursor;
}
#Override
public void transactionLoadComplete(Cursor cursor) {
}
}
CategoryLoad:
public class CategoryLoad extends AsyncTask<Void, Void, Cursor> {
private static final String TAG = "LoadTask";
private categoryLoadComplete loadComplete;
private WeakReference<Context> categoryWeakReference;
private DatabaseHelper db;
public interface categoryLoadComplete {
void categoryLoadComplete(Cursor cursor);
}
public CategoryLoad(Context context) {
categoryWeakReference = new WeakReference<>(context);
db = DatabaseHelper.getInstance(categoryWeakReference.get());
try {
loadComplete = (categoryLoadComplete) categoryWeakReference.get();
} catch (ClassCastException e) {
Log.e(TAG, context.toString() + " must implement LoadComplete");
}
}
#Override
protected Cursor doInBackground(Void... params) {
Cursor result = db.getReadableDatabase().query(
DatabaseHelper.CATEGORIES_TABLE,
null, null, null, null, null, DatabaseHelper.CATEGORY_KEY_ID);
result.getCount();
return result;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(Cursor cursor) {
loadComplete.categoryLoadComplete(cursor);
}
}
TransactionLoad:
public class TransactionLoad extends AsyncTask<Void, Void, Cursor> {
private static final String TAG = "LoadTask";
private LoadComplete loadComplete;
private WeakReference<Context> transactionWeakReference;
private DatabaseHelper tt;
public interface LoadComplete {
void transactionLoadComplete(Cursor cursor);
}
public TransactionLoad(Context context) {
transactionWeakReference = new WeakReference<>(context);
tt = DatabaseHelper.getInstance(transactionWeakReference.get());
try {
loadComplete = (LoadComplete) transactionWeakReference.get();
} catch (ClassCastException e) {
Log.e(TAG, context.toString() + " must implement LoadComplete");
}
}
#Override
protected Cursor doInBackground(Void... params) {
Cursor result = tt.getReadableDatabase().query(
DatabaseHelper.TRANSACTIONS_TABLE,
null, null, null, null, null, DatabaseHelper.TRANSACTION_KEY_ID);
result.getCount();
return result;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(Cursor cursor) {
loadComplete.transactionLoadComplete(cursor);
}
}
DatabaseHelper:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "budgets.db";
private static final int SCHEMA = 1;
public static final String KEY_ID = "_id";
// ~~~~~~~~~~~~~~~~~~~Categories~~~~~~~~~~~~~~~~~~~~~~~~~~~
public static final String CATEGORIES_TABLE = "categories";
// ~~~~~~~~~~~~~~~~~~~~~Columns~~~~~~~~~~~~~~~~~~~~~~~~~~~
public static final String CATEGORY_KEY_ID = "_id_cat";
public static final String CATEGORY_NAME = "cat_name";
public static final String CATEGORY_AMOUNT = "cat_amount";
public static final String CATEGORY_CURRENCY = "cat_currency";
public static final String CATEGORY_FREQUENCY = "cat_frequency";
public static final String CATEGORY_DURATION_VALUE = "cat_duration_value";
public static final String CATEGORY_DURATION_MODIFIER = "cat_duration_modifier";
public static final String CATEGORY_OVERAGE = "cat_overage";
public static final String CATEGORY_SURPLUS = "cat_surplus";
public static final String CATEGORY_DATE = "cat_date";
// ~~~~~~~~~~~~~~~~~~~Transactions~~~~~~~~~~~~~~~~~~~~~~~~~~~
public static final String TRANSACTIONS_TABLE = "transactions";
// ~~~~~~~~~~~~~~~~~~~~~Columns~~~~~~~~~~~~~~~~~~~~~~~~~~~
public static final String TRANSACTION_KEY_ID = "_id_trans";
public static final String TRANSACTION_NAME = "trans_name";
public static final String TRANSACTION_PRICE = "trans_price";
public static final String TRANSACTION_CATEGORY = "trans_category";
public static final String TRANSACTION_CURRENCY = "trans_currency";
public static final String TRANSACTION_RECURRING = "trans_recurring";
public static final String TRANSACTION_NOTES = "trans_notes";
public static final String TRANSACTION_DATE = "trans_date";
private static DatabaseHelper mInstance = null;
public static synchronized DatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new DatabaseHelper(context.getApplicationContext());
}
return mInstance;
}
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA);
}
public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,
int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE categories (_id_cat INTEGER PRIMARY KEY AUTOINCREMENT, " +
"cat_name TEXT, cat_amount TEXT, cat_currency TEXT, cat_frequency TEXT," +
"cat_duration_value TEXT, cat_duration_modifier TEXT, cat_overage TEXT, " +
"cat_surplus TEXT, cat_date TEXT);");
db.execSQL("CREATE TABLE transactions (_id_trans INTEGER PRIMARY KEY AUTOINCREMENT, " +
"trans_name TEXT, trans_price TEXT, trans_category TEXT, trans_currency TEXT, " +
"trans_recurring TEXT, trans_notes TEXT, trans_date TEXT, " +
"FOREIGN KEY(trans_category) REFERENCES categories(cat_name));");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
int upgradeTo = oldVersion + 1;
while (upgradeTo <= newVersion) {
switch (upgradeTo) {
case 2:
break;
}
upgradeTo++;
}
}
}
You need to set the cursor on the adapter in your categoryLoadComplete() and transactionLoadComplete() methods, and then call adapter.notifyDataSetChanged().
Your cursor is null because it has not been assigned by the time you pass if off you your adapter. Try not creating your adapter until "categoryLoadComplete".
#Override
public void categoryLoadComplete(Cursor cursor) {
data = cursor;
categoryAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
data,
new String[] {DatabaseHelper.CATEGORY_NAME},
new int[] {android.R.id.text1},
0);
categorySpinner.setAdapter(categoryAdapter);
}
I have one RecyclerView and my method in RecyclerView adapter is working, but only for position i select and for example, when i click image with sign X i'm deleting first item which i positioned in remove method, but i want this to happens when user click image with sign X, to give him ability to select what item from the list he will delete.
Also i would like to delete that item from SQLite, but my method isn't good probably in helper class.
Here is MainActivity:
public class MainActivity extends AppCompatActivity {
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
GridAdapter mGridAdapter;
DBHelper dbh;
String firstName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
initAddImage();
dbh = new DBHelper(this);
initRecyclerView();
initDeleteImage();
}
public List<Birthday> getData() {
List<Birthday> birthdays = new ArrayList<>();
Birthday birthday = null;
Cursor c = dbh.getBirthdayData();
if (c != null) {
while (c.moveToNext()) {
int nameIndex = c.getColumnIndex(dbh.BIRTHDAY_NAME);
String nameText = c.getString(nameIndex);
this.firstName = nameText;
int lastNameIndex = c.getColumnIndex(dbh.BIRTHDAY_LAST_NAME);
String lastNameText = c.getString(lastNameIndex);
birthday = new Birthday();
birthday.setNAME(nameText);
birthday.setLAST_NAME(lastNameText);
birthdays.add(birthday);
}
}
return birthdays;
}
private void initRecyclerView(){
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setItemAnimator(new ScaleInAnimator());
// The number of Columns
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new GridLayoutManager(this, 3);
mRecyclerView.setLayoutManager(mLayoutManager);
mGridAdapter = new GridAdapter(getData());
mRecyclerView.setAdapter(mGridAdapter);
}
private void initAddImage(){
ImageView addImage = (ImageView) findViewById(R.id.add_image);
addImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddBirthday.class);
startActivity(intent);
}
});
}
private void initDeleteImage(){
ImageView deleteImage = (ImageView) findViewById(R.id.delete_image);
deleteImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mGridAdapter.removeItem(0);
}
});
}
#Override
protected void onResume() {
super.onResume();
initRecyclerView();
}
}
Here is my RecyclerView Adapter:
public class GridAdapter extends RecyclerView.Adapter<GridAdapter.MyViewHolder> {
private List<Birthday> birthdays;
DBHelper dbh;
public GridAdapter(List<Birthday> birthdays){
this.birthdays = birthdays;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
CustomTextView firstName, lastName;
TextView dateOfBirthday;
public MyViewHolder(View itemView) {
super(itemView);
firstName = (CustomTextView) itemView.findViewById(R.id.first_name);
lastName = (CustomTextView) itemView.findViewById(R.id.last_name);
dateOfBirthday = (TextView) itemView.findViewById(R.id.date_of_birthday);
}
}
public void removeItem(int position) {
birthdays.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_item, parent, false);
MyViewHolder holder = new MyViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.firstName.setText(birthdays.get(position).getNAME());
holder.lastName.setText(birthdays.get(position).getLAST_NAME());
}
#Override
public int getItemCount() {
return birthdays.size();
}
}
And here is my Database: Method for deleting item is at the bottom of class
public class DBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "_database";
private static final String BIRTHDAY_TABLE_NAME = "birthday_table";
public static final String BIRTHDAY_ID = "birthday_id";
public static final String BIRTHDAY_NAME = "birthday_name";
public static final String BIRTHDAY_LAST_NAME = "birthday_last_name";
private static final String CREATE_BIRTHDAY_TABLE = "CREATE TABLE " + BIRTHDAY_TABLE_NAME +
" ( " + BIRTHDAY_ID + " INTEGER PRIMARY KEY,"
+ BIRTHDAY_NAME + " TEXT," + BIRTHDAY_LAST_NAME + " TEXT );";
SQLiteDatabase database;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BIRTHDAY_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + BIRTHDAY_TABLE_NAME);
onCreate(db);
}
public void setBirthdayData(String birthdayName, String birthdayLastName) {
database = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(BIRTHDAY_NAME, birthdayName);
cv.put(BIRTHDAY_LAST_NAME, birthdayLastName);
database.insert(BIRTHDAY_TABLE_NAME, null, cv);
}
public Cursor getBirthdayData() {
database = getReadableDatabase();
String[] columns = {BIRTHDAY_ID, BIRTHDAY_NAME, BIRTHDAY_LAST_NAME};
Cursor c = database.query(BIRTHDAY_TABLE_NAME, columns, null, null, null, null, BIRTHDAY_ID + " DESC");
return c;
}
public Cursor getBirthdayName(String[] args) {
database = getReadableDatabase();
String query = "SELECT " + BIRTHDAY_NAME + " FROM " + BIRTHDAY_TABLE_NAME + " WHERE " + BIRTHDAY_NAME + " =?";
Cursor c = database.rawQuery(query, args);
return c;
}
public boolean deleteItem(long rowId) {
SQLiteDatabase db = getWritableDatabase();
return db.delete(BIRTHDAY_TABLE_NAME, BIRTHDAY_ID + "=" + rowId, null) > 0;
}
}
Assume your X sign is an ImageButton
Add the ImageButton in your grid_item.xml
In your MyViewHolder add ImageView as item named deleteItem
In OnBindViewHolder
`holder.deleteItem.setOnclickListener(new OnClickListener(){
#Override
public void onClick(View v){
dbHelper.deleteItem(birthdays.get(position).getItemId); /* you pass birthday id to a method deleteItem() in your DBHelper.java */
birthdays.remove(position);
GridAdapter.this.notifyDataSetChanged();
});`
deleteItem(long birthdayId) method
deleteItem(long birthdayId){
return database.delete(BIRTHDAY_TABLE_NAME, BIRTHDAY_ID + " = '" + birthdayId +"'", null, null, null, null);
}
I have a list for that i want to add search function using search view. i have sqlite database and two fragments in which i am adding products and in another i am displaying the products in list view. i want to filter this list. how can i achieve this? i have searched many links but by searching all i have got confused..I am new to android so plz anyone can help? your help will be appretiated.. thnk u..
this is my main activity
public class MainActivity extends AppCompatActivity implements android.support.v7.widget.SearchView.OnQueryTextListener{
Toolbar mToolbar;
public DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FrameLayout mContentFrame;
FragmentManager fragmentManager;
private static final String PREFERENCES_FILE = "mymaterialapp_settings";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private int mCurrentSelectedPosition;
public ArrayList<Item> arrayList;
public DBHandler db;
ArrayList<Item> array_data;
public SearchView searchView;
ListView listview;
public ArrayAdapter<Item> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
setUpToolbar();
arrayList=new ArrayList<Item>();
array_data=new ArrayList<Item>();
db = new DBHandler(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.nav_drawer);
mUserLearnedDrawer = Boolean.valueOf(readSharedSetting(this, PREF_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
firstTimeFrag();
setUpNavDrawer();
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mContentFrame = (FrameLayout) findViewById(R.id.nav_contentframe);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
Fragment newFragment;
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
menuItem.setChecked(true);
switch (menuItem.getItemId()) {
case R.id.navigation_item_1:
newFragment = new AddStock();
transaction.replace(R.id.nav_contentframe, newFragment);
// transaction.addToBackStack(null);
transaction.commit();
mCurrentSelectedPosition = 0;
mDrawerLayout.closeDrawers();
return true;
case R.id.navigation_item_2:
newFragment = new ViewStock();
transaction.replace(R.id.nav_contentframe, newFragment);
// transaction.addToBackStack(null);
transaction.commit();
mCurrentSelectedPosition = 1;
mDrawerLayout.closeDrawers();
return true;
default:
return true;
}
}
});
//fragmentManager.beginTransaction().replace(R.id.nav_contentframe, fragment).commit();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION, 0);
Menu menu = mNavigationView.getMenu();
menu.getItem(mCurrentSelectedPosition).setChecked(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(this,R.menu.menu_main);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
case R.id.search_view:
return true;
}
return super.onOptionsItemSelected(item);
}
private void setUpToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
}
}
private void setUpNavDrawer() {
if (mToolbar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setNavigationIcon(R.drawable.ic_drawer);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
if (!mUserLearnedDrawer) {
mDrawerLayout.openDrawer(GravityCompat.START);
mUserLearnedDrawer = true;
saveSharedSetting(this, PREF_USER_LEARNED_DRAWER, "true");
}
}
public static void saveSharedSetting(Context ctx, String settingName, String settingValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(settingName, settingValue);
editor.apply();
}
public static String readSharedSetting(Context ctx, String settingName, String defaultValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPref.getString(settingName, defaultValue);
}
private void firstTimeFrag(){
Fragment fr = new ViewStock();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.nav_contentframe, fr);
fragmentTransaction.commit();
}
}
this is my item class
public class Item {
public int id;
public String item_name;
public String item_desc;
public String item_qty;
public Item(){}
public Item(int id ,String item_name,String item_desc,String item_qty) {
super();
this.item_name = item_name;
this.item_desc = item_desc;
this.item_qty = item_qty;
}
public Item(String item_name,String item_desc, String item_qty){
this.item_name = item_name;
this.item_desc=item_desc;
this.item_qty = item_qty;
}
public int getID(){
return id;
}
public void setID(int id){
this.id= id;
}
public String getItem_name(){
return item_name;
}
public void setItem_name(String item_name)
{
this.item_name=item_name;
}
public String getItem_desc()
{
return item_desc;
}
public void setItem_desc(String item_desc)
{
this.item_desc=item_desc;
}
public String getItem_qty()
{
return item_qty;
}
public void setItem_qty(String item_qty) {
this.item_qty = item_qty;
}
}
this is my ItemAdapter
public class ItemAdapter extends ArrayAdapter<Item> implements Filterable {
Context context;
// ValueFilter valueFilter;
ArrayList<Item> mStringFilterList;
ArrayList<Item> items;
public ItemAdapter(Context context, int resourceId,
ArrayList<Item> items) {
super(context, resourceId, items);
this.context = context;
this.items=items;
mStringFilterList=items;
}
public int getCount() {
return items.size();
}
public Item getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Item rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_item, null);
holder.txtItemName = (TextView) convertView.findViewById(R.id.txt_item_name);
holder.txtItemDesc = (TextView) convertView.findViewById(R.id.txt_item_desc);
holder.txtItemQty = (TextView) convertView.findViewById(R.id.txt_item_qty);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtItemName.setText(rowItem.getItem_name());
holder.txtItemDesc.setText(rowItem.getItem_desc());
holder.txtItemQty.setText(rowItem.getItem_qty());
return convertView;
}
private class ViewHolder {
TextView txtItemName;
TextView txtItemDesc;
TextView txtItemQty;
}
}
this is my view stock fragment
public class ViewStock extends Fragment {
public ViewStock() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.fragment_view_stock, container, false);
MainActivity act = (MainActivity) this.getActivity();
act.listview = (ListView)rootview.findViewById(R.id.list);
act.listview.setTextFilterEnabled(true);
act.array_data = new ArrayList<Item>();
// Context mCtx = getActivity().getApplicationContext();
// ItemAdapter adapter = new ItemAdapter(getActivity(), R.layout.list_item, act.arrayList);
// listview.setAdapter(adapter);
act.db = new DBHandler(getActivity());
ArrayList<Item> item_array_from_db = act.db.Get_items();
for (int i = 0; i < item_array_from_db.size(); i++) {
int idno = item_array_from_db.get(i).getID();
String name = item_array_from_db.get(i).getItem_name();
String desc = item_array_from_db.get(i).getItem_desc();
String qty = item_array_from_db.get(i).getItem_qty();
Item cnt = new Item();
cnt.setID(idno);
cnt.setItem_name(name);
cnt.setItem_desc(desc);
cnt.setItem_qty(qty);
act.array_data.add(cnt);
}
act.db.close();
act.adapter = new ItemAdapter(getActivity(), R.layout.list_item,
act.array_data);
act.listview.setAdapter(act.adapter);
act.adapter.notifyDataSetChanged();
return rootview;
}
}
this is my database
public class DBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "stock";
private static final String TABLE_ITEMS = "items";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "itemname";
private static final String KEY_DESC = "itemdesc";
private static final String KEY_QTY = "itemqty";
private final ArrayList<Item> array_list = new ArrayList<Item>();
public DBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_DESC + " TEXT," + KEY_QTY + " INTEGER" + ")";
db.execSQL(CREATE_ITEMS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);
onCreate(db);
}
public void Add_Item(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.getItem_name());
values.put(KEY_DESC, item.getItem_desc());
values.put(KEY_QTY, item.getItem_qty());
db.insert(TABLE_ITEMS, null, values);
db.close();
}
Item Get_Item(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID,
KEY_NAME, KEY_DESC, KEY_QTY }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Item item = new Item(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3));
cursor.close();
db.close();
return item;
}
public ArrayList<Item> Get_items() {
try {
array_list.clear();
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.setID(Integer.parseInt(cursor.getString(0)));
item.setItem_name(cursor.getString(1));
item.setItem_desc(cursor.getString(2));
item.setItem_qty(cursor.getString(3));
array_list.add(item);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return array_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return array_list;
}
}
this is my view stock layout
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="com.example.owner.stock.ViewStock">
<!-- TODO: Update blank fragment layout -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:id="#+id/header"
android:weightSum="1"
android:background="#ff45f3ff">
<TextView
android:id="#+id/lbl_item_name"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="#string/txt_item_name"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold"
android:layout_weight="0.33" />
<TextView
android:id="#+id/lbl_item_desc"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="#string/txt_item_desc"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold"
android:layout_weight="0.33" />
<TextView
android:id="#+id/lbl_item_qty"
android:layout_width="100dp"
android:layout_height="match_parent"
android:text="#string/txt_item_qty"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold"
android:layout_weight="0.33" />
</LinearLayout>
<ListView
android:layout_width="wrap_content"
android:layout_height="462dp"
android:id="#+id/list"
android:layout_gravity="center"
android:background="#android:color/background_light"
/>
</FrameLayout>
plz can anyone help me out for this?? I need to know can we use filter class for sqlite? and i have a fragment in that i have my list so how the search activity will be called??
You can use Filter instance from the ArrayAdapter to filter the items.
Your code can be like this-
mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
mAdapter.getFilter().filter(mCurFilter);
and can be fired from the
public boolean onQueryTextChange(String newText)
Method of implemented SerachView.
For the detail you can have a look on the API Demo.
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<Item> filterList = new ArrayList<Item>();
for (int i = 0; i < mStringFilterList.size(); i++) {
if ( (mStringFilterList.get(i).getItem_name())
.contains(constraint.toString())) {
Item item = new Item(mStringFilterList.get(i)
.getItem_name() , mStringFilterList.get(i)
.getItem_desc() , mStringFilterList.get(i)
.getItem_qty());
filterList.add(item);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
}
return results;
}
#Override
public void publishResults(CharSequence constraint,
FilterResults results) {
items = (ArrayList<Item>) results.values;
notifyDataSetChanged();
}
}
this is my filter