My Entity class looks like this:
#Entity
public class User {
public int getId() {
return id;
}
#NonNull
public ArrayList<String> getValues(){
return values;
}
#NonNull
public ArrayList<String> getDates(){
return dates;
}
#NonNull
public String getType_counter() {
return type_counter;
}
#NonNull
public String getWhere_counter() {
return where_counter;
}
#PrimaryKey(autoGenerate = true)
public int id;
#ColumnInfo(name = "d")
#TypeConverters({Converters.class})
public ArrayList<String> dates;
#ColumnInfo(name = "value")
#TypeConverters({Converters.class})
public ArrayList<String> values;
#ColumnInfo(name = "type")
public String type_counter;
#ColumnInfo(name = "location")
public String where_counter;
}
I have one RecyclerView which shows only type and location and when you click on any item it goes to another activity where another RecyclerView shows values and dates of this particular User (by Id) as arrays.
My problem is this: user of my app can either create new User object or update it (add value and date to ArrayLists) and when updating RecyclerView is not working properly.
Suppose I have two User objects and my database looks like this:
My fist object has two values and dates but RecyclerView shows only one.
When I add another value and date to the second User object, RecyclerView shows two elements in both objects.
This is how I update values:
private void saveNewValue(String value, String type, String location){
// Getting current date
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
String formattedDate = df.format(c);
userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
// checking if the counter exists
int mList = userViewModel.setTypeLocation(type, location);
if (mList == 0){
//Saving new User
User user = new User();
if (user.values == null){
user.values = new ArrayList<String>();
}
if (user.dates == null){
user.dates = new ArrayList<String>();
}
user.values.add(value);
user.dates.add(formattedDate);
user.type_counter = type;
user.where_counter = location;
userViewModel.insert(user);
Toast.makeText(this, "Successfully saved!", Toast.LENGTH_SHORT).show();
}
else {
//Getting current data
User mUser = userViewModel.getUserWithLocationType(type, location);
ArrayList<String> values_user = mUser.getValues();
ArrayList<String> dates_user = mUser.getDates();
// Updating arrays
values_user.add(value);
dates_user.add(formattedDate);
// Creating new User object with updated values
User updatedUser = new User();
updatedUser.id = mUser.getId();
updatedUser.type_counter = type;
updatedUser.where_counter = location;
updatedUser.values = values_user;
updatedUser.dates = dates_user;
userViewModel.update(updatedUser);
//userAdapter.notifyItemChanged();
Toast.makeText(this, "Successfully updated!", Toast.LENGTH_SHORT).show();
}
}
This is Adapter class for an already described RecyclerView:
public class CalculationAdapter extends RecyclerView.Adapter<CalculationAdapter.CalcViewHolder>{
private LayoutInflater inflater;
private Context mContext;
private ArrayList<String> mValues;
private ArrayList<String> mDates;
private User mUser;
public CalculationAdapter(Context ctx){
inflater = LayoutInflater.from(ctx);
mContext = ctx;
}
public void setUser(User user){
mUser = user;
mValues = user.getValues();
mDates = user.getDates();
notifyDataSetChanged();
Log.i("values", String.valueOf(mValues));
Log.i("dates", String.valueOf(mDates));
}
#NonNull
#Override
public CalculationAdapter.CalcViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.calculations_item, parent, false);
CalculationAdapter.CalcViewHolder holder = new CalculationAdapter.CalcViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull CalculationAdapter.CalcViewHolder holder, int position) {
if (mValues != null & mDates != null){
String value = mValues.get(position);
String date = mDates.get(position);
holder.setValuesDates(value, date, position);
}
else{
holder.mValue.setText("No value");
holder.mDate.setText("No date");
}
}
#Override
public int getItemCount() {
if (mValues != null){
return mValues.size();
} else return 0;
}
class CalcViewHolder extends RecyclerView.ViewHolder {
private TextView mValue;
private TextView mDate;
private int mPosition;
public CalcViewHolder(#NonNull View itemView) {
super(itemView);
mValue = itemView.findViewById(R.id.item_value);
mDate = itemView.findViewById(R.id.item_date);
}
public void setValuesDates(String value, String date, int position){
mValue.setText(value);
mDate.setText(date);
mPosition = position;
}
}
}
This is ViewModel class:
public class UserViewModel extends AndroidViewModel {
private String TAG = this.getClass().getSimpleName();
private UserDao userDao;
private AppDatabase appDatabase;
private LiveData<List<User>> mAllUsers;
private LiveData<String[]> mAllLocations;
private LiveData<User> mUser;
private int UserLocationTypeExists;
public UserViewModel(#NonNull Application application) {
super(application);
appDatabase = AppDatabase.getInstance(application);
userDao = appDatabase.userDao();
mAllUsers = userDao.getAllValues();
mAllLocations = userDao.getAllLocations();
}
public void setId(int id){
mUser = userDao.getUserWithId(id);
}
public User getUserWithLocationType(String type, String location){
return userDao.getUserwithLocationType(type, location);
}
public int setTypeLocation(String type, String location){
UserLocationTypeExists = userDao.UserWithTypeLocationExists(type, location);
return UserLocationTypeExists;
}
public void update(User user) {
new UpdateAsyncTask(userDao).execute(user);
}
public void insert(User user){
new InsertAsyncTask(userDao).execute(user);
}
public void delete(User user){
new DeleteAsyncTask(userDao).execute(user);
}
public LiveData<List<User>> getAllUsers(){
return mAllUsers;
}
public LiveData<String[]> getAllLocations() {
return mAllLocations;
}
public LiveData<User> getUserAtId(){
return mUser;
}
private class InsertAsyncTask extends AsyncTask<User, Void, Void> {
UserDao userDao;
public InsertAsyncTask(UserDao userDao) {
this.userDao = userDao;
}
#Override
protected Void doInBackground(User... users) {
userDao.insertValue(users[0]);
return null;
}
}
private class DeleteAsyncTask extends AsyncTask<User, Void, Void> {
UserDao userDao;
public DeleteAsyncTask(UserDao userDao) {
this.userDao = userDao;
}
#Override
protected Void doInBackground(User... users) {
userDao.deleteValue(users[0]);
return null;
}
}
private class UpdateAsyncTask extends AsyncTask<User, Void, Void> {
UserDao userDao;
public UpdateAsyncTask(UserDao userDao) {
this.userDao = userDao;
}
#Override
protected Void doInBackground(User... users) {
userDao.update(users[0]);
return null;
}
}
}
This is the Activity where I have RecyclerView:
public class CalculationActivity extends AppCompatActivity{
private int id_counter;
private UserViewModel userViewModel;
private CalculationAdapter calcAdapter;
private int rate;
private String value1, date1, value2, date2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculation);
Bundle extras = getIntent().getExtras();
if (extras != null) {
id_counter = extras.getInt("id");
}
RecyclerView recyclerView = findViewById(R.id.recyclerView_calc);
calcAdapter = new CalculationAdapter(this);
recyclerView.setAdapter(calcAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
userViewModel.setId(id_counter);
userViewModel.getUserAtId().observe(this, new Observer<User>() {
#Override
public void onChanged(User user) {
calcAdapter.setUser(user);
}
});
}
}
Could somebody please help me figure out why doesn't my RecyclerView update data correctly? Thanks in advance.
I can add more info if necessary.
This is TypeConverters.class:
public class Converters {
#TypeConverter
public static ArrayList<String> fromString(String value) {
Type listType = new TypeToken<ArrayList<String>>() {}.getType();
return new Gson().fromJson(value, listType);
}
#TypeConverter
public static String fromArrayList(ArrayList<String> list) {
Gson gson = new Gson();
return gson.toJson(list);
}
}
EDIT: I saved different values in the database. Here is how the database looking:
This is Activity1:
When I click on both items they both show value 2222:
Output of SetUser method (when I click on each of the items):
I/values: [2222]
I/dates: [27-Juli-2022]
I/values: [2222]
I/dates: [27-Juli-2022]
Small mistake... I've been sending ID to Activity2 the wrong way. I've been getting it in the onBindViewHolder method which goes over all the elements and which is why I got only values from the last saved element. I needed to get ID in the Holder class in OnClick method. Thanks for all the help anyway.
Related
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 ?
I have some adapter which use retrofit to get data right from web api and place it to recyclerview
public class NoticeAdapter extends RecyclerView.Adapter<NoticeAdapter.EmployeeViewHolder> {
private Wind wind;
private ArrayList<Notice> dataList;
private Main main;
private Date currentTime = Calendar.getInstance().getTime();
private RecyclerItemClickListener recyclerItemClickListener;
public NoticeAdapter(ArrayList<Notice> dataList, Main main, Wind wind, RecyclerItemClickListener recyclerItemClickListener) {
this.dataList = dataList;
this.main = main;
this.wind = wind;
this.recyclerItemClickListener = recyclerItemClickListener;
}
#Override
public EmployeeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.single_view_row, parent, false);
return new EmployeeViewHolder(view);
}
#Override
public void onBindViewHolder(EmployeeViewHolder holder, #SuppressLint("RecyclerView") final int position) {
if(getAddressMap()!=null){holder.txtNoticeAddress.setText("Loc: "+getAddressMap());}else{holder.txtNoticeAddress.setText("Loc: Unknown location");}
holder.imageIcon.setImageURI(Uri.parse("android.resource://com.locweather/drawable/i"+dataList.get(position).getIcon()));
holder.txtNoticeWind.setText("Wind: "+roundUp(+wind.getSpeed(),1)+"m/s, "+arrow());
holder.txtNoticeTempMain.setText(roundUp(+main.getTemp(),1)+"°C");
holder.txtNoticeWeather.setText(dataList.get(position).getWeather()+" : "+dataList.get(position).getInfo());
holder.txtNoticeTemp.setText("Feels: "+roundUp(+main.getFeelsLike(),1)+"°C ");
holder.txtNoticeTime.setText(currentTime.toString());
holder.txtNoticeHumidity.setText("Humidity: "+main.getHumidity()+"%");
holder.txtNoticePressure.setText("Pressure: "+main.getPressure()+"hPa");
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recyclerItemClickListener.onItemClick(dataList.get(position));
}
});
}
#Override
public int getItemCount() {
return dataList.size();
}
class EmployeeViewHolder extends RecyclerView.ViewHolder {
ImageView imageIcon;
TextView txtNoticeWeather, txtNoticeTempMain,txtNoticeTemp, txtNoticeHumidity,txtNoticeAddress,txtNoticePressure,txtNoticeWind,txtNoticeTime;
EmployeeViewHolder(View itemView) {
super(itemView);
imageIcon=itemView.findViewById(R.id.image_icon);
txtNoticeTime= itemView.findViewById(R.id.txt_time);
txtNoticeWind= itemView.findViewById(R.id.txt_notice_wind);
txtNoticeAddress= itemView.findViewById(R.id.txt_notice_title);
txtNoticeWeather = itemView.findViewById(R.id.txt_notice_weather);
txtNoticeTemp = itemView.findViewById(R.id.txt_notice_temp);
txtNoticeHumidity = itemView.findViewById(R.id.txt_notice_humidity);
txtNoticePressure = itemView.findViewById(R.id.txt_notice_pressure);
txtNoticeTempMain = itemView.findViewById(R.id.txt_notice_temp_main);
}
}
This is my recyclerview
This works only when network is enabled
The question is how to set this data right from RecyclerView (or other way) to my Room DataBase when network is enabled by Onclick SaveButton to create other recyclerview and set data there, to get it offline later.
I'm trying to create Entity
#Entity
public class WeatherData {
#PrimaryKey(autoGenerate = true)
private long id;
private String address;
private Double windSpeed;
private Integer windDegree;
private String datalistIcon;
private String datalistInfo;
private String datalistWeather;
private Double mainTemp;
private Double mainFeel;
private Integer mainHumidity;
private Integer mainPressure;
private String time;
private Double locLat;
private Double locLon;
public WeatherData(){}
#Ignore
public WeatherData(String address, Double windSpeed, Integer windDegree, String datalistIcon,String datalistInfo,String datalistWeather, Double mainTemp,Double mainFeel,Integer mainHumidity,Integer mainPressure,String time,LatLng currentLocation,Double locLat,Double locLon) {
this.address = address;
this.windSpeed = windSpeed;
this.windDegree = windDegree;
this.datalistIcon=datalistIcon;
this.datalistInfo=datalistInfo;
this.datalistWeather=datalistWeather;
this.mainTemp=mainTemp;
this.mainFeel=mainFeel;
this.mainHumidity=mainHumidity;
this.mainPressure=mainPressure;
this.time=time;
this.locLat=locLat;
this.locLon=locLon;
}
Dao
#Dao
public interface WeatherDataDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
void saveAll(List<WeatherData> weathers);
#Insert(onConflict = OnConflictStrategy.REPLACE)
void save(WeatherData weather);
#Update
void update(WeatherData weather);
#Delete
void delete(WeatherData weather);
#Query("SELECT * FROM WeatherData")
LiveData<List<WeatherData>> findAll();
}
and DataBase
#Database(entities = {WeatherData.class}, version = 1)
public abstract class WeatherDatabase extends RoomDatabase {
public static WeatherDatabase INSTANCE;
public abstract WeatherDataDao weatherDao();
private static final Object sLock = new Object();
public static WeatherDatabase getInstance(Context context) {
synchronized (sLock) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
WeatherDatabase.class, "Weathers.db")
.allowMainThreadQueries()
.build();
}
return INSTANCE;
}
}
Which way do I need to create it?
Create an #Entity Notice which is your data type to be stored in your Room DB.
Create a View Model which is attached to your Activity/Fragment where you need to show this list.
Use your ViewModel to store the list from API into your Room DB.
Create a LiveData which observes on the DB and sends the updated list to the other view.
Code for Saving Data in DB. This needs to be run on Background Thread.
public static void saveNoticeList(Context context, List<Notice> noticeList) {
if (context != null && noticeList != null) {
RoomDatabaseCreator.getInstance(context)
.getDatabase()
.noticeDao()
.saveNotices(noticeList);
}
}
// For Saving in background you can use RxJava, I am using a new thread for simplification
backgroundHandler.post(() -> {
saveNoticeList(getActivity(), dataList);
});
ViewModel
public class NoticeViewModel extends AndroidViewModel {
public MutableLiveData<List<Notice>> mNoticesLiveData = new MutableLiveData<>();
private Context mContext;
public NoticeViewModel(final Application application) {
super(application);
mContext = application.getApplicationContext();
mNoticesLiveData = Transformations.switchMap(databaseCreated,
(Function<Boolean, LiveData<List<Notice>>) isDbCreated -> {
if (!Boolean.TRUE.equals(isDbCreated)) { // Not needed here, but watch out for null
//noinspection unchecked
return ABSENT;
} else {
return databaseCreator.getDatabase()
.noticedao()
.getSavedNotices();
}
}
});
public LiveData<List<Notice> getNoticeLiveData() {
return mNoticesLiveData;
}
}
Activity Code where you need to show the saved data
//1. Initialize the viewModel
NoticeViewModel viewModel = ViewModelProviders.of(this).get(NoticeViewModel.class);
//2. Subscribe to the saved notices live-data to get updates in your view
viewModel.getNoticeLiveData().observe(this
list -> {
if (list.isEmpty()) {
return;
}
// Add the list in your adapter
});
I have Class Orders:
public class Order extends RealmObject {
#PrimaryKey
#SerializedName("Id")
private int id;
#SerializedName("Contractor")
private Contractor contractor;
#SerializedName("ItemAmounts")
private RealmList<ItemAmount> itemsAmounts = new RealmList<>();
#SerializedName("ModificationDate")
private Date modificationDate;
#SerializedName("ExportDate")
private Date exportDate;
#SerializedName("Export")
private boolean exportStatus;
#SerializedName("User")
private User user;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Contractor getContractor() {
return contractor;
}
public void setContractor(Contractor contractor) {
this.contractor = contractor;
}
public RealmList<ItemAmount> getItemsAmounts() {
return itemsAmounts;
}
public void setItemsAmounts(RealmList<ItemAmount> itemsAmounts) {
this.itemsAmounts = itemsAmounts;
}
public Date getModificationDate() {
return modificationDate;
}
public void setModificationDate(Date modificationDate) {
this.modificationDate = modificationDate;
}
public Date getExportDate() {
return exportDate;
}
public void setExportDate(Date exportDate) {
this.exportDate = exportDate;
}
public boolean isExportStatus() {
return exportStatus;
}
public void setExportStatus(boolean exportStatus) {
this.exportStatus = exportStatus;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
And i Create any new order save to Realm:
public void insertOrUpdate(Order order) {
Order orderToCompare = realm.where(Order.class)
.equalTo("id", order.getId()).findFirst();
realm.beginTransaction();
if (orderToCompare == null) {
Order orderRealm = realm.createObject(Order.class, order.getId());
orderRealm.setExportStatus(order.isExportStatus());
orderRealm.setContractor(order.getContractor());
orderRealm.setModificationDate(order.getModificationDate());
} else if (!orderToCompare.equals(order)) {
realm.copyToRealmOrUpdate(order);
}
realm.commitTransaction();
}
All my Orders have List of ItemAmount and ItemAmount have single item(Items is also contains in Realm) and his amount. So when i try change the amount of item in one order all my amount in others ItemAmount is updated. Below its function which I update the amount:
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
itemPosition = position;
AlertDialog.Builder builder = new AlertDialog.Builder(OrderItemsActivity.this);
View mView = getLayoutInflater().inflate(R.layout.change_amount, null);
builder.setView(mView);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
Button changeAmountButton = (Button) mView.findViewById(R.id.changeAmountButton);
final EditText setAmountEditText = (EditText) mView.findViewById(R.id.setAmountEditText);
changeAmountButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (setAmountEditText.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(), "Pole nie może być puste", Toast.LENGTH_SHORT).show();
} else {
orderDAO = new OrderDAO();
orderDAO.updateAmountOfItem(Integer.parseInt(setAmountEditText.getText().toString()), itemPosition, selectedOrderId);
itemAmounts.clear();
alertDialog.dismiss();
prepareOrderData();
}
}
});
}
public void updateAmountOfItem(int amount, int itemPosition, int orderId) {
realm.beginTransaction();
Order orderToCompare = realm.where(Order.class)
.equalTo("id", orderId).findFirst();
orderToCompare = realm.copyFromRealm(orderToCompare);
RealmList<ItemAmount> itemAmounts = orderToCompare.getItemsAmounts();
ItemAmount itemAmount = itemAmounts.get(itemPosition);
itemAmount.setAmount(amount);
itemAmounts.set(itemPosition,itemAmount);
orderToCompare.setItemsAmounts(itemAmounts);
realm.insertOrUpdate(orderToCompare);
realm.commitTransaction();
}
How fix it? Because i need update only one instance, not all of them.
I want to store the data in a ArrayList and access it in another class,but when when I access the arraylist,the arraylist.size() is 0.Means I didn't access the same arraylist. Somebody please tell me what I doing wrong.
Here is my POJO class
public class item {
private String name;
private String body;
private String profileImage;
public Item(){
}
public Item(String body,String name,String profileImage){
this.body = body;
this.name = name;
this.profileImage = profileImage;
}
//Getter and setter
Here is how I store the data in Class A,which I checked,is successfully insert it to the arraylist.
Class A
List<Item> items = new ArrayList<>();
Item item = new Item();
item.setBody(body);
item.setName(name);
item.setProfileImage(profileImage);
items.add(item);
The problem is in Class B when I access the item.size() it return value 0,means that I didnt access to the same arraylist.
Here is what I done in Class B
List<Item>items = new ArrayList<>();
Log.d("ListSize",String.valueOf(items.size()));
I tried this which I done in RecycleView before,but this doesnt work,cause my Class B is a Fragment activity
public Class B(Context mContext, List<Item> items) {
this.mContext = mContext;
this.items = items;
}
So what is the correct way for me initialize the arraylist which I save data to in Class A in Class B?
change class like this:
public class Item implements Parcelable{
private String name;
private String body;
private String profileImage;
public Item(){
}
public Item(Parcel in) {
name = in.readString();
body = in.readString();
profileImage = in.readString();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(body);
dest.writeString(profileImage);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Item> CREATOR = new Parcelable.Creator<Item>() {
#Override
public Item createFromParcel(Parcel in) {
return new Item(in);
}
#Override
public Item[] newArray(int size) {
return new Item[size];
}
};
public Item(String body,String name,String profileImage){
this.body = body;
this.name = name;
this.profileImage = profileImage;
}
Now in Class A:
ArrayList<Item> mDATA = new ArrayList<>();
/****** add values in array list ****/
Intent i = new Intent(CLASS_A.this, CLASS_B.class);
i.putParcelableArrayListExtra("ARRAY_DATA", mDATA);
startActivity(i);
Now in Class B, get list:
Intent intent = getIntent();
ArrayList<Item> mDATAFROMA = new ArrayList<>();
try {
mDATAFROMA = intent.getParcelableArrayListExtra("ARRAY_DATA");
Log.d("ListSize",String.valueOf(mDATAFROMA.size()));
} catch (Exception e) {
e.printStackTrace();
}
For fragement pass like:
Bundle args = new Bundle();
args.putParcelableArrayList("GET_LIST", (ArrayList<? extends Parcelable>) mDATA);
fragmentDemo.setArguments(args);
And in fragment fetch:
ArrayList<Item> mDATAFROMA = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle pb=getArguments();
mDATAFROMA = pb.getParcelableArrayList("GET_LIST");
}
I'm trying to use blog id to get JSON object from server. At the moment I'm getting this error
java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()
on a null object reference`.How do I use the post Id to get the full content what am I doing wrong. Please help!!!
MyBlog Adapter:
public class MyBlogAdapter extends RecyclerView.Adapter<BlogViewHolder> {
List<BlogResponse> postsList;
Context context;
public static String blog_Id, blogID;
private LayoutInflater inflater;
public MyBlogAdapter(Context context, List<BlogResponse> postsList){
this.context = context;
this.inflater = LayoutInflater.from(context);
this.postsList = postsList;
}
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_view,parent, false);
return new BlogViewHolder(view);
}
#Override
public void onBindViewHolder(BlogViewHolder holder, int position) {
final BlogResponse posts= postsList.get(position);
holder.summary.setText(posts.getBlogExcerpt().trim().toString());
holder.title.setText(posts.getBlogTitle().trim().toString());
// Glide.with(context).load(posts.getBlogThumbnail()).into(holder.cover);
holder.blogHolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AnotherSingleView.class);
blog_Id = posts.getBlogId();
intent.putExtra(blogID,blog_Id);
Log.d("MyblogAdapter","Please check blog Id: "+blog_Id);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
Log.d("MyBlogAdapter,","getItemCount"+postsList.size());
return postsList == null ? (0) : postsList.size();
}
}
SecondActivity:
public class AnotherSingleView extends AppCompatActivity {
String postID;
int position;
public TextView blogTitle,blogSub,blogContent;
public ImageView blogPic;
List<SingleBlogPost> singleBlogPosts;
SingleBlogPost singleBlogPost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another_single_view);
Intent intent = getIntent();
Bundle showBlogId = intent.getExtras();
postID = showBlogId.getString(blogID);
Log.d("AnotherSingleView","Please check blog Id: "+postID);
singleBlogPosts = new ArrayList<>();
blogContent = (TextView)findViewById(R.id.blog_content);
blogSub = (TextView) findViewById(R.id.blog_subtitle);
blogTitle =(TextView) findViewById(R.id.blog_title);
blogPic =(ImageView) findViewById(R.id.blog_pix);
singlePostDisplay();
}
private void singlePostDisplay() {
BlogaPI api = ApiClient.getBlogInterface();
Call<List<SingleBlogPost>> call = api.postResponse(postID);
call.enqueue(new Callback<List<SingleBlogPost>>() {
#Override
public void onResponse(Call<List<SingleBlogPost>> call, Response<List<SingleBlogPost>> response) {
singleBlogPosts = response.body();
if (singleBlogPosts != null && !singleBlogPosts.isEmpty() ){
for (SingleBlogPost posts : singleBlogPosts){
Log.d("AnotherSingleView","Please check RESPONSE: "+response.body().toString());
blogTitle.setText(posts.getBlogTitle());
blogSub.setText(posts.getBlogSubtitle());
blogContent.setText(posts.getBlogContent());
// Glide.with(AnotherSingleView.this).load(singlepost.getBlogMedimg()).into(blogPic);
}
}
else{
Toast.makeText(AnotherSingleView.this, "Something is empty", Toast.LENGTH_SHORT).show();
} }
#Override
public void onFailure(Call<List<SingleBlogPost>> call, Throwable t) {
Toast.makeText(AnotherSingleView.this, "check again: "+t.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
Interface:
public interface BlogaPI {
#GET("blog")
Call<BlogList> response();
#GET("post/{blog_id}")
Call<List<SingleBlogPost>> postResponse(#Path("blog_id") String blog_id);
//Call<List<SingleBlogPost>> postResponse();
}
SingleBlogPost:
public class SingleBlogPost {
#SerializedName("blog_id")
#Expose
private String blogId;
#SerializedName("blog_title")
#Expose
private String blogTitle;
#SerializedName("blog_subtitle")
#Expose
private String blogSubtitle;
#SerializedName("blog_excerpt")
#Expose
private String blogExcerpt;
#SerializedName("blog_content")
#Expose
private String blogContent;
#SerializedName("blog_thumbnail")
#Expose
private String blogThumbnail;
#SerializedName("blog_medimg")
#Expose
private String blogMedimg;
#SerializedName("category_title")
#Expose
private String categoryTitle;
public SingleBlogPost(String blogId,String blogTitle, String blogSubtitle, String blogExcerpt,
String blogContent, String blogThumbnail, String blogMedimg, String categoryTitle){
this.blogId = blogId;
this.blogTitle = blogTitle;
this.blogSubtitle = blogSubtitle;
this.blogExcerpt = blogExcerpt;
this.blogContent = blogContent;
this.blogThumbnail = blogThumbnail;
this.blogMedimg = blogMedimg;
this.categoryTitle = categoryTitle;
}
public String getBlogId() {
return blogId;
}
public void setBlogId(String blogId) {
this.blogId = blogId;
}
public String getBlogTitle() {
return blogTitle;
}
public void setBlogTitle(String blogTitle) {
this.blogTitle = blogTitle;
}
public String getBlogSubtitle() {
return blogSubtitle;
}
public void setBlogSubtitle(String blogSubtitle) {
this.blogSubtitle = blogSubtitle;
}
public String getBlogExcerpt() {
return blogExcerpt;
}
public void setBlogExcerpt(String blogExcerpt) {
this.blogExcerpt = blogExcerpt;
}
public String getBlogContent() {
return blogContent;
}
public void setBlogContent(String blogContent) {
this.blogContent = blogContent;
}
public String getBlogThumbnail() {
return blogThumbnail;
}
public void setBlogThumbnail(String blogThumbnail) {
this.blogThumbnail = blogThumbnail;
}
public String getBlogMedimg() {
return blogMedimg;
}
public void setBlogMedimg(String blogMedimg) {
this.blogMedimg = blogMedimg;
}
public String getCategoryTitle() {
return categoryTitle;
}
public void setCategoryTitle(String categoryTitle) {
this.categoryTitle = categoryTitle;
}
}
Check if the server response is different then null before you do a enhanced for like this:
if(singleBlogPosts!= null) {
for (SingleBlogPosts posts : singleBlogPosts){
Log.d("AnotherSingleView","Please check RESPONSE: "+response.body().toString());
blogTitle.setText(posts.getBlogTitle());
blogSub.setText(posts.getBlogSubtitle());
blogContent.setText(posts.getBlogContent());
// Glide.with(AnotherSingleView.this).load(singlepost.getBlogMedimg()).into(blogPic);
}
}
you question was list iterator,but we can`t see you list use on anywhere,i guess you may be use recyclerView on you data has not get,because get data was asynchronous.try to use data if you can sure it is existing.