RecyclerView not displaying ArrayList correctly - java

For some reason the only thing displayed in my RecyclerView is com.stu54259.plan2cook.Model.Shopping_list#5cb7482 repeated with various end codes not the contents of the ArrayList. Any suggestions must be something with the recylerview adapter. Can add xml etc if need be but i'm sure I've just missed something stupid.
Shopping_List class
package com.stu54259.plan2cook.Model;
public class Shopping_List {
private int id;
private String ingredient_type;
private String ingredient_name;
private Double quantity;
private String measurement_name;
public Shopping_List() {
}
public Shopping_List(String ingredient_type, String ingredient_name, Double quantity, String measurement_name) {
this.ingredient_type = ingredient_type;
this.ingredient_name = ingredient_name;
this.quantity = quantity;
this.measurement_name = measurement_name;
}
public Shopping_List(int id, String ingredient_type, String ingredient_name, Double quantity, String measurement_name) {
this.id = id;
this.ingredient_type = ingredient_type;
this.ingredient_name = ingredient_name;
this.quantity = quantity;
this.measurement_name = measurement_name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIngredient_type() {
return ingredient_type;
}
public void setIngredient_type(String ingredient_type) {
this.ingredient_type = ingredient_type;
}
public String getIngredient_name() {
return ingredient_name;
}
public void setIngredient_name(String ingredient_name) {
this.ingredient_name = ingredient_name;
}
public Double getQuantity() {
return quantity;
}
public void setQuantity(Double quantity) {
this.quantity = quantity;
}
public String getMeasurement_name() {
return measurement_name;
}
public void setMeasurement_name(String measurement_name) {
this.measurement_name = measurement_name;
}
}
Activity
public class ShoppingList extends MainActivity {
ShoppingListAdapter adapterRecipe;
List<Shopping_List> shopList = new ArrayList<>();
RecyclerView listIngredient;
SQLiteDatabase db;
Cursor c;
EditText edittext;
String search;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shopping_list);
edittext = findViewById(R.id.editPlanName);
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
search = edittext.getText().toString();
Log.d("Search value", search);
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
loadIngredient();
adapterRecipe.notifyDataSetChanged();
return true;
}
return false;
}
});
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent a = new Intent(ShoppingList.this,MainActivity.class);
startActivity(a);
break;
case R.id.recipes:
Intent b = new Intent(ShoppingList.this,RecipeSearch.class);
startActivity(b);
break;
case R.id.shoppingList:
Intent c = new Intent(ShoppingList.this, ShoppingList.class);
startActivity(c);
break;
case R.id.mealPlan:
Intent d = new Intent(ShoppingList.this, MenuPlan.class);
startActivity(d);
break;
case R.id.reminder:
Intent e = new Intent(ShoppingList.this, Reminders.class);
startActivity(e);
break;
}
return false;
}
});
adapterRecipe = new ShoppingListAdapter(this, shopList);
listIngredient = findViewById(R.id.listIngredient);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
listIngredient.setLayoutManager(mLayoutManager);
listIngredient.setItemAnimator(new DefaultItemAnimator());
listIngredient.setAdapter(adapterRecipe);
}
public void loadIngredient() {
shopList.clear();
db = (new DatabaseManager(this).getWritableDatabase());
String RECIPE_SEARCH =
"SELECT SUM(A.ingredient_quantity) quantity, A.ingredient ingredient_name, A.recipe, B.ingredient_type, B.measurement_name, C.id, D.plan_name " +
"FROM " + DatabaseManager.TABLE_QUANTITY + " AS A JOIN " + DatabaseManager.TABLE_INGREDIENTS + " AS B ON A.ingredient = B.ingredient_name " +
"JOIN " + DatabaseManager.TABLE_PLAN_RECIPES + " AS C ON A.recipe = C.recipe_name " +
"JOIN " + DatabaseManager.TABLE_MEAL_PLAN + " AS D ON C.id = D.plan_recipe " +
"WHERE D.plan_name LIKE ? GROUP BY A.ingredient";
Log.d("Search query", RECIPE_SEARCH);
c = db.rawQuery(RECIPE_SEARCH, new String[]{"%" + search + "%"});
if (c.moveToFirst()) {
do {
Shopping_List shopping_list = new Shopping_List();
shopping_list.setQuantity(c.getDouble(c.getColumnIndex("quantity")));
shopping_list.setIngredient_name(c.getString(c.getColumnIndex("ingredient_name")));
shopping_list.setIngredient_type(c.getString(c.getColumnIndex("ingredient_type")));
shopping_list.setMeasurement_name(c.getString(c.getColumnIndex("measurement_name")));
shopList.add(shopping_list);
} while (c.moveToNext());
}
c.close();
db.close();
}
}
Adapter
public class ShoppingListAdapter extends RecyclerView.Adapter<com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder> {
private List<Shopping_List> shopList;
private LayoutInflater mInflater;
private com.stu54259.plan2cook.Adapters.RecyclerViewAdapter.ItemClickListener mClickListener;
// data is passed into the constructor
public ShoppingListAdapter(Context context, List<Shopping_List> data) {
this.mInflater = LayoutInflater.from(context);
this.shopList = data;
}
// inflates the row layout from xml when needed
#Override
public com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.fragment_item, parent, false);
return new com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder(view);
}
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder holder, int position) {
if(shopList.get(position) != null)
{
holder.myTextView.setText(shopList.get(position).toString());
}
}
// total number of rows
#Override
public int getItemCount() {
return shopList.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.quantity);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// allows clicks events to be caught
void setClickListener(com.stu54259.plan2cook.Adapters.RecyclerViewAdapter.ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}

Add this method in your Shopping_List class, so when you use toString() for a Shopping_List instance you will get all its properties separated by spaces:
public String toString() {
return ingredient_name + " " + ingredient_type + " " + quantity + " " + measurement_name;
}
You can change the order of the properties.

