I have a server that I get data from and display on a RecyclerView, When I click on the view, it is expected to open another activity that will display the full detail of the specific view, therefore the Id of the post is used to get the full content. I passed the id by intent to the new Activity, am getting an error:
Caused by: java.lang.IndexOutOfBoundsException: Invalid index 34, size is 0
how do I make the Api call to get the content using id?
This is the full content for the item with id=34
{
"blog_id": "34",
"blog_title": "BLOG TITLE",
"blog_subtitle": "Inspiration for Article Intro Effects",
"blog_excerpt": "<p>Lorem ipsum dolor sit amet, veniam vidisse periculis ei mel, an nam malis nostrud euripidis. Ad invidunt explicari repudiandae qui, ut quo dolor sadipscing. Est laudem offendit ei. Id mentitum asse",
"blog_content": "<p>We may define a food to be any substance which will repair the functional waste of the body, increase its growth, or maintain the heat, muscular, and nervous energy.</p>\r\n<p>In its most comprehensive sense, the oxygen of the air is a food; as although it is admitted by the lungs, it passes into the blood, and there re-acts upon the other food which has passed through the stomach. It is usual, however, to restrict the term food to such nutriment as enters the body by the intestinal canal. Water is often spoken of as being distinct from food, but for this there is no sufficient reason.</p>\r\n<p>Many popular writers have divided foods into flesh-formers, heat-givers, and bone-formers. Although attractive from its simplicity, this classification will not
"blog_thumbnail": "https://watchnollywood.ml/app/templates/default/",
"blog_medimg": "https://watchnollywood.ml/app/templates/default/images/medium_57d4789461f8b.jpg",
"category_title": "General"
}
BlogAdapter:
public class MyBlogAdapter extends RecyclerView.Adapter<BlogViewHolder> {
List<BlogPost> postsList;
List<SingleBlogPost> singleBlogPosts;
Context context;
private LayoutInflater inflater;
static String blog_Id;
static String blogID;
public MyBlogAdapter(Context context, List<BlogPost> 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.blog_post_item,parent, false);
return new BlogViewHolder(view);
}
#Override
public void onBindViewHolder(BlogViewHolder holder, int position) {
BlogPost 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();
}
}
AnotherSingleView:
public class AnotherSingleView extends AppCompatActivity {
String postID;
int position = 0;
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() {
singleBlogPost = singleBlogPosts.get(Interger.parseInt(postID));
String post_id = singleBlogPost.getBlogId();
if (postID.matches(post_id)){
BlogaPI api = ApiClient.getBlogInterface();
Call<List<SingleBlogPost>> call = api.postResponse();
call.enqueue(new Callback<List<SingleBlogPost>>() {
#Override
public void onResponse(Call<List<SingleBlogPost>> call, Response<List<SingleBlogPost>> response) {
singleBlogPosts = response.body();
blogContent.setText(singleBlogPost.getBlogContent());
blogSub.setText(singleBlogPost.getBlogSubtitle());
blogTitle.setText(singleBlogPost.getBlogTitle());
Glide.with(AnotherSingleView.this).load(singleBlogPost.getBlogMedimg()).into(blogPic);
}
#Override
public void onFailure(Call<List<SingleBlogPost>> call, Throwable t) {
}
});
}
}
}
Interface:
public interface BlogRequestInterface {
#GET("blog")
Call<BlogApi> getMyBlog();
#GET("post/{id}")
Call<List<SingleBlogPost>> getSinglePost();
}
Pojo class:
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 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;
}
I do not recommend adding ClickListeners on onBindViewHolder. My onCreateViewHolder does something like this.
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.blog_post_item,parent, false);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do stuff
}
});
return new BlogViewHolder(view);
}
And if you need position or list object for that you can refer to this link http://androidshenanigans.blogspot.com.tr/2015/02/viewholder-pattern-common-mistakes.html
Hope it helps.
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 successfully populated my recycleview from mysql database and I want to implement search filter on it. I have seen some examples and tried to implement it. I know i'm close but cant get it properly to work.
My current progress is when I try to search something the whole recycle view goes blank and nothing happens after that.
Here are my java code:
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getHotelDetails();
mylearningAdapters1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.reviews_list);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
inputSearch = (EditText)findViewById(R.id.searchBar);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// filter your list from your input
filter(s.toString());
//you can use runnable postDelayed like 500 ms to delay search text
}
});
}
void filter(String text){
List<MyHotelReviewAdapter> temp = new ArrayList();
for(MyHotelReviewAdapter d: mylearningAdapters){
//or use .equal(text) with you want equal match
//use .toLowerCase() for better matches
if(d.getHotel_user().contains(text)){
temp.add(d);
}
}
//update recyclerview
RecyclerViewMyHotelReviewAdapter rc = new RecyclerViewMyHotelReviewAdapter(mylearningAdapters);
rc.updateList(temp);
}
Here is my Recycleview adapter class code:
RecyclerViewMyHotelReviewAdapter.java
public class RecyclerViewMyHotelReviewAdapter extends RecyclerView.Adapter<RecyclerViewMyHotelReviewAdapter.LearningHolder> {
static Context context;
public static List<MyHotelReviewAdapter> mylearningAdapters;
public RecyclerViewMyHotelReviewAdapter(List<MyHotelReviewAdapter> mylearningAdapters, Context context){
super();
this.mylearningAdapters = mylearningAdapters;
this.context = context;
}
public RecyclerViewMyHotelReviewAdapter(List<MyHotelReviewAdapter> mylearningAdapters) {
}
#Override
public RecyclerViewMyHotelReviewAdapter.LearningHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_hotel_details, parent, false);
LearningHolder learningHolder = new LearningHolder(view);
//RecyclerViewModuleAdapter.ModuleHolder moduleHolder = new RecyclerViewModuleAdapter.ModuleHolder(view);
return learningHolder;
}
#SuppressLint("NewApi")
#Override
public void onBindViewHolder(RecyclerViewMyHotelReviewAdapter.LearningHolder holder, int position) {
final MyHotelReviewAdapter mylearningAdapter1 = mylearningAdapters.get(position);
int t = 4;
String a = mylearningAdapter1.getHotel_People();
int c = t + Integer.parseInt(a);
//Toast.makeText(context, ""+c, Toast.LENGTH_SHORT).show();
holder.hotel_user.setText(mylearningAdapter1.getHotel_user());
holder.hotel_dateIn.setText(mylearningAdapter1.getHotel_CheckIn());
holder.hotel_dateOut.setText(mylearningAdapter1.getHotel_CheckOut());
holder.total.setText(String.valueOf("Guests: "+c));
holder.htlName.setText(mylearningAdapter1.getHotel_name());
holder.id.setText(mylearningAdapter1.getHotel_id());
//holder.english_d.setText(mylearningAdapter1.getEnglish());
}
public void updateList(List<MyHotelReviewAdapter> list){
mylearningAdapters = list;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return mylearningAdapters.size();
}
public class LearningHolder extends RecyclerView.ViewHolder {
String deleteBooking = "http://site2test.in/OxygenClub/mobileapp/delete_booking_careTaker.php";
AppCompatTextView hotel_user, hotel_dateIn, hotel_dateOut, htlName, total, id;
Button checkIn, checkOut;
public LearningHolder(View itemView) {
super(itemView);
hotel_user = (AppCompatTextView)itemView.findViewById(R.id.name);
hotel_dateIn = (AppCompatTextView)itemView.findViewById(R.id.checkin);
hotel_dateOut = (AppCompatTextView)itemView.findViewById(R.id.checkout);
htlName = (AppCompatTextView)itemView.findViewById(R.id.hotelName);
total = (AppCompatTextView)itemView.findViewById(R.id.totalPeople);
id = (AppCompatTextView)itemView.findViewById(R.id.hotelId);
}
}
}...
My DataHolder class.
public class MyHotelReviewAdapter {
public String Hotel_People;
public String Hotel_CheckIn;
public String Hotel_CheckOut;
public String Hotel_User;
public String Hotel_Name;
public String Hotel_Id;
public String getHotel_CheckIn() {
return this.Hotel_CheckIn;
}
public void setHotel_CheckIn(String hotel_checkIn) {
this.Hotel_CheckIn = hotel_checkIn;
}
public String getHotel_CheckOut() {
return this.Hotel_CheckOut;
}
public void setHotel_CheckOut(String hotel_checkOut) {
this.Hotel_CheckOut = hotel_checkOut;
}
public String getHotel_People() {
return this.Hotel_People;
}
public void setHotel_People(String hotel_people) {
this.Hotel_People = hotel_people;
}
public String getHotel_user() {
return this.Hotel_User;
}
public void setHotel_user(String hotel_user) {
this.Hotel_User = hotel_user;
}
public String getHotel_name(){
return this.Hotel_Name;
}
public void setHotel_name(String hotel_name){
this.Hotel_Name = hotel_name;
}
public String getHotel_id(){
return this.Hotel_Id;
}
public void setHotel_id(String hotel_id){
this.Hotel_Id = hotel_id;
}
}
I want to search my data by Hotel_user. I have coded the value of getHotel_user in filter function.
I have 5 fragments inside my activity where one fragment stays active at one time. Clicking on a recyclerview item opens another fragment and puts current fragment in the backstack.
The same code was working fine some days ago, but now the app is throwing NotSerializableException whenever I click the home button to put the app in background. I have tried putting the initializing the variables inside onStart and then giving the null value in onStop but that didn't work.
Fragment Code:
public class PaperListFragment extends Fragment implements Serializable {
private static final String TAG = "PaperListFragment";
private static final String QUESTIONS_FRAGMENT_TAG = "questions_fragment";
private static final String ADD_PAPER_FRAGMENT_TAG = "add_paper_fragment";
private OnFragmentActiveListener mOnFragmentActiveListener;
private TextView mHeadingText;
private Bundle mOutState;
private FirebaseAuth mAuth;
private DatabaseReference mDatabaseReference;
private ProgressBar mProgressBar;
private OnItemClickListener mOnItemClickListener;
private FloatingActionButton mFab;
private RecyclerView mRecyclerViewPaper;
private ArrayList<Paper> mPaperList = new ArrayList<>();
private Subject mSubject = new Subject();
private Exam mExam = new Exam();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_recycler_list, container, false);
mProgressBar = (ProgressBar) rootView.findViewById(R.id.progressbar_news);
mFab = (FloatingActionButton) rootView.findViewById(R.id.floatingActionButton);
mProgressBar.setVisibility(View.VISIBLE);
Log.d(TAG, "onCreateView: Fragment created");
mAuth = FirebaseAuth.getInstance();
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
if (mAuth.getCurrentUser() == null) {
startActivity(new Intent(getActivity(), LoginActivity.class));
getActivity().finish();
return null;
}
if (getArguments() != null) {
mOnFragmentActiveListener = (OnFragmentActiveListener) getArguments().getSerializable(Keys.FRAGMENT_ACTIVE_LISTENER);
mSubject = (Subject) getArguments().getSerializable(Keys.SUBJECT_KEY);
mExam = (Exam) getArguments().getSerializable(Keys.EXAMS_KEY);
}
mRecyclerViewPaper = (RecyclerView) rootView.findViewById(R.id.recycler_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()) {
#Override
public boolean canScrollVertically() {
return false;
}
};
mRecyclerViewPaper.setLayoutManager(layoutManager);
Log.d(TAG, "onCreateView: Layout Manager Set.");
mFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startAddPaperFragment();
}
});
mOnItemClickListener = new OnItemClickListener() {
#Override
public void onItemClicked(RecyclerView.ViewHolder holder, int position) {
Log.d(TAG, "onItemClicked: Clicked item position is: "+ position);
QuestionListFragment questionFragment = new QuestionListFragment();
questionFragment.setRetainInstance(true);
startFragment(position, questionFragment, QUESTIONS_FRAGMENT_TAG);
}
#Override
public void OnItemLongClicked(RecyclerView.ViewHolder holder, int position) {
}
};
mHeadingText = (TextView) rootView.findViewById(R.id.heading_textview);
mHeadingText.setText(mExam.getExam_name()+" > "+ mSubject.getSubject_name());
if (mOutState != null) {
mPaperList = (ArrayList<Paper>) mOutState.getSerializable(Keys.PAPER_LIST_KEY);
updateUI();
} else {
updateUIFromDatabase();
}
return rootView;
}
private void startFragment(int position, Fragment fragment, String fragmentTag) {
Paper paper = new Paper();
if (mPaperList.size() > 0) {
paper = mPaperList.get(position);
}
Bundle args = new Bundle();
args.putSerializable(Keys.EXAMS_KEY, mExam);
args.putSerializable(Keys.SUBJECT_KEY, mSubject);
args.putSerializable(Keys.PAPER, paper);
args.putSerializable(Keys.FRAGMENT_ACTIVE_LISTENER, mOnFragmentActiveListener);
fragment.setArguments(args);
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right);
fragmentTransaction.replace(R.id.questions_fragment_container, fragment, fragmentTag);
fragmentTransaction.addToBackStack(fragmentTag);
fragmentTransaction.commit();
}
private void startAddPaperFragment() {
AddPaperFragment addPaperFragment = new AddPaperFragment();
addPaperFragment.setRetainInstance(true);
startFragment(0, addPaperFragment, ADD_PAPER_FRAGMENT_TAG);
}
private void updateUIFromDatabase() {
if (getArguments() != null){
Exam exam = (Exam) getArguments().getSerializable(Keys.EXAMS_KEY);
Subject subject = (Subject) getArguments().getSerializable(Keys.SUBJECT_KEY);
DatabaseReference paperReference =
mDatabaseReference
.child(Keys.APP_DATA_KEY)
.child(Keys.EXAM_PAPERS)
.child(exam.getExam_name())
.child(subject.getSubject_name());
Query query = paperReference.orderByChild(Keys.TIME_ADDED);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mPaperList.clear();
for (DataSnapshot paperChild : dataSnapshot.getChildren()) {
mPaperList.add(paperChild.getValue(Paper.class));
}
updateUI();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
private void updateUI() {
PaperRecyclerAdapter adapter = new PaperRecyclerAdapter(
getActivity(),
mRecyclerViewPaper,
mPaperList,
mOnItemClickListener
);
mRecyclerViewPaper.setAdapter(adapter);
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onResume() {
super.onResume();
if (getArguments()!=null){
mOnFragmentActiveListener.onFragmentActive(
this,
"Topics"
);
}
}
#Override
public void onPause() {
super.onPause();
mOutState = new Bundle();
mOutState.putSerializable(Keys.PAPER_LIST_KEY, mPaperList);
}
}
Exception:
2018-12-26 17:49:38.344 14834-14834/in.crazybytes.bankmaniaadmin E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.crazybytes.bankmaniaadmin, PID: 14834
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = in.crazybytes.bankmaniaadmin.activities.QuestionsActivity)
at android.os.Parcel.writeSerializable(Parcel.java:1526)
at android.os.Parcel.writeValue(Parcel.java:1474)
at android.os.Parcel.writeArrayMapInternal(Parcel.java:723)
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1408)
at android.os.Bundle.writeToParcel(Bundle.java:1133)
at android.os.Parcel.writeBundle(Parcel.java:763)
at android.support.v4.app.FragmentState.writeToParcel(FragmentState.java:124)
at android.os.Parcel.writeTypedArray(Parcel.java:1306)
at android.support.v4.app.FragmentManagerState.writeToParcel(FragmentManager.java:639)
at android.os.Parcel.writeParcelable(Parcel.java:1495)
at android.os.Parcel.writeValue(Parcel.java:1401)
at android.os.Parcel.writeArrayMapInternal(Parcel.java:723)
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1408)
at android.os.Bundle.writeToParcel(Bundle.java:1133)
at android.os.Parcel.writeBundle(Parcel.java:763)
at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3697)
at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3768)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.io.NotSerializableException: com.google.firebase.auth.internal.zzj
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1224)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1584)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1549)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1472)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1218)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1584)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1549)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1472)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1218)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
at android.os.Parcel.writeSerializable(Parcel.java:1521)
at android.os.Parcel.writeValue(Parcel.java:1474)
at android.os.Parcel.writeArrayMapInternal(Parcel.java:723)
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1408)
at android.os.Bundle.writeToParcel(Bundle.java:1133)
at android.os.Parcel.writeBundle(Parcel.java:763)
at android.support.v4.app.FragmentState.writeToParcel(FragmentState.java:124)
at android.os.Parcel.writeTypedArray(Parcel.java:1306)
at android.support.v4.app.FragmentManagerState.writeToParcel(FragmentManager.java:639)
at android.os.Parcel.writeParcelable(Parcel.java:1495)
at android.os.Parcel.writeValue(Parcel.java:1401)
at android.os.Parcel.writeArrayMapInternal(Parcel.java:723)
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1408)
at android.os.Bundle.writeToParcel(Bundle.java:1133)
at android.os.Parcel.writeBundle(Parcel.java:763)
at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3697)
at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3768)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Note: The weird thing is that one of fragment has the exact same code and is hosted inside the same activity, but when that fragment is active and app goes to background, interestingly the app is not crashing.
**Exam Model Class:
package in.crazybytes.bankmaniaadmin.models;
import java.io.Serializable;
public class Exam implements Serializable {
private String mExam_name;
private String mExam_key;
private Long mTime_added;
private int mNum_subjects;
private int mNum_questions;
public Exam(String exam_name, String exam_key, Long time_added, int num_subjects, int num_questions) {
mExam_name = exam_name;
mExam_key = exam_key;
mTime_added = time_added;
mNum_subjects = num_subjects;
mNum_questions = num_questions;
}
public Exam() {
}
public String getExam_name() {
return mExam_name;
}
public void setExam_name(String exam_name) {
mExam_name = exam_name;
}
public String getExam_key() {
return mExam_key;
}
public void setExam_key(String exam_key) {
mExam_key = exam_key;
}
public Long getTime_added() {
return mTime_added;
}
public void setTime_added(Long time_added) {
mTime_added = time_added;
}
public int getNum_subjects() {
return mNum_subjects;
}
public void setNum_subjects(int num_subjects) {
mNum_subjects = num_subjects;
}
public int getNum_questions() {
return mNum_questions;
}
public void setNum_questions(int num_questions) {
mNum_questions = num_questions;
}
}
Paper Model Class
package in.crazybytes.bankmaniaadmin.models;
import java.io.Serializable;
public class Paper implements Serializable {
private String mPaper_name;
private String mPaper_key;
private Long mTime_added;
private int mNum_questions;
public Paper(String paper_name, String paper_key, Long time_added, int num_questions) {
mPaper_name = paper_name;
mPaper_key = paper_key;
mTime_added = time_added;
mNum_questions = num_questions;
}
public Paper() {
}
public String getPaper_key() {
return mPaper_key;
}
public void setPaper_key(String paper_key) {
mPaper_key = paper_key;
}
public Long getTime_added() {
return mTime_added;
}
public void setTime_added(Long time_added) {
mTime_added = time_added;
}
public int getNum_questions() {
return mNum_questions;
}
public void setNum_questions(int num_questions) {
mNum_questions = num_questions;
}
public String getPaper_name() {
return mPaper_name;
}
public void setPaper_name(String paper_name) {
mPaper_name = paper_name;
}
}
Subject Model Class:
package in.crazybytes.bankmaniaadmin.models;
import java.io.Serializable;
public class Subject implements Serializable {
private String mSubject_name;
private String mSubject_key;
private Long mTime_added;
private int mNum_papers;
private int mNum_questions;
public Subject(String subject_name, String subject_key, Long time_added, int num_papers, int num_questions) {
mSubject_name = subject_name;
mSubject_key = subject_key;
mTime_added = time_added;
mNum_papers = num_papers;
mNum_questions = num_questions;
}
public Subject() {
}
public String getSubject_name() {
return mSubject_name;
}
public void setSubject_name(String subject_name) {
mSubject_name = subject_name;
}
public String getSubject_key() {
return mSubject_key;
}
public void setSubject_key(String subject_key) {
mSubject_key = subject_key;
}
public Long getTime_added() {
return mTime_added;
}
public void setTime_added(Long time_added) {
mTime_added = time_added;
}
public int getNum_papers() {
return mNum_papers;
}
public void setNum_papers(int num_papers) {
mNum_papers = num_papers;
}
public int getNum_questions() {
return mNum_questions;
}
public void setNum_questions(int num_questions) {
mNum_questions = num_questions;
}
}
Somehow QuestionsActivity is getting into the fragment save state, even if you don't intend for that to happen. While QuestionsActivity is being serialized, another object that is not serializable is being encountered. That's why you see TextViews and other things attempting to get serialized because all the instance variables of QuestionsActivity get serialized by default.
My best guess for why this is happening is due to this line:
args.putSerializable(Keys.FRAGMENT_ACTIVE_LISTENER, mOnFragmentActiveListener);
But it's difficult to know for sure without seeing where OnFragmentActiveListener is defined. I'm assuming either QuestionsActivity implements OnFragmentActiveListener, or QuestionsActivity defines OnFragmentActiveListener as an inner class. Either way, if you put an OnFragmentActiveListener into fragment arguments, you will encounter an exception because you indirectly are storing the entire QuestionsActivity as a fragment arg too. When a fragment stops, all fragment args become part of the fragment save state. And that's the cause of the error.
I would suggest not passing the OnFragmentActiveListener around as a fragment arg. If the OnFragmentActiveListener comes from the activity, just use getActivity() to get a reference to the activity and then get a reference to the listener.
I also noticed PaperListFragment implements Serializable and I'm assuming you did the same thing for QuestionsActivity. You probably did this to get around compile errors. But this has led to runtime errors because the instance variables on both of these classes are not all serializable. So to avoid more runtime issues, I would suggest never having activities or fragments implement serializable because these classes are inherently not serializable due to their members.
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.
I want show image into RecyclerView and i should use this images from drawable folder. I write below codes, but show me this error :
java.lang.IllegalArgumentException: Unknown type class [I. You must provide a Model of a type for which there is a registered ModelLoader, if you are using a custom model, you must first call Glide#register with a ModelLoaderFactory for your custom model class
at com.bumptech.glide.RequestManager.loadGeneric(RequestManager.java:629)
at com.bumptech.glide.RequestManager.load(RequestManager.java:598)
at com.tellfa.colony.Adapters.ColoniesAdapter.onBindViewHolder(ColoniesAdapter.java:66)
at com.tellfa.colony.Adapters.ColoniesAdapter.onBindViewHolder(ColoniesAdapter.java:29)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5768)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5801)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5037)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4913)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2029)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1414)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1377)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:578)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3260)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3069)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3518)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1705)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1559)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1468)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1705)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1559)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1468)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2101)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1858)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1077)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5845)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at jav
Model codes:
public class MainDataModel implements Serializable {
private static final long serialVersionUID = 1L;
private String category;
private String categoryID;
private String categoryDescription;
private int[] categoryImages;
private TimeInterpolator interpolator;
public MainDataModel(String categoryID, String category, String categoryDescription, int[] categoryImages,
TimeInterpolator interpolator) {
this.categoryID = categoryID;
this.category = category;
this.categoryDescription = categoryDescription;
this.categoryImages = categoryImages;
this.interpolator = interpolator;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getCategoryID() {
return categoryID;
}
public void setCategoryID(String caategoryID) {
this.categoryID = caategoryID;
}
public String getCategoryDescription() {
return categoryDescription;
}
public void setCategoryDescription(String categoryDescription) {
this.categoryDescription = categoryDescription;
}
public TimeInterpolator getInterpolator() {
return interpolator;
}
public void setInterpolator(TimeInterpolator interpolator) {
this.interpolator = interpolator;
}
public int[] getCategoryImages() {
return categoryImages;
}
public void setCategoryImages(int[] categoryImages) {
this.categoryImages = categoryImages;
}
}
AsyncTask codes and set image :
public class ColoniesDataInfo {
private static Context mContext;
private String ServerAddress = ServerIP_colonies.getColoniesIP();
public void getColoniesDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress);
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
#Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
//String url = (String) params[0];
Request request = new Request.Builder()
.url(ServerAddress)
//.cacheControl(CacheControl.FORCE_NETWORK)
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("categories");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
String colID = postObject.getString("id");
String colTitle = postObject.getString("title");
String colDescription = postObject.getString("description");
final int[] colImages = {
R.drawable.colonies_image_food,
R.drawable.colonies_image_medical,
R.drawable.colonies_image_tecgnolegy,
R.drawable.colonies_image_entertenement,
R.drawable.colonies_image_car,
R.drawable.colonies_image_model,
R.drawable.colonies_image_sport,
};
Log.d("Data", "Colonies ID: " + colID);
Log.d("Data", "Colonies title: " + colTitle);
Log.d("Data", "Colonies Desc: " + colDescription);
Log.d("Data", "---------------------------------");
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(colID, colTitle, colDescription, colImages,
Utils.createInterpolator(Utils.BOUNCE_INTERPOLATOR)));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
} else {
Toast.makeText(mContext, "Empty", Toast.LENGTH_SHORT).show();
}
}
}
}
Adapter codes and set image into adapter :
public class ColoniesAdapter extends RecyclerView.Adapter<ColoniesAdapter.ViewHolder> {
private List<MainDataModel> mDateSet;
private Context mContext;
private SparseBooleanArray expandState = new SparseBooleanArray();
public ColoniesAdapter(Context context, List<MainDataModel> dataSet) {
this.mContext = context;
this.mDateSet = dataSet;
for (int i = 0; i < mDateSet.size(); i++) {
expandState.append(i, false);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.colonies_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.colonies_title.setText(mDateSet.get(position).getCategory());
holder.colonies_title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getPosition();
MainDataModel model = mDateSet.get(pos);
v.getContext().startActivity(new Intent(v.getContext(), Category_page.class)
.putExtra("categoryTitle", model.getCategory())
.putExtra("categoryID", model.getCategoryID()));
}
});
Glide.with(mContext)
.load(mDateSet.get(position).getCategoryImages())
.placeholder(R.drawable.post_image)
.crossFade()
.override(700, 400)
.into(holder.colonies_image);
holder.colonies_description.setText(mDateSet.get(position).getCategoryDescription());
holder.expandableLayout.setInterpolator(mDateSet.get(position).getInterpolator());
holder.expandableLayout.setExpanded(expandState.get(position));
holder.expandableLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
createRotateAnimator(holder.buttonLayout, 0f, 180f).start();
expandState.put(position, true);
}
#Override
public void onPreClose() {
createRotateAnimator(holder.buttonLayout, 180f, 0f).start();
expandState.put(position, false);
}
});
holder.buttonLayout.setRotation(expandState.get(position) ? 180f : 0f);
holder.buttonLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
onClickButton(holder.expandableLayout);
}
});
}
private void onClickButton(final ExpandableLayout expandableLayout) {
expandableLayout.toggle();
}
#Override
public int getItemCount() {
return mDateSet.size();
}
public void remove(int position) {
mDateSet.remove(position);
notifyItemRemoved(position);
}
public void clear() {
mDateSet.clear();
notifyDataSetChanged();
}
public void add(List<MainDataModel> models) {
mDateSet.addAll(models);
notifyDataSetChanged();
}
public void update(List<MainDataModel> models) {
mDateSet.clear();
mDateSet.addAll(models);
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView colonies_title, colonies_description;
private ImageView colonies_image;
private ExpandableLinearLayout expandableLayout;
private RelativeLayout buttonLayout;
public ViewHolder(View itemView) {
super(itemView);
colonies_title = (TextView) itemView.findViewById(R.id.colonies_colony_title_text);
colonies_image = (ImageView) itemView.findViewById(R.id.colonies_cover_image);
colonies_description = (TextView) itemView.findViewById(R.id.colonies_expandable_description_text);
buttonLayout = (RelativeLayout) itemView.findViewById(R.id.colonies_expandable_button);
expandableLayout = (ExpandableLinearLayout) itemView.findViewById(R.id.colonies_expandable_layout);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* v.getContext().startActivity(new Intent(v.getContext(), PostShow_page.class)
.putExtra("title", model.getTitle())
.putExtra("image", model.getThumbnail()));*/
}
});
}
}
public ObjectAnimator createRotateAnimator(final View target, final float from, final float to) {
ObjectAnimator animator = ObjectAnimator.ofFloat(target, "rotation", from, to);
animator.setDuration(300);
animator.setInterpolator(Utils.createInterpolator(Utils.LINEAR_INTERPOLATOR));
return animator;
}
}
How can i fix it?
First of all why are you loading all the array of images into a single imageView? Your method getCategoryImages() gives you an integer array of images. retrieve one by one corresponding to the position.
If the problem still persists you can refer to the below link with the same issue
https://github.com/bumptech/glide/issues/588
Glide.with(mContext)
.load(mDateSet.get(position).getCategoryImages()[position])
.placeholder(R.drawable.post_image)
.crossFade()
.override(700, 400)
.into(holder.colonies_image);
You are trying to load a list of ints and that is why Glide isn't working.
As you gave one ImageView as destination, only one image can be loaded there.
What you need to do is extract the image you wish to load and then pass it to Glide.