I did recyclerView, and each child is "Detail".
I am now asking how to sent user to the next activity when he click on "Detail". For each click send him to the other activity.
private List<ParentObject> initData() {
TitleCreator titleCreator = TitleCreator.get(this);
List<TitleParent> titles = titleCreator.getAll();
List<ParentObject> parentObject = new ArrayList<>();
for(TitleParent title:titles)
{
List<Object> childList = new ArrayList<>();
childList.add(new TitleChild("Detail", ""));
title.setChildObjectList(childList);
parentObject.add(title);
}
return parentObject;
}
This is code where I put every child to be "Detail".
I had four Parent titles and of course four child titles. When user click on first *Parent title it open child title. Question is when user click on this child title how to send him to the other activity?
Here is my adapter fil
package com.example.user_pc.glavnastranicaprojekat.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import
com.bignerdranch.expandablerecyclerview.Adapter.ExpandableRecyclerAdapter;
import com.bignerdranch.expandablerecyclerview.Model.ParentObject;
import com.example.user_pc.glavnastranicaprojekat.models.TitleChild;
import com.example.user_pc.glavnastranicaprojekat.models.TitleParent;
import com.example.user_pc.glavnastranicaprojekat.R;
import
com.example.user_pc.glavnastranicaprojekat.ViewHolders.TitleChildViewHolder;
import
com.example.user_pc.glavnastranicaprojekat.ViewHolders.TitleParentViewHolder;
import java.util.List;
public class MyAdapter extends
ExpandableRecyclerAdapter<TitleParentViewHolder,TitleChildViewHolder> {
LayoutInflater inflater;
public MyAdapter(Context context, List<ParentObject> parentItemList) {
super(context, parentItemList);
inflater = LayoutInflater.from(context);
}
#Override
public TitleParentViewHolder onCreateParentViewHolder(ViewGroup viewGroup) {
View view = inflater.inflate(R.layout.list_parent,viewGroup,false);
return new TitleParentViewHolder(view);
}
#Override
public TitleChildViewHolder onCreateChildViewHolder(ViewGroup viewGroup) {
View view = inflater.inflate(R.layout.list_child,viewGroup,false);
return new TitleChildViewHolder(view);
}
#Override
public void onBindParentViewHolder(TitleParentViewHolder titleParentViewHolder, int i, Object o) {
TitleParent title = (TitleParent)o;
titleParentViewHolder._textView.setText(title.getTitle());
}
#Override
public void onBindChildViewHolder(TitleChildViewHolder titleChildViewHolder, int i, Object o) {
TitleChild title = (TitleChild)o;
titleChildViewHolder.option1.setText(title.getOption1());
titleChildViewHolder.option2.setText(title.getOption2());
}
}
TitleParent.java :
package com.example.user_pc.glavnastranicaprojekat.models;
import com.bignerdranch.expandablerecyclerview.Model.ParentObject;
import java.util.List;
import java.util.UUID;
public class TitleParent implements ParentObject{
private List<Object> mChildrenList;
private UUID _id;
private String title;
public TitleParent(String title) {
this.title = title;
_id = UUID.randomUUID();
}
public UUID get_id() {
return _id;
}
public void set_id(UUID _id) {
this._id = _id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public List<Object> getChildObjectList() {
return mChildrenList;
}
#Override
public void setChildObjectList(List<Object> list) {
mChildrenList = list;
}
}
Here is TitleChild.java:
package com.example.user_pc.glavnastranicaprojekat.models;
public class TitleChild {
public String option1;
public String option2;
public TitleChild(String option1, String option2) {
this.option1 = option1;
this.option2 = option2;
}
public String getOption1() {
return option1;
}
public void setOption1(String option1) {
this.option1 = option1;
}
public String getOption2() {
return option2;
}
public void setOption2(String option2) {
this.option2 = option2;
}
}
TitleCreator.java:
package com.example.user_pc.glavnastranicaprojekat.models;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
public class TitleCreator {
static TitleCreator _titleCreator;
List<TitleParent> _titleParents;
public TitleCreator(Context context) {
_titleParents = new ArrayList<>();
TitleParent title = new TitleParent(String.format("Coppa"));
_titleParents.add(title);
TitleParent title1 = new TitleParent(String.format("Levante"));
_titleParents.add(title1);
TitleParent title2 = new TitleParent(String.format("Monument"));
_titleParents.add(title2);
TitleParent title3 = new TitleParent(String.format("Comming soon"));
_titleParents.add(title3);
}
public static TitleCreator get(Context context)
{
if(_titleCreator == null)
_titleCreator = new TitleCreator(context);
return _titleCreator;
}
public List<TitleParent> getAll() {
return _titleParents;
}
}
TitleChildViewHolder:
package com.example.user_pc.glavnastranicaprojekat.ViewHolders;
import android.view.View;
import android.widget.TextView;
import com.bignerdranch.expandablerecyclerview.ViewHolder.ChildViewHolder;
import com.example.user_pc.glavnastranicaprojekat.R;
public class TitleChildViewHolder extends ChildViewHolder {
public TextView option1,option2;
public TitleChildViewHolder(View itemView) {
super(itemView);
option1 = itemView.findViewById(R.id.option1);
option2 = itemView.findViewById(R.id.option2);
}
}
TitleParentViewHolder:
package com.example.user_pc.glavnastranicaprojekat.ViewHolders;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import com.bignerdranch.expandablerecyclerview.ViewHolder.ParentViewHolder;
import com.example.user_pc.glavnastranicaprojekat.R;
public class TitleParentViewHolder extends ParentViewHolder {
public TextView _textView;
public ImageButton _imageButton;
public TitleParentViewHolder(View itemView) {
super(itemView);
_textView = itemView.findViewById(R.id.parentTitle);
_imageButton = itemView.findViewById(R.id.expandArrow);
}
}
MainActivity:
RecyclerView recyclerView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
recyclerView = findViewById(R.id.myRecyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
MyAdapter adapter = new MyAdapter(this,initData());
adapter.setParentClickableViewAnimationDefaultDuration();
adapter.setParentAndIconExpandOnClick(true);
recyclerView.setAdapter(adapter);
}
private List<ParentObject> initData() {
TitleCreator titleCreator = TitleCreator.get(this);
List<TitleParent> titles = titleCreator.getAll();
List<ParentObject> parentObject = new ArrayList<>();
for(TitleParent title:titles)
{
List<Object> childList = new ArrayList<>();
childList.add(new TitleChild("Detail", ""));
title.setChildObjectList(childList);
parentObject.add(title);
}
return parentObject;
}
titleChildViewHolder.itemView.setOnClickListener(
new OnClickListener(View v){
context.startActivity(new Intent(context,DESTINATION_ACTIVITY.class)));
}
);
Put this code inside onBindChildViewHolder
try something like this:
#Override
public void onBindChildViewHolder(TitleChildViewHolder titleChildViewHolder, int i, Object o) {
TitleChild title = (TitleChild)o;
titleChildViewHolder.option1.setText(title.getOption1());
titleChildViewHolder.option2.setText(title.getOption2());
titleChildViewHolder.option1.setOnClickListener(
new OnClickListener(View v){
context.startActivity(new Intent(context,ACTIVITY_TO_LAUNCH.class)));
}
);
}
If you need you can set an equivalent OnClickListener also on titleChildViewHolder.option2
Maybe you could add a container of views option1 and option2 so you could set only one ClickListener
Related
This question already has an answer here:
Firebase Android ListView not being displayed
(1 answer)
Closed 1 year ago.
I am creating an Android Grocery Shop App, where firestore used. I am implementing a Nested Recyclerview where I have done coding for showing data from firestore to recycler view by Category Names.
But, all products are showing in the recyclerview, like the below image. Data is not sorted by category names.
Codes
ProductsAdapterbyCategory.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.chattthedev.shoppingguskara.Activities.Models.ProductsModel;
import com.chattthedev.shoppingguskara.R;
import java.util.List;
public class ProductsAdapterbyCategory extends
RecyclerView.Adapter<ProductsAdapterbyCategory.ViewHolderForProducts> {
List<ProductsModel> productsbycat;
Context context;
public ProductsAdapterbyCategory(List<ProductsModel> productsbycat, Context context) {
this.productsbycat = productsbycat;
this.context = context;
}
#NonNull
#Override
public ViewHolderForProducts onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.singleforitembycat, parent, false);
ViewHolderForProducts viewHolderForProducts = new ViewHolderForProducts(view);
return viewHolderForProducts;
}
#Override
public void onBindViewHolder(#NonNull ViewHolderForProducts holder, int position) {
holder.catnameinprod.setText(productsbycat.get(position).getItemCategory());
ProductsAdapter2 productsAdapter2 = new ProductsAdapter2(productsbycat, context);
holder.recyclerViewinprod.setHasFixedSize(true);
holder.recyclerViewinprod.setLayoutManager(new LinearLayoutManager(context, RecyclerView.HORIZONTAL, false));
holder.recyclerViewinprod.setAdapter(productsAdapter2);
holder.recyclerViewinprod.setNestedScrollingEnabled(false);
}
#Override
public int getItemCount() {
return (productsbycat != null ? productsbycat.size() : 0);
}
public class ViewHolderForProducts extends RecyclerView.ViewHolder {
public TextView catnameinprod;
public Button viewmoreinprod;
public RecyclerView recyclerViewinprod;
public ViewHolderForProducts(#NonNull View itemView) {
super(itemView);
catnameinprod = itemView.findViewById(R.id.catnameforfetch);
viewmoreinprod = itemView.findViewById(R.id.buttviewmoreitem);
recyclerViewinprod = itemView.findViewById(R.id.recyclerprodfetch);
}
}
}
ProductsAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.chattthedev.shoppingguskara.Activities.Models.ProductsModel;
import com.chattthedev.shoppingguskara.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class ProductsAdapter2 extends RecyclerView.Adapter {
List<ProductsModel> productsModelList;
Context context;
public ProductsAdapter2(List<ProductsModel> productsModelList, Context context) {
this.productsModelList = productsModelList;
this.context = context;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.horizontal_scroll_item, parent, false);
ProductsAdapter2.ViewHolderClass2 viewHolderClass = new ProductsAdapter2.ViewHolderClass2(view);
return viewHolderClass;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
ProductsAdapter2.ViewHolderClass2 viewHolderClass = (ProductsAdapter2.ViewHolderClass2) holder;
ProductsModel productsModel = productsModelList.get(position);
viewHolderClass.proditemname.setText(productsModel.getItemname());
viewHolderClass.proditemprice.setText("Rs." + productsModel.getItemActualPrice() + "/-");
Picasso.get().load(productsModel.getItemImageUrl()).into(viewHolderClass.prodimage);
}
public void updatelist(List<ProductsModel> models){
productsModelList = new ArrayList<>();
productsModelList.addAll(models);
notifyDataSetChanged();
}
public Filter getFilter(){
return new Filter() {
private List<ProductsModel> filtered = new ArrayList<ProductsModel>();
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString().toLowerCase();
filtered.clear();
if(charString.isEmpty()){
filtered = productsModelList;
//filteredCUG = CUG;
}
else{
for (ProductsModel cug : productsModelList){
if( cug.getItemname().toLowerCase().contains(charString)){
filtered.add(cug);
}
}
//filteredCUG = filtered;
}
FilterResults filterResults = new FilterResults();
filterResults.values = filtered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
productsModelList = (List<ProductsModel>) filterResults.values;
notifyDataSetChanged();
}
};
}
#Override
public int getItemCount() {
return productsModelList.size();
}
public class ViewHolderClass2 extends RecyclerView.ViewHolder {
TextView proditemname, proditemprice, productitemdiscount;
ImageView prodimage;
public ViewHolderClass2(#NonNull View itemView) {
super(itemView);
proditemname = itemView.findViewById(R.id.hsproducttitle);
proditemprice = itemView.findViewById(R.id.hsproductprice);
prodimage = itemView.findViewById(R.id.hsproductimage);
productitemdiscount = itemView.findViewById(R.id.hsproductdesc);
}
}
}
HomeFragment.java only providing the recyclerview fetching data function from firestore
private void getproductsfromcats() {
Query query = collectionReference.orderBy("ItemCategory");
query.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for (QueryDocumentSnapshot queryDocumentSnapshot : queryDocumentSnapshots) {
ProductsModel productsModel = queryDocumentSnapshot.toObject(ProductsModel.class);
productsModelList2.add(productsModel);
}
productsAdapterbyCategory = new
ProductsAdapterbyCategory(productsModelList2,view.getContext());
product_items_for_cat.setAdapter(productsAdapterbyCategory);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(view.getContext(), "Failed", Toast.LENGTH_SHORT).show();
}
});
}
ProductsModel.java
public class ProductsModel {
private String ItemActualPrice, ItemCategory, ItemDescription, ItemDiscount,
ItemFinalPrice, ItemId, ItemImageUrl, ItemStock, ItemUnit, ItemWeight,
Itemname;
public ProductsModel() {
}
public ProductsModel(String itemActualPrice, String itemCategory, String
itemDescription, String itemDiscount, String itemFinalPrice, String itemId,
String itemImageUrl, String itemStock, String itemUnit, String itemWeight,
String itemname) {
ItemActualPrice = itemActualPrice;
ItemCategory = itemCategory;
ItemDescription = itemDescription;
ItemDiscount = itemDiscount;
ItemFinalPrice = itemFinalPrice;
ItemId = itemId;
ItemImageUrl = itemImageUrl;
ItemStock = itemStock;
ItemUnit = itemUnit;
ItemWeight = itemWeight;
Itemname = itemname;
}
public String getItemActualPrice() {
return ItemActualPrice;
}
public void setItemActualPrice(String itemActualPrice) {
ItemActualPrice = itemActualPrice;
}
public String getItemCategory() {
return ItemCategory;
}
public void setItemCategory(String itemCategory) {
ItemCategory = itemCategory;
}
public String getItemDescription() {
return ItemDescription;
}
public void setItemDescription(String itemDescription) {
ItemDescription = itemDescription;
}
public String getItemDiscount() {
return ItemDiscount;
}
public void setItemDiscount(String itemDiscount) {
ItemDiscount = itemDiscount;
}
public String getItemFinalPrice() {
return ItemFinalPrice;
}
public void setItemFinalPrice(String itemFinalPrice) {
ItemFinalPrice = itemFinalPrice;
}
public String getItemId() {
return ItemId;
}
public void setItemId(String itemId) {
ItemId = itemId;
}
public String getItemImageUrl() {
return ItemImageUrl;
}
public void setItemImageUrl(String itemImageUrl) {
ItemImageUrl = itemImageUrl;
}
public String getItemStock() {
return ItemStock;
}
public void setItemStock(String itemStock) {
ItemStock = itemStock;
}
public String getItemUnit() {
return ItemUnit;
}
public void setItemUnit(String itemUnit) {
ItemUnit = itemUnit;
}
public String getItemWeight() {
return ItemWeight;
}
public void setItemWeight(String itemWeight) {
ItemWeight = itemWeight;
}
public String getItemname() {
return Itemname;
}
public void setItemname(String itemname) {
Itemname = itemname;
}
}
Firestore DB Structure Screenshot
you can create two different collection(meat,fruit) in firestore
I have a problem with my android app.
I have a RecyclerView and a click handler for it. When you click on a list item, one of the class fields is displayed on the screen. Also inside there is a button, by clicking on which another class field should be displayed. But the program throws a NullPointerException. I understand why this is happening, but I cannot understand how to modify my code, please help.
here is my Adapeter
package com.skorbr.stock_yandextest;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class TickerAdapter extends RecyclerView.Adapter<TickerAdapter.TickerViewHolder> {
private List<Ticker> tickers;
private Context context;
// listener
private final Listener onTickerClickListener;
// constructor
public TickerAdapter(List<Ticker> tickers, Listener onTickerClickListener) {
this.tickers = tickers;
this.onTickerClickListener = onTickerClickListener;
}
#NonNull
#Override
public TickerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.recycler_stock_item, parent, false);
// click on RecyclerView
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onTickerClickListener.onTickerClick((Ticker) v.getTag());
}
});
// click on button
view.findViewById(R.id.button_favourite).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onTickerClickListener.onFavouriteClick((Ticker) v.getTag());
}
});
return new TickerViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull TickerViewHolder holder, int position) {
Ticker ticker = tickers.get(position);
holder.bind(ticker);
holder.itemView.setTag(ticker);
}
#Override
public int getItemCount() {
return tickers.size();
}
class TickerViewHolder extends RecyclerView.ViewHolder {
private TextView ticker;
private TextView tickerFull;
private TextView price;
private TextView priceChange;
private ImageView tickerLogo;
private Button favouriteButton;
public TickerViewHolder(#NonNull final View itemView) {
super(itemView);
ticker = itemView.findViewById(R.id.ticker);
tickerFull = itemView.findViewById(R.id.ticker_full);
price = itemView.findViewById(R.id.price);
priceChange = itemView.findViewById(R.id.price_change);
tickerLogo = itemView.findViewById(R.id.ticker_image);
favouriteButton = itemView.findViewById(R.id.button_favourite);
}
// заполнение элемента RecyclerView данными
void bind(Ticker ticker) {
double priceNow = ticker.getPrice();
double priceDayAgo = ticker.getPriceDayAgo();
String sign = "";
this.ticker.setText(ticker.getTicker());
this.tickerFull.setText(ticker.getTickerFull());
this.price.setText("$" + priceNow);
// check price
if (priceNow < priceDayAgo) {
sign = "-";
this.priceChange.setTextColor(context.getResources().getColor(R.color.colorRedDm));
} else if (priceNow > priceDayAgo) {
sign = "+";
this.priceChange.setTextColor(context.getResources().getColor(R.color.colorGreenDm));
}
// check favourites
if (ticker.isFavourite()) {
this.favouriteButton.setBackground(context.getDrawable(R.drawable.ic_favourite_on));
} else {
this.favouriteButton.setBackground(context.getDrawable(R.drawable.ic_favourite_off));
}
this.priceChange.setText(String.format("%s$%.2f (%.2f%%)", sign, Math.abs(priceNow-priceDayAgo), Math.abs(priceNow/priceDayAgo*100-100)));
this.tickerLogo.setImageResource(ticker.getTickerLogo());
}
}
interface Listener {
void onTickerClick(Ticker ticker);
void onFavouriteClick(Ticker ticker);
}
}
Here is my Main Activity
package com.skorbr.stock_yandextest;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class ActivityMain extends Activity {
private RecyclerView tickerList;
private TickerAdapter tickerAdapter;
private List<Ticker> tickerListList;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tickerListList = tickerList();
tickerList = findViewById(R.id.tickers_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
tickerList.setLayoutManager(layoutManager);
tickerAdapter = new TickerAdapter(tickerListList, new TickerAdapter.Listener() {
#Override
public void onTickerClick(Ticker ticker) {
Toast.makeText(ActivityMain.this, ticker.getTickerFull(), Toast.LENGTH_SHORT);
}
#Override
public void onFavouriteClick(Ticker ticker) {
Toast.makeText(ActivityMain.this, ticker.getTicker(), Toast.LENGTH_SHORT);
}
});
tickerList.setAdapter(tickerAdapter);
}
private List<Ticker> tickerList() {
List<Ticker> tickers = new ArrayList<>();
tickers.add(new Ticker("APPL", "Apple Inc.", 138.54, 150.22, R.drawable.apple_logo, false));
tickers.add(new Ticker("TSLA", "Tesla Motors", 904.37, 753.92, R.drawable.tesla_logo, true));
tickers.add(new Ticker("GOOGL", "Alphabel Class A", 1845.90, 1845.90, R.drawable.google_logo, false));
return tickers;
}
}
Here is my class for data
package com.skorbr.stock_yandextest;
public class Ticker {
private String ticker;
private String tickerFull;
private double price;
private double priceDayAgo;
private int tickerLogo;
private boolean isFavourite;
public Ticker(String ticker, String tickerFull, double price, double priceDayAgo, int tickerLogo, boolean isFavourite) {
this.ticker = ticker;
this.tickerFull = tickerFull;
this.price = price;
this.priceDayAgo = priceDayAgo;
this.tickerLogo = tickerLogo;
this.isFavourite = isFavourite;
}
public String getTicker() {
return ticker;
}
public String getTickerFull() {
return tickerFull;
}
public double getPrice() {
return price;
}
public double getPriceDayAgo() {
return priceDayAgo;
}
public int getTickerLogo() {
return tickerLogo;
}
public boolean isFavourite() {
return isFavourite;
}
public void setFavourite(boolean favourite) {
isFavourite = favourite;
}
}
#Override
public void onBindViewHolder(#NonNull TickerViewHolder holder, int position) {
Ticker ticker = tickers.get(position);
holder.bind(ticker);
holder.itemView.setTag(ticker);
// add this line
holder.favouriteButton.setTag(ticker);
}
Or you can modify the onCreateViewHolder()
view.findViewById(R.id.button_favourite).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// instead of
onTickerClickListener.onFavouriteClick((Ticker) v.getTag());
// use
onTickerClickListener.onFavouriteClick((Ticker) view.getTag());
}
});
I need to open another activity from a custom adapter, just like a list and then when I click on that, it will take to another activity and get a data from database and show it in the text view,
the problem is in SearchAdapter.java in the context.startActivity(intent);
here's my searchAdapter.java
package Adapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
//import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.manualdiagnosiskeperawatan.R;
import com.example.manualdiagnosiskeperawatan.isiDiagnosis;
import java.util.List;
import Model.Daftar;
class SearchViewHolder extends RecyclerView.ViewHolder{
public TextView judul, diagnosis;
public SearchViewHolder(View itemView) {
super(itemView);
judul = itemView.findViewById(R.id.judul);
diagnosis = itemView.findViewById(R.id.textViewIsi);
}
}
public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder>
{
private Context context;
private List<Daftar> data;
public SearchAdapter(Context context, List<Daftar> data) {
this.context = context;
this.data = data;
}
#Override
public SearchViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.layout_item,parent,false);
return new SearchViewHolder(itemView);
}
#Override
public void onBindViewHolder(final SearchViewHolder holder, final int position)
{
holder.judul.setText(data.get(position).getJudul());
//open activity
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, data.get(position).getDiagnosis(),Toast.LENGTH_SHORT).show();
//this code, isn't working
Intent intent = new Intent(context, isiDiagnosis.class);
intent.putExtra("did",data.get(position).getDid());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return data.size();
}
}
and here is my isiDiagnosis.java which will be opened when I clicked the list from the SearchAdapter.java
package com.example.manualdiagnosiskeperawatan;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.TextView;
import com.mancj.materialsearchbar.MaterialSearchBar;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import Adapter.SearchAdapter;
import Database.Database;
import Model.Daftar;
public class isiDiagnosis extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
Database database;
List<Daftar> daftars = new ArrayList<>();
private TextView judul, diagnosis;
private String DID = "judul";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_isi_diagnosis);
DID = getIntent().getStringExtra("judul");
database = new Database(this);
diagnosis = (TextView) findViewById(R.id.textViewIsi);
//init DB
loadData(DID);
}
private void loadData(String did) {
//i don't really know how to code, just see from the youtube, so i made this myself
// database.getDiagnosis();
// String diagnosis = daftars.get(database.getDiagnosis());
// database.getDiagnosis(diagnosis.setText());
}
}
here's my searchDiagnosis.java
package com.example.manualdiagnosiskeperawatan;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.ListViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Adapter;
import android.widget.ListView;
import com.mancj.materialsearchbar.MaterialSearchBar;
import java.util.ArrayList;
import java.util.List;
import Adapter.SearchAdapter;
import Database.Database;
public class searchDiagnosis extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
Database database;
MaterialSearchBar materialSearchBar;
List<String> suggestList = new ArrayList<>();
#Override
protected void onStart() {
super.onStart();
adapter = new SearchAdapter(getBaseContext(),database.getDaftar());
recyclerView.setAdapter(adapter);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_diagnosis);
//init view
recyclerView = (RecyclerView) findViewById(R.id.recycler_search);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
materialSearchBar =(MaterialSearchBar) findViewById(R.id.search_bar);
//init DB
database = new Database(this);
//Setup search bar
materialSearchBar.setHint("Search");
materialSearchBar.setCardViewElevation(10);
loadSuggestList();
materialSearchBar.addTextChangeListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
List<String> suggest = new ArrayList<>();
for(String search:suggestList){
if(search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if(!enabled) {
// recyclerView.setAdapter(adapter);
//if close Search, just restore default
adapter = new SearchAdapter(getBaseContext(),database.getDaftar());
recyclerView.setAdapter(adapter);
}
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString());
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
//Init adapter default set all result
adapter = new SearchAdapter(this,database.getDaftar());
}
private void startSearch(String text) {
adapter = new SearchAdapter(this,database.getDataByJudul(text));
recyclerView.setAdapter(adapter);
}
private void loadSuggestList() {
suggestList = database.getJudul();
materialSearchBar.setLastSuggestions(suggestList);
}
}
here's my Daftar.class
package Model;
public class Daftar {
public int id;
public String did, judul, diagnosis;
public Daftar(int id,String did, String judul, String diagnosis) {
this.id = id;
this.did = did;
this.judul = judul;
this.diagnosis = diagnosis;
}
public Daftar() {
}
public int getId() {
return id;
}
public String getDid() {
return did;
}
public void setDid(String did) {
this.did = did;
}
public void setId(int id) {
this.id = id;
}
public String getJudul() {
return judul;
}
public void setJudul(String judul) {
this.judul = judul;
}
public String getDiagnosis() {
return diagnosis;
}
public void setDiagnosis(String diagnosis) {
this.diagnosis = diagnosis;
}
}
Look I don't know what kind of database is this, but I know that you are not receiving the intent extra correctly:
In your isiDiagnosis:
............
//get the did like this
DID = getIntent().getStringExtra("did");
.......
loadData(DID);
//loading the data is up to you according to the database
private void loadData(String did) {.........}
I knew my question is similar with the other questioners but it was not solved my problem because I am still curious about how to declare the item which is the children of parent node. This is my stucture data on my Firebase:
I've tried to created the classes for my case:
DolanIemClass.java
private String name_tourism;
private String location_tourism;
private String info_tourism;
private String telepon;
private String url_photo;
private String url_photo_collage;
private double lat_location_tourism;
private double lng_location_tourism;
public DolanItemClass() {
//constructor untuk panggilan ke DataSnapshot.getValue
}
public DolanItemClass(String name_tourism, String location_tourism, String info_tourism, String telepon, String url_photo, String url_photo_collage, double lat_location_tourism, double lng_location_tourism) {
this.name_tourism = name_tourism;
this.location_tourism = location_tourism;
this.info_tourism = info_tourism;
this.telepon = telepon;
this.url_photo = url_photo;
this.url_photo_collage = url_photo_collage;
this.lat_location_tourism = lat_location_tourism;
this.lng_location_tourism = lng_location_tourism;
}
public String getUrl_photo_collage() {
return url_photo_collage;
}
public String getName_tourism() {
return name_tourism;
}
public void setName_tourism(String name_tourism) {
this.name_tourism = name_tourism;
}
public String getLocation_tourism() {
return location_tourism;
}
public void setLocation_tourism(String location_tourism) {
this.location_tourism = location_tourism;
}
public String getInfo_tourism() {
return info_tourism;
}
public void setInfo_tourism(String info_tourism) {
this.info_tourism = info_tourism;
}
public String getTelepon() {
return telepon;
}
public void setTelepon(String telepon) {
this.telepon = telepon;
}
public String getUrl_photo() {
return url_photo;
}
public void setUrl_photo(String url_photo) {
this.url_photo = url_photo;
}
public double getLat_location_tourism() {
return lat_location_tourism;
}
public void setLat_location_tourism(double lat_location_tourism) {
this.lat_location_tourism = lat_location_tourism;
}
public double getLng_location_tourism() {
return lng_location_tourism;
}
public void setLng_location_tourism(double lng_location_tourism) {
this.lng_location_tourism = lng_location_tourism;
}
}
DolanViewHolder.class
import android.view.View;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
public class DolanImageViewHolder extends RecyclerView.ViewHolder {
private final ImageView imgDetailData;
public DolanImageViewHolder(#NonNull View itemView) {
super(itemView);
imgDetailData = itemView.findViewById(R.id.img_detail_item_data);
}
public void showImageArray(DolanItemClass dolanItemClass){
Glide.with(itemView.getContext()).load(dolanItemClass.getUrl_photo_collage()).into(imgDetailData);
}
}
And the activity class to show the list
package co.id.roningrum.firebasearrayimage;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class DetailTouristListAct extends AppCompatActivity {
private ImageView imgDetailData;
private TextView tvNamaDetail, tvAlamatDetail, tvDescDetail;
private RecyclerView rvImageDetailCollages;
private DatabaseReference databaseReference;
private ValueEventListener valueEventListener;
private FirebaseRecyclerAdapter<DolanItemClass, DolanImageViewHolder> firebaseRecyclerAdapter;
public static final String EXTRA_WISATA_KEY = "tourist_key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_tourist_list);
String touristKey = getIntent().getStringExtra(EXTRA_WISATA_KEY);
if(touristKey == null){
throw new IllegalArgumentException("Must pass Extra");
}
imgDetailData = findViewById(R.id.img_detail_data);
tvNamaDetail = findViewById(R.id.tv_name_detail);
tvAlamatDetail = findViewById(R.id.tv_info_tourism_detail);
tvDescDetail = findViewById(R.id.tv_address_detail);
rvImageDetailCollages = findViewById(R.id.rv_photo_collage);
databaseReference = FirebaseDatabase.getInstance().getReference().child("Tourism").child(touristKey);
rvImageDetailCollages.setLayoutManager(new GridLayoutManager(this, 2));
LoadDetailData();
}
private void ShowCollage() {
Query query = databaseReference.child("url_photo_collage");
FirebaseRecyclerOptions<DolanItemClass> options = new FirebaseRecyclerOptions.Builder<DolanItemClass>()
.setQuery(query, DolanItemClass.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<DolanItemClass, DolanImageViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull DolanImageViewHolder dolanImageViewHolder, int i, #NonNull DolanItemClass dolanItemClass) {
dolanImageViewHolder.showImageArray(dolanItemClass);
}
#NonNull
#Override
public DolanImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new DolanImageViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image_data, parent, false));
}
};
firebaseRecyclerAdapter.notifyDataSetChanged();
rvImageDetailCollages.setAdapter(firebaseRecyclerAdapter);
}
private void LoadDetailData() {
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DolanItemClass dolanItemClass = dataSnapshot.getValue(DolanItemClass.class);
tvNamaDetail.setText(dolanItemClass.getName_tourism());
tvAlamatDetail.setText(dolanItemClass.getLocation_tourism());
tvDescDetail.setText(dolanItemClass.getInfo_tourism());
Glide.with(getApplicationContext()).load(dolanItemClass.getUrl_photo()).into(imgDetailData);
ShowCollage();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
databaseReference.addValueEventListener(eventListener);
valueEventListener = eventListener;
}
#Override
protected void onStart() {
super.onStart();
LoadDetailData();
if(firebaseRecyclerAdapter!=null){
firebaseRecyclerAdapter.startListening();
}
}
#Override
protected void onStop() {
super.onStop();
databaseReference.removeEventListener(valueEventListener);
}
}
I expected that I can show the array of url_photo_collage node but I don't have any idea for my item class.
The problem in your code is that your url_photo_collage field is declared in your DolanItemClass class of type String while in your database is an array. To solve this, change the type of your field from String to a List<String> and get it accordingly in your adapter.
My code was worked perfectly just before i added header image, after that listview not showing the given datas.
These are the main pages.
Can anyone help please.Any help will be appreciated.
MyRecyclerViewAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class MyRecyclerViewAdapter extends
RecyclerView.Adapter<MyRecyclerViewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<DataObject> mDataset;
private static MyClickListener myClickListener;
Context context;
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
String[] data;
public MyRecyclerViewAdapter(String[] data) {
this.data = data;
}
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView desc;
ImageView image,head_img;
public DataObjectHolder(View itemView) {
super(itemView);
desc = (TextView) itemView.findViewById(R.id.description);
image = (ImageView) itemView.findViewById(R.id.image);
head_img=(ImageView) itemView.findViewById(R.id.header_img);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
this.mDataset = myDataset;
this.context=context;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if(viewType==TYPE_ITEM) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview, parent, false);
//DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return new DataObjectHolder(view);
}
else if (viewType==TYPE_HEADER){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header, parent, false);
//DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return new DataObjectHolder(view);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
if(holder instanceof VHItem) {
holder.desc.setText(mDataset.get(position ).getDescription());
// holder.image.setText(mDataset.get(position).getImage_url());
Picasso.with(holder.image.getContext()).load(mDataset.get(position ).getImage_url()).into(holder.image);
}
else if(holder instanceof VHHeader){
holder.head_img.setImageResource(R.drawable.cam);
}
}
public void addItem(DataObject dataObj, int index) {
mDataset.add(dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return (null != mDataset ? mDataset.size() + 1 : 0);
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
private class VHItem extends DataObjectHolder {
public VHItem(View itemView) {
super(itemView);
}
}
private class VHHeader extends DataObjectHolder {
public VHHeader(View itemView) {
super(itemView);
}
}
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
private boolean isPositionHeader(int position) {
return position == 0;
}
private String getItem(int position) {
return data[position - 1];
}
}
Profile2Fragment.java
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class Profile2Fragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "RecyclerViewActivity";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.recycler_view, container, false);
mRecyclerView = (RecyclerView) rootview.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyRecyclerViewAdapter(getDataSet());
mRecyclerView.setAdapter(mAdapter);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
return rootview;
}
private ArrayList<DataObject> getDataSet() {
ArrayList<DataObject> results = new ArrayList<DataObject>();
for (int index = 0; index < 1; index++) {
DataObject obj = new DataObject("Lorem Ipsum is simply\n dummy text of the", "https://mediastream.jumeirah.com/webimage/heroactual//globalassets/global/hotels-and-resorts/dubai/madinat-jumeirah/restaurants/pierchic/madinat-jumeirah-pierchic-inside-restaurant-02-hero.jpg");
results.add(obj);
obj = new DataObject("Lorem Ipsum is simply\n dummy text of the", "https://photos.smugmug.com/Portfolio/i-HBk894k/0/db7f0344/L/The%20Black%20Couches-L.jpg");
results.add(obj);
obj = new DataObject("Lorem Ipsum is simply\n dummy text of the", "http://thesmartlocal.com/images/easyblog_images/82/Pollen.jpg");
results.add(obj);
}
return results;
}
}
DataObject.java
public class DataObject {
private String description;
private String image_url;
DataObject (String text1, String text2){
description = text1;
image_url = text2;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
try to change return statement
`return new DataObjectHolder(view);
to your specific Class like return
new VHHeader(view);
and
return new VHItem(view);
in onCreateViewHolder..