You have wrong code in onBindViewHolder method. You should set text with some field from Shopping_List object:
#Override
public void onBindViewHolder(com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder holder, int position) {
if(shopList.get(position) != null)
{
holder.myTextView.setText(shopList.get(position).toString());
}
}
You haven't put the Shopping_List object here, but if you have something like this:
public class Shopping_List {
public String title;
public String getTitle() {
return title;
}
}
Then you should do something like this:
#Override
public void onBindViewHolder(com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder holder, int position) {
if(shopList.get(position) != null)
{
holder.myTextView.setText(shopList.get(position).getTitle());
}
}

Although it doesn't give a direct solution, I would suggest that you use the groupie library. It will most likely remove your error and reduce boilerplate code and complexity.

Related

How can I save a list within a list using the room persistence library? (android & Java)

how are you, I hope everyone is fine
I have created an application to generate a sales invoice.
In SalesInvoiceActivity, when the user clicks on the FloatingActionButton, it goes to AddSaleInvoiceActivity.
addSaleInvoiceFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(SalesInvoiceActivity.this, AddSaleInvoiceActivity.class));
}
});
In AddSaleInvoiceActivity there is an EditText and Date to store the name of the customer and invoice date in RecyclerView list in SalesInvoiceActivity.
customerName = addCustomerNameEt.getText().toString();
date = new Date();
When the user presses the Save Invoice button, the invoice number is saved with the ID, the invoice date, and the customer's name.
final SaleInvoiceEntry saleInvoiceEntry = new SaleInvoiceEntry(customerName, date);
appDatabase.salesInvoiceDao().insertSaleInvoice(saleInvoiceEntry);
#Entity(tableName = "saleInvoice")
public class SaleInvoiceEntry {
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "customerName")
private String customerName;
#ColumnInfo(name = "invoiceDate")
private Date invoiceDate;
#Ignore
public SaleInvoiceEntry(String customerName, Date invoiceDate) {
this.customerName = customerName;
this.invoiceDate = invoiceDate;
}
public SaleInvoiceEntry(int id) {
this.id = id;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerName() {
return customerName;
}
public void setInvoiceDate(Date invoiceDate) {
this.invoiceDate = invoiceDate;
}
public Date getInvoiceDate() {
return invoiceDate;
}
}
#Dao
public interface SalesInvoiceDao {
#Query("SELECT * FROM saleInvoice ORDER BY id")
LiveData<List<SaleInvoiceEntry>> loadAllSalesInvoice();
#Query("SELECT * FROM saleInvoice WHERE id = :saleInvoiceId")
LiveData<SaleInvoiceEntry> loadSalesInvoiceById(int saleInvoiceId);
#Insert
void insertSaleInvoice(SaleInvoiceEntry saleInvoiceEntry);
#Update(onConflict = OnConflictStrategy.REPLACE)
void updateSaleInvoice(SaleInvoiceEntry saleInvoiceEntry);
#Delete
void deleteSaleInvoice(SaleInvoiceEntry saleInvoiceEntry);
}
public class SalesInvoiceAdapter extends RecyclerView.Adapter<SalesInvoiceAdapter.SalesInvoiceViewHolder>
implements AddProductToSaleInvoiceAdapter.ItemClickListener {
private static final String DATE_FORMAT = "dd/MM/yyy";
private final SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
private final ItemClickListener itemClickListener;
private List<SaleInvoiceEntry> saleInvoiceEntries;
private final Context context;
private AppDatabase appDatabase;
private String saleInvoiceNumber, customerName, saleInvoiceDate;
public SalesInvoiceAdapter(Context context, ItemClickListener listener, AppDatabase appDatabase) {
this.context = context;
itemClickListener = listener;
this.appDatabase = appDatabase;
}
#NonNull
#Override
public SalesInvoiceViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.sales_list, parent, false);
return new SalesInvoiceViewHolder(view);
}
#SuppressLint({"SetTextI18n", "NotifyDataSetChanged"})
#Override
public void onBindViewHolder(SalesInvoiceViewHolder salesInvoiceViewHolder, int saleInvoicePosition) {
SaleInvoiceEntry saleInvoiceEntry = saleInvoiceEntries.get(saleInvoicePosition);
saleInvoiceNumber = String.valueOf(saleInvoiceEntry.getId());
salesInvoiceViewHolder.saleInvoiceNumberView.setText(context.getString(R.string.sale_invoice_number) + " : " + saleInvoiceNumber);
customerName = saleInvoiceEntry.getCustomerName();
salesInvoiceViewHolder.customerNameView.setText(context.getString(R.string.customer_name) + " : " + customerName);
saleInvoiceDate = dateFormat.format(saleInvoiceEntry.getInvoiceDate());
salesInvoiceViewHolder.saleInvoiceDateView.setText(context.getString(R.string.invoice_date) + " : " + saleInvoiceDate);
appDatabase = AppDatabase.getInstance(context);
salesInvoiceViewHolder.deleteSaleInvoice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(context, R.style.CutShapeTheme);
builder.setTitle(context.getString(R.string.delete_invoice))
.setMessage(context.getString(R.string.delete_invoice_message))
.setPositiveButton(context.getString(R.string.yes), (dialogInterface, i) -> {
try {
AppExecutors.getInstance().diskIO().execute(new Runnable() {
#Override
public void run() {
int saleInvoicePosition = salesInvoiceViewHolder.getAdapterPosition();
appDatabase.salesInvoiceDao().deleteSaleInvoice(saleInvoiceEntries.get(saleInvoicePosition));
}
});
Toast.makeText(context, context.getString(R.string.invoice_deleted), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
})
.setCancelable(false)
.setNegativeButton(context.getString(R.string.no), (dialog, which) -> {
})
.create().show();
}
});
salesInvoiceViewHolder.editSaleInvoice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent saleInvoiceIntent = new Intent(context, AddSaleInvoiceActivity.class);
int saleInvoiceId = saleInvoiceEntries.get(salesInvoiceViewHolder.getAdapterPosition()).getId();
saleInvoiceIntent.putExtra(EXTRA_SALE_INVOICE_ID, saleInvoiceId);
context.startActivity(saleInvoiceIntent);
}
});
}
#Override
public int getItemCount() {
if (saleInvoiceEntries == null) {
return 0;
}
return saleInvoiceEntries.size();
}
public List<SaleInvoiceEntry> getSaleInvoiceEntries() {
return saleInvoiceEntries;
}
#SuppressLint("NotifyDataSetChanged")
public void setSaleInvoiceEntries(List<SaleInvoiceEntry> saleInvoiceEntries) {
this.saleInvoiceEntries = saleInvoiceEntries;
notifyDataSetChanged();
}
#Override
public void onItemClickListener(int productId, String productName) {
}
public interface ItemClickListener {
void onItemClickListener(int saleInvoiceId, String customerName);
}
class SalesInvoiceViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private final TextView saleInvoiceNumberView, customerNameView, saleInvoiceDateView;
private final ImageView deleteSaleInvoice, editSaleInvoice;
public SalesInvoiceViewHolder(View itemView) {
super(itemView);
saleInvoiceNumberView = itemView.findViewById(R.id.listInvoiceNumber);
customerNameView = itemView.findViewById(R.id.listCustomerName);
saleInvoiceDateView = itemView.findViewById(R.id.listInvoiceDate);
deleteSaleInvoice = itemView.findViewById(R.id.listDeleteSaleInvoice);
editSaleInvoice = itemView.findViewById(R.id.listEditSaleInvoice);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int saleInvoiceId = saleInvoiceEntries.get(getAdapterPosition()).getId();
String customerName = saleInvoiceEntries.get(getAdapterPosition()).getCustomerName();
itemClickListener.onItemClickListener(saleInvoiceId, customerName);
}
}
}
public class SalesInvoiceActivity extends AppCompatActivity implements SalesInvoiceAdapter.ItemClickListener {
private FloatingActionButton addSaleInvoiceFab;
private RecyclerView salesInvoiceRv;
private SalesInvoiceAdapter salesInvoiceAdapter;
private AppDatabase appDatabase;
private View salesInvoiceEmptyView;
private SearchView salesInvoiceSv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sales_invoice);
initSalesInvoiceView();
setupSalesInvoiceViewModel();
setupSalesInvoiceRecycleView();
addSaleInvoiceFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(SalesInvoiceActivity.this, AddSaleInvoiceActivity.class));
}
});
salesInvoiceSv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
setupSalesInvoiceViewModel();
salesInvoiceFilter(newText);
return true;
}
});
}
private void salesInvoiceFilter(String text) {
ArrayList<SaleInvoiceEntry> salesInvoiceList = new ArrayList<>();
for (SaleInvoiceEntry saleInvoice : salesInvoiceAdapter.getSaleInvoiceEntries()) {
if (saleInvoice.getCustomerName().toLowerCase().contains(text.toLowerCase())) {
salesInvoiceList.add(saleInvoice);
}
}
if (salesInvoiceList.isEmpty()) {
Toast.makeText(this, getString(R.string.no_invoice), Toast.LENGTH_SHORT).show();
} else {
salesInvoiceAdapter.setSaleInvoiceEntries(salesInvoiceList);
}
}
private void initSalesInvoiceView() {
salesInvoiceEmptyView = findViewById(R.id.salesInvoiceEmptyView);
addSaleInvoiceFab = findViewById(R.id.addSaleInvoiceFab);
salesInvoiceRv = findViewById(R.id.salesInvoiceRv);
salesInvoiceSv = findViewById(R.id.saleSearchView);
}
private void setupSalesInvoiceRecycleView() {
appDatabase = AppDatabase.getInstance(getApplicationContext());
salesInvoiceAdapter = new SalesInvoiceAdapter(this, this, appDatabase);
salesInvoiceRv.setHasFixedSize(true);
salesInvoiceRv.setLayoutManager(new LinearLayoutManager(this));
salesInvoiceRv.setAdapter(salesInvoiceAdapter);
}
private void setupSalesInvoiceViewModel() {
MainViewModel mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
mainViewModel.getListSalesInvoiceLiveData().observe(this, new Observer<List<SaleInvoiceEntry>>() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onChanged(#Nullable List<SaleInvoiceEntry> saleInvoiceEntries) {
salesInvoiceAdapter.setSaleInvoiceEntries(saleInvoiceEntries);
salesInvoiceAdapter.notifyDataSetChanged();
if (salesInvoiceAdapter.getItemCount() == 0) {
salesInvoiceRv.setVisibility(View.GONE);
salesInvoiceEmptyView.setVisibility(View.VISIBLE);
salesInvoiceSv.setVisibility(View.GONE);
} else {
salesInvoiceRv.setVisibility(View.VISIBLE);
salesInvoiceEmptyView.setVisibility(View.GONE);
salesInvoiceSv.setVisibility(View.VISIBLE);
}
}
});
}
#Override
public void onItemClickListener(int saleInvoiceId, String customerName) {
Intent intent = new Intent(SalesInvoiceActivity.this, SaleDetailsActivity.class);
intent.putExtra("saleInvoiceId", saleInvoiceId);
intent.putExtra("productName", customerName);
startActivity(intent);
}
}
In AddSaleInvoiceActivity, I created a button that when the user clicks on it, it will be directed to the product store to capture the name of the product, selling price and store it in the RecyclerView list inside AddSaleInvoiceActivity
private Button addProductToSaleInvoiceBtn;
private void initAddProductToSaleInvoiceViews() {
addProductToSaleInvoiceBtn = findViewById(R.id.addProductToSaleInvoiceBtn);
addProductToSaleInvoiceBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent productToSaleInvoiceIntent = new Intent(AddSaleInvoiceActivity.this, ProductStoreActivity.class);
productToSaleInvoiceIntent.putExtra(EXTRA_PRODUCT_TO_SALE_INVOICE_ID, 1);
startActivity(productToSaleInvoiceIntent);
}
});
productToSaleInvoiceRv = findViewById(R.id.productToSaleInvoiceRv);
addProductToSaleInvoiceAdapter = new AddProductToSaleInvoiceAdapter(this, this, appDatabase);
productToSaleInvoiceRv.setHasFixedSize(true);
productToSaleInvoiceRv.setLayoutManager(new LinearLayoutManager(this));
productToSaleInvoiceRv.setAdapter(addProductToSaleInvoiceAdapter);
MainViewModel mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
mainViewModel.getListToSalesInvoiceLiveData().observe(this, new Observer<List<AddProductToSalesInvoiceEntry>>() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onChanged(#Nullable List<AddProductToSalesInvoiceEntry> addProductToSalesInvoiceEntries) {
addProductToSaleInvoiceAdapter.setProductToSalesInvoiceEntries(addProductToSalesInvoiceEntries);
addProductToSaleInvoiceAdapter.notifyDataSetChanged();
}
});
}
#Entity(tableName = "addProductToSalesInvoice")
public class AddProductToSalesInvoiceEntry {
#PrimaryKey(autoGenerate = true)
private int addProductToSalesInvoiceId;
private final String toSalesInvoiceProductName;
private final int toSalesInvoiceProductQuantity;
private final float toSalesInvoiceProductSellingPrice;
#Ignore
public AddProductToSalesInvoiceEntry(String toSalesInvoiceProductName, int toSalesInvoiceProductQuantity
, float toSalesInvoiceProductSellingPrice) {
this.toSalesInvoiceProductName = toSalesInvoiceProductName;
this.toSalesInvoiceProductQuantity = toSalesInvoiceProductQuantity;
this.toSalesInvoiceProductSellingPrice = toSalesInvoiceProductSellingPrice;
}
public AddProductToSalesInvoiceEntry(int addProductToSalesInvoiceId, String toSalesInvoiceProductName, int toSalesInvoiceProductQuantity
, float toSalesInvoiceProductSellingPrice) {
this.addProductToSalesInvoiceId = addProductToSalesInvoiceId;
this.toSalesInvoiceProductName = toSalesInvoiceProductName;
this.toSalesInvoiceProductQuantity = toSalesInvoiceProductQuantity;
this.toSalesInvoiceProductSellingPrice = toSalesInvoiceProductSellingPrice;
}
public int getAddProductToSalesInvoiceId() {
return addProductToSalesInvoiceId;
}
public void setAddProductToSalesInvoiceId(int addProductToSalesInvoiceId) {
this.addProductToSalesInvoiceId = addProductToSalesInvoiceId;
}
public String getToSalesInvoiceProductName() {
return toSalesInvoiceProductName;
}
public int getToSalesInvoiceProductQuantity() {
return toSalesInvoiceProductQuantity;
}
public float getToSalesInvoiceProductSellingPrice() {
return toSalesInvoiceProductSellingPrice;
}
}
#Dao
public interface AddProductToSalesInvoiceDao {
#Query("SELECT * FROM addProductToSalesInvoice ORDER BY addProductToSalesInvoiceId")
LiveData<List<AddProductToSalesInvoiceEntry>> addProductToSalesInvoiceLoadAllProducts();
#Query("SELECT * FROM addProductToSalesInvoice WHERE addProductToSalesInvoiceId = :addProductToSalesInvoiceProductId")
LiveData<AddProductToSalesInvoiceEntry> addProductToSalesInvoiceLoadProductsById(int addProductToSalesInvoiceProductId);
#Insert
void addProductToSalesInvoiceInsertProduct(AddProductToSalesInvoiceEntry addProductToSalesInvoiceEntry);
#Update(onConflict = OnConflictStrategy.REPLACE)
void addProductToSalesInvoiceUpdateProduct(AddProductToSalesInvoiceEntry addProductToSalesInvoiceEntry);
#Delete
void addProductToSalesInvoiceDeleteProduct(AddProductToSalesInvoiceEntry addProductToSalesInvoiceEntry);
#Delete
void addProductToSalesInvoiceDeleteAllProduct(List<AddProductToSalesInvoiceEntry> toSalesInvoiceEntries);
}
public class AddProductToSaleInvoiceAdapter extends RecyclerView
.Adapter<AddProductToSaleInvoiceAdapter.AddProductToSalesInvoiceViewHolder> {
private final ItemClickListener addProductToSalesInvoiceItemClickListener;
private List<AddProductToSalesInvoiceEntry> addProductToSalesInvoiceEntries;
private final Context context;
private AppDatabase appDatabase;
private String addProductToSalesInvoiceProductName;
private int addProductToSalesInvoiceProductQuantity;
private float addProductToSalesInvoiceProductSellingPrice;
private List<AddProductToSalesInvoiceEntry> addProductToSalesInvoiceEntryList;
public AddProductToSaleInvoiceAdapter(Context context, ItemClickListener listener, AppDatabase appDatabase) {
this.context = context;
addProductToSalesInvoiceItemClickListener = listener;
this.appDatabase = appDatabase;
}
#NonNull
#Override
public AddProductToSalesInvoiceViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.add_products_to_sale_invoice_list, parent, false);
return new AddProductToSalesInvoiceViewHolder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(AddProductToSalesInvoiceViewHolder addProductToSalesInvoiceViewHolder
, int productToSalesInvoicePosition) {
AddProductToSalesInvoiceEntry addProductToSalesInvoiceEntry
= addProductToSalesInvoiceEntries.get(productToSalesInvoicePosition);
addProductToSalesInvoiceProductName = addProductToSalesInvoiceEntry.getToSalesInvoiceProductName();
addProductToSalesInvoiceViewHolder.listAddProductToSalesInvoiceProductNameView.setText(addProductToSalesInvoiceProductName);
addProductToSalesInvoiceProductQuantity = addProductToSalesInvoiceEntry.getToSalesInvoiceProductQuantity();
addProductToSalesInvoiceViewHolder.listAddProductToSalesInvoiceProductQuantityView.setText("" + addProductToSalesInvoiceProductQuantity);
addProductToSalesInvoiceProductSellingPrice = addProductToSalesInvoiceEntry.getToSalesInvoiceProductSellingPrice();
addProductToSalesInvoiceViewHolder.listAddProductToSalesInvoiceProductSellingPriceView.setText("" + addProductToSalesInvoiceProductSellingPrice);
addProductToSalesInvoiceViewHolder.productSellingPriceView.setText(context.getString(R.string.product_selling_price) + " : " + addProductToSalesInvoiceProductSellingPrice);
#Override
public int getItemCount() {
if (addProductToSalesInvoiceEntries == null) {
return 0;
}
return addProductToSalesInvoiceEntries.size();
}
public List<AddProductToSalesInvoiceEntry> getAddProductToSalesInvoiceEntries
(ArrayList<AddProductToSalesInvoiceEntry> uProductToSalesInvoiceList) {
return addProductToSalesInvoiceEntries;
}
#SuppressLint("NotifyDataSetChanged")
public void setProductToSalesInvoiceEntries(List<AddProductToSalesInvoiceEntry> addProductToSalesInvoiceEntries) {
this.addProductToSalesInvoiceEntries = addProductToSalesInvoiceEntries;
notifyDataSetChanged();
}
public interface ItemClickListener {
void onItemClickListener(int productId, String productName);
}
class AddProductToSalesInvoiceViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private final TextView listAddProductToSalesInvoiceProductNameView, listAddProductToSalesInvoiceProductQuantityView
, listAddProductToSalesInvoiceProductSellingPriceView;
public AddProductToSalesInvoiceViewHolder(View itemView) {
super(itemView);
listAddProductToSalesInvoiceProductNameView = itemView
.findViewById(R.id.listAddProductToSalesInvoiceProductNameView);
listAddProductToSalesInvoiceProductQuantityView = itemView
.findViewById(R.id.listAddProductToSalesInvoiceProductQuantityView);
listAddProductToSalesInvoiceProductSellingPriceView = itemView
.findViewById(R.id.listAddProductToSalesInvoiceProductSellingPriceView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int productId = addProductToSalesInvoiceEntries.get(getAdapterPosition()).getAddProductToSalesInvoiceId();
String productName = addProductToSalesInvoiceEntries.get(getAdapterPosition()).getToSalesInvoiceProductName();
addProductToSalesInvoiceItemClickListener.onItemClickListener(productId, productName);
}
}
}
Now how do I store the AddProductToSalesInvoiceEntry list inside the SaleInvoiceEntry list when the user clicks the save invoice button ?

problem with scrolling up or down of listview

When I try to take all the values of the NumberPicker, it correctly returns the ones in the middle, while the first and last returns only the last one that has been modified between them. I don't understand where I'm wrong.
public class piatto {
String nome;
String Descrizione;
String prezzo;
String immagine;
String tag;
public piatto(String nome, String Descrizione, String prezzo, String immagine, String tag) {
this.nome= nome;
this.Descrizione= Descrizione;
this.prezzo= prezzo;
this.immagine=immagine;
this.tag=tag;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDescrizione() {
return Descrizione;
}
public void setDescrizione(String descrizione) {
Descrizione = descrizione;
}
public String getPrezzo() {
return prezzo;
}
public void setPrezzo(String prezzo) {
this.prezzo = prezzo;
}
public String getImmagine() {
return immagine;
}
public void setImmagine(String immagine) {
this.immagine = immagine;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
}
this is my adapeter
public class ProductListAdapterforListView extends BaseAdapter {
private Context mContext;
private List<piatto> mProductList;
public ProductListAdapterforListView(Context mContext, List<piatto> mProductList) {
this.mContext = mContext;
this.mProductList = mProductList;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public piatto getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listitemview ;
if (convertView==null){
listitemview = View.inflate(mContext, R.layout.row_data_list, null);
ImageView i = (ImageView) listitemview.findViewById(R.id.imagepiatto);
com.shawnlin.numberpicker.NumberPicker numberPicker = (com.shawnlin.numberpicker.NumberPicker) listitemview.findViewById(R.id.number_picker);
TextView n=(TextView) listitemview.findViewById(R.id.namepiatto);
TextView p=(TextView) listitemview.findViewById(R.id.prezzopiatto);
n.setText(mProductList.get(position).getNome());
p.setText(mProductList.get(position).getPrezzo()+" €");
Picasso.get().load(mProductList.get(position).getImmagine()).into(i);
} else {
listitemview=convertView;
}
return listitemview;
}
}
And this is my Java class where I get the values of the NumberPicker of each Item
#Override
public void onClick(View view) {
if (view.getId()==R.id.buttonnext){
Float totale = (float) 0.0;
String listapiatti="";
for (int i = 0; i < listView.getChildCount(); i++) {
view = listView.getChildAt(i);
TextView n = view.findViewById(R.id.namepiatto);
String nome = n.getText().toString();
TextView p = view.findViewById(R.id.prezzopiatto);
String pricestr = p.getText().toString();
String[] prezzo = pricestr.split(" ");
Float price = Float.valueOf(prezzo[0]);
com.shawnlin.numberpicker.NumberPicker numberPicker = (com.shawnlin.numberpicker.NumberPicker) view.findViewById(R.id.number_picker);
int value = numberPicker.getValue();
if (value != 0) {
totale = totale + (price * value);
listapiatti = listapiatti + nome + ": " + value + ", ";
Toast.makeText(getApplicationContext(), String.valueOf(i)+" "+value,
Toast.LENGTH_LONG).show();
}
}
String finale=String.valueOf(totale);
startActivity(new Intent(carrello3.this, ordine.class));
}
if (view.getId()==R.id.buttonback){
onBackPressed();
}
}
it doesn't seem like a good idea to create an object on setOnScrollListener which gets called many many times during scrolling up/down. if you could provide more detail would be great.

My get method is returning 0 even though it has a value

So I have two classes. I'm trying to send integer data from one class to the other with a get method (getInputTime). The variable I'm returning inside the get method has a value. But when I use the get method inside of the other class called TimeActivity it just returns 0.
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private static final String TAG = "CustomAdapter";
private ArrayList<Integer> mWorkTW = new ArrayList<>();
private ArrayList<Integer> mWorkET = new ArrayList<>();
private ArrayList<Integer> mRestTW = new ArrayList<>();
private ArrayList<Integer> mRestET = new ArrayList<>();
private Context mContext;
private int numberOfIntervals;
public CustomAdapter() {
}
public CustomAdapter(Context context, ArrayList<Integer> mWorkTW, ArrayList<Integer> mWorkET, ArrayList<Integer> mRestTW, ArrayList<Integer> mRestET, int numberOfIntervals) {
this.mWorkTW = mWorkTW;
this.mWorkET = mWorkET;
this.mRestTW = mRestTW;
this.mRestET = mRestET;
this.mContext = context;
this.numberOfIntervals = numberOfIntervals;
//this.inputTimeIntegerWET = inputTimeIntegerWET;
Log.d(TAG, "CustomAdapter: " + numberOfIntervals);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View customView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.time_row, viewGroup, false);
ViewHolder holder = new ViewHolder(customView, new InputTextListener());
return holder;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
Log.d(TAG, "onBindViewHolder: called");
viewHolder.workTextView.setText(R.string.work_text_view);
viewHolder.restTextView.setText(R.string.rest_text_view);
viewHolder.workEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
viewHolder.workEditText.setHint("");
else
viewHolder.workEditText.setHint(mWorkET.get(viewHolder.getAdapterPosition()));
}
});
viewHolder.restEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
viewHolder.restEditText.setHint("");
else
viewHolder.restEditText.setHint(mRestET.get(viewHolder.getAdapterPosition()));
}
});
}
#Override
public int getItemCount() {
Log.d(TAG, "" + numberOfIntervals);
return numberOfIntervals;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public InputTextListener inputTextListener;
TextView workTextView;
EditText workEditText;
TextView restTextView;
EditText restEditText;
ConstraintLayout parentLayout;
public ViewHolder(#NonNull View itemView, InputTextListener inputTextListener) {
super(itemView);
workTextView = itemView.findViewById(R.id.workTextView);
workEditText = itemView.findViewById(R.id.workEditText);
restTextView = itemView.findViewById(R.id.restTextView);
restEditText = itemView.findViewById(R.id.restEditText);
parentLayout = itemView.findViewById(R.id.parentLayout);
this.inputTextListener = inputTextListener;
workEditText.addTextChangedListener(inputTextListener);
}
}
class InputTextListener implements TextWatcher {
String inputTimeString;
int inputTime;
HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
public HashMap<String, Integer> getHashMap() {
return hashMap;
}
public InputTextListener() {
}
public void setHashMap(HashMap<String, Integer> hashMap) {
this.hashMap = hashMap;
}
public int getInputTime() {
return inputTime;
}
public void setInputTime(int inputTime) {
this.inputTime= inputTime;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
Log.d(TAG, "onTextChanged: I've made it to here!");
inputTimeString = s.toString().trim();
inputTime = Integer.parseInt(inputTimeString);
setInputTime(inputTime);
// hashMap.put("EDITTEXT VALUE", inputTime);
Log.d(TAG, "onTextChanged: " + inputTime);
int bla = inputTime + 2;
Log.d(TAG, "onTextChanged: " + bla);
Log.d(TAG, "onTextChanged: " + hashMap.containsKey("EDITTEXT VALUE"));
Log.d(TAG, "onTextChanged: " + hashMap.get("EDITTEXT VALUE"));
Log.d(TAG, "onTextChanged: "+ getInputTime());
//setHashMap(hashMap);
} catch (NumberFormatException NFE) {
mWorkET = null;
}
}
#Override
public void afterTextChanged(Editable s) {
}
}
}
public class TimeActivity extends AppCompatActivity {
public static final String TAG = TimeActivity.class.getSimpleName();
private int numberOfIntervals;
private ArrayList<Integer> WTV = new ArrayList<>();
private ArrayList<Integer> WET = new ArrayList<>();
private ArrayList<Integer> RTV = new ArrayList<>();
private ArrayList<Integer> RET = new ArrayList<>();
private int inputTime;
// private String yusuf = "5";
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.custom_menu, menu);
Drawable continueImageDrawable = menu.findItem(R.id.continueItem).getIcon();
continueImageDrawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
//Every non-transparent pixel will be turned into white.
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.continueItem:
CustomAdapter a = new CustomAdapter();
CustomAdapter.InputTextListener i = a.new InputTextListener();
//HashMap<String, Integer> hashMap = i.getHashMap();
//inputTime = hashMap.get("EDITTEXT VALUE");
inputTime = i.getInputTime();
// Log.d(TAG, "onOptionsItemSelected: " + hashMap.get("EDITTEXT VALUE"));
//Log.d(TAG, "onOptionsItemSelected: " + hashMap.containsKey("EDITTEXT VALUE"));
Log.d(TAG, "onOptionsItemSelected: " + inputTime);
retrieveInputTime(inputTime);
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time);
Log.d(TAG, "onCreate: Started");
View timeRowLayout = findViewById(R.id.parentLayout);
Intent intent = getIntent();
numberOfIntervals = intent.getIntExtra("Interval Count", numberOfIntervals);
Log.d(TAG, "" + numberOfIntervals);
initializeViews();
}
private void retrieveInputTime(int inputTime) {
Log.d(TAG, "retrieveInputTime: " + inputTime);
Intent intent2 = new Intent(this, ClockActivity.class);
if (inputTime > 0) {
intent2.putExtra("Input Time", inputTime);
startActivity(intent2);
Log.d(TAG, "retrieveInputTime: The data has been retrieved" + inputTime);
} else {
Toast.makeText(this, "Must enter a whole number 2", Toast.LENGTH_SHORT).show();
}
}
private void initializeViews() {
Log.d(TAG, "initializeViews: Preparing views");
//Make sure they can change through the R.strings
WTV.add(R.string.work_text_view);
WET.add(R.string.default_time_value);
RTV.add(R.string.rest_text_view);
RET.add(R.string.default_time_value);
initializeRecyclerView();
}
private void initializeRecyclerView() {
Log.d(TAG, "initializeRecyclerView: Initialize RecyclerView");
RecyclerView intervalRecyclerView = findViewById(R.id.intervalRecyclerView);
CustomAdapter adapter = new CustomAdapter(this, WTV, WET, RTV, RET, numberOfIntervals);
intervalRecyclerView.setAdapter(adapter);
intervalRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
I expect for the getInputTime method to return the correct value inside the TimeActivity class
I see you use getInputTime() in two places:
inside onTextChanged() it is preceded by setInputTime() so it should has value there
inside onOptionsItemSelected() it is called right after creating a new object via InputTextListener(). No initialization is done besides calling the default constructor. inputTime should be 0 at this point.
The CustomAdapater instance that you are referring to in onOptionsItemSelected isn't the same as the one you are initializing for your recyclerView in onCreate.
Look:
CustomAdapter a = new CustomAdapter();
CustomAdapter.InputTextListener i = a.new InputTextListener();
inputTime = i.getInputTime();
You are creating new instance of CustomAdapter then creating new instance of InputTextListener (zero connection between these objects so far), calling getInputTime() on that object will obviously return 0, since it's the default value of int in java.
Anyway, I can't really see the point for using recyclerView in your code.
First of all I want to thank everyone for trying to help solve the problem but I finally solved. The solution is to make the inputTime variable inside the InputTextListener class static. But since it's an inner class I had to make the InputTextListener class it's own class. If you have any thoughts or questions just comment down below.

Recycerview changing the wrong items

here is my recyclerview adapter classs
public class WebsiteAdapter extends RecyclerView.Adapter<WebsiteAdapter.WebsiteHolder> {
private List<Website> websites = new ArrayList<>();
private WebsiteViewModel websiteViewModel;
WebsiteAdapter(WebsiteViewModel viewModel){
this.websiteViewModel = viewModel;
}
#NonNull
#Override
public WebsiteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.website_item, parent, false);
return new WebsiteHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final WebsiteHolder holder, final int position) {
final Website currentWebsite = websites.get(position);
final Boolean bookmarkStatus = currentWebsite.getFavourite();
final List<WebPage> webPages = websiteViewModel.getRepository().getAllWebPagesForWebsite(currentWebsite.getWebsite_id());
holder.textViewTitle.setText(currentWebsite.getWebsiteName());
if(currentWebsite.getDescription() != null){
holder.textViewDescription.setText(currentWebsite.getDescription());
holder.textViewDescription.setVisibility(View.VISIBLE);
}
if(webPages!=null && !webPages.isEmpty()) {
holder.secondaryAdapter.setWebPages(webPages);
holder.expandCollapse.setVisibility(View.VISIBLE);
}
if(bookmarkStatus){
holder.isBookmarked = true;
holder.bookmarkButton.setBackgroundResource(R.drawable.ic_bookmark_24px);
} else {
holder.isBookmarked = false;
holder.bookmarkButton.setBackgroundResource(R.drawable.ic_bookmark_border_24px);
}
holder.cardViewWebsite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String websiteUrl = currentWebsite.getWebsite_url();
System.out.println("Description = " + currentWebsite.getDescription() + ", boomarked : " + currentWebsite.getFavourite());
List<WebPage> webPages = websiteViewModel.getRepository().getAllWebPagesForWebsite(currentWebsite.getWebsite_id());
for(WebPage webPage : webPages){
System.out.println("Web pages: ");
System.out.println(webPage.toString() + ", ");
}
launchWebsite(v.getContext(), websiteUrl);
}
});
holder.bookmarkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Website bookmarked before click : " + bookmarkStatus + ", Description is : " + currentWebsite.getDescription());
currentWebsite.setFavourite(!bookmarkStatus);
System.out.println("Website bookmark clicked, status has been set to : " + currentWebsite.getFavourite());
websiteViewModel.getRepository().websiteDao.updateWebsite(currentWebsite);
notifyItemChanged(position);
}
});
}
private void launchWebsite(Context context, String URL) {
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
builder.setStartAnimations(context, R.anim.push_off_screen_left, R.anim.push_onto_screen_from_right);
builder.setExitAnimations(context, R.anim.push_onto_screen_from_left, R.anim.push_off_screen_right);
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(context,Uri.parse(URL));
}
#Override
public int getItemCount() {
return websites.size();
}
public void setWebsites(List<Website> websites) {
this.websites = websites;
notifyDataSetChanged();
}
class WebsiteHolder extends RecyclerView.ViewHolder {
private TextView textViewTitle;
private TextView textViewDescription;
private CardView cardViewWebsite;
private boolean isBookmarked; // ALSO FAVOURITED
private boolean isExpanded = false;
private Button expandCollapse;
private Button bookmarkButton;
private SecondaryAdapter secondaryAdapter;
private RecyclerView childRecyclerView;
public WebsiteHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.text_view_title);
textViewDescription = itemView.findViewById(R.id.text_view_description);
cardViewWebsite = itemView.findViewById(R.id.cardViewWebsite);
bookmarkButton = itemView.findViewById(R.id.bookmarkButton);
childRecyclerView = itemView.findViewById(R.id.childRecyclerview);
expandCollapse = itemView.findViewById(R.id.expandCollapse);
expandCollapse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isExpanded) {
collapseView();
} else {
expandView();
}
}
});
childRecyclerView.setLayoutManager(new LinearLayoutManager(itemView.getContext(), LinearLayoutManager.HORIZONTAL, false));
LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(itemView.getContext(), R.anim.layout_animation_slide_in);
childRecyclerView.setLayoutAnimation(animation);
childRecyclerView.setHasFixedSize(true);
secondaryAdapter = new SecondaryAdapter();
childRecyclerView.setAdapter(secondaryAdapter);
}
private void collapseView() {
isExpanded = false;
childRecyclerView.setVisibility(View.GONE);
}
private void expandView() {
isExpanded = true;
childRecyclerView.setVisibility(View.VISIBLE);
}
}
}
The issue I am having is, when I press the bookmark button on item A: the expand button on a different item will appear when it should not. B: The secondaryRecyclerView gets set to some other website. How do I go about debugging this? Is there anything that jumps out as a culpit? I feel like I am setting somethings in the wrong place. Thanks very much
wrong item changes in recyclerview
Thanks to this post, I one, added in a bindView method, and 2: added ELSE statements to negate the if statements. Problems solved :) For now :)

display data from SQLite database to custom listview

I am trying to display data from SQLite database to custom listview but it is not displaying. When I am using simple list view with single data then it's working but not working when I am trying to display on custom listview.
MainActivity.java
package com.example.addressbook;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.AddressBook.MESSAGE";
private ListView lv;
List<Listcollection> collectionlist;
DBHelper mydb;
private Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
mydb = new DBHelper(this);
// CustomListAdapter customListAdapter = new
// CustomListAdapter(MainActivity.this, );
lv.setAdapter(new ViewAdapter(mydb.listfromdb()));
// lv.setAdapter(ViewAdapter);
// adding it to the list view.
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),
com.example.addressbook.Display.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
public class ViewAdapter extends BaseAdapter {
LayoutInflater mInflater;
List<Listcollection> collectionlist;
public ViewAdapter(List<Listcollection> c) {
collectionlist = c;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return collectionlist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#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
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_item, null);
}
Listcollection o = collectionlist.get(position);
if (o != null) {
TextView idText = (TextView) convertView
.findViewById(R.id.lvid);
TextView nameText = (TextView) convertView
.findViewById(R.id.lvname);
TextView dateText = (TextView) convertView
.findViewById(R.id.lvdate);
TextView phoneText = (TextView) convertView
.findViewById(R.id.lvphone);
if (idText != null) {
idText.setText(Integer.toString(o.getId()));
}
if (nameText != null) {
nameText.setText("Name : "
+ collectionlist.get(position).getName());
}
if (dateText != null) {
dateText.setText("Date: "
+ collectionlist.get(position).getDate());
}
if (phoneText != null) {
phoneText.setText("Phone: "
+ collectionlist.get(position).getPhone());
}
}
return convertView;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mainmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.item1:
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(getApplicationContext(),
com.example.addressbook.Display.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String C_NAME = "name";
public static final String C_TYPE = "type";
public static final String C_ADDRESS = "address";
public static final String C_DATE = "date";
public static final String C_PHONE = "phone";
private HashMap hp;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table contacts "
+ "(id integer primary key, name text,phone text,type text, address text,date text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertContact(String name, String phone, String type,
String address, String date) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("type", type);
contentValues.put("address", address);
contentValues.put("date", date);
db.insert("contacts", null, contentValues);
return true;
}
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from contacts where id=" + id + "",
null);
return res;
}
public int numberOfRows() {
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db,
CONTACTS_TABLE_NAME);
return numRows;
}
public boolean updateContact(Integer id, String name, String phone,
String type, String address, String date) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("type", type);
contentValues.put("address", address);
contentValues.put("date", date);
db.update("contacts", contentValues, "id = ? ",
new String[] { Integer.toString(id) });
return true;
}
public Integer deleteContact(Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts", "id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<Listcollection> listfromdb() {
SQLiteDatabase db = this.getReadableDatabase();
Listcollection lcollection;
Listcollection list = new Listcollection();
ArrayList<Listcollection> results = new ArrayList<Listcollection>();
Cursor crs = db.rawQuery("select * from contacts", null);
crs.moveToFirst();
list.setId(crs.getInt(crs.getColumnIndex(CONTACTS_COLUMN_ID)));
list.setName(crs.getString(crs.getColumnIndex(C_NAME)));
list.setDate(crs.getString(crs.getColumnIndex(C_DATE)));
list.setPhone(crs.getString(crs.getColumnIndex(C_PHONE)));
db.close();
return results;
}
}
enter code here
Listcollection.java
public class Listcollection {
// private variables
int id;
String name;
String type;
String address;
String date;
String phone;
// Empty constructor
public Listcollection(Parcel in) {
}
// constructor
public Listcollection(int id, String name, String type, String address,
String date, String phone) {
this.id = id;
this.name = name;
this.type = type;
this.address = address;
this.phone = phone;
this.date = date;
}
public Listcollection() {
// TODO Auto-generated constructor stub
}
// getting id
public int getId() {
return this.id;
}
// setting id
public void setId(int id) {
this.id = id;
}
// getting name
public String getName() {
return this.name;
}
// setting name
public void setName(String name) {
this.name = name;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDate() {
return this.date;
}
public void setDate(String date) {
this.date = date;
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String toString() {
return "Complain [id=" + id + ", name=" + name + ", type=" + type
+ ", address=" + address + ", date=" + date + ", phone="
+ phone + ",";
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Listcollection other = (Listcollection) obj;
if (id != other.id)
return false;
return true;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeInt(getId());
parcel.writeString(getName());
parcel.writeString(getType());
parcel.writeString(getAddress());
parcel.writeString(getPhone());
parcel.writeString(getDate());
}
public static final Parcelable.Creator<Listcollection> CREATOR = new Parcelable.Creator<Listcollection>() {
public Listcollection createFromParcel(Parcel in) {
return new Listcollection(in);
}
public Listcollection[] newArray(int size) {
return new Listcollection[size];
}
};
}
You're not actually adding the database records to the results collection in listfromdb().
Should be something like:
public ArrayList<Listcollection> listfromdb() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Listcollection> results = new ArrayList<Listcollection>();
Cursor crs = db.rawQuery("select * from contacts", null);
while (crs.moveToNext()) {
Listcollection item = new Listcollection();
item.setId(crs.getInt(crs.getColumnIndex(CONTACTS_COLUMN_ID)));
item.setName(crs.getString(crs.getColumnIndex(C_NAME)));
item.setDate(crs.getString(crs.getColumnIndex(C_DATE)));
list.setPhone(crs.getString(crs.getColumnIndex(C_PHONE)));
results.add(item);
}
db.close();
return results;
}

Categories