I want to create this card view inside recycler View.
I got this problem.I can't retrieve the data inside of the card views.
I want to whenever that Check Box is true, Get the data(Meal, price, and count which is in this example (1)) and add to the list in my Main Activity.
I am stuck on this for 6 hour straight. If someone know the solution please help. I am dying over here.
MainActivity:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
CardData data;
List<CardData> list=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Hawk.init(getApplicationContext()).build();
data = new CardData("Meal","1","12","http");
list.add(data);
recyclerView=(RecyclerView)findViewById(R.id.recycler_view);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
final RecyclerView.Adapter adapter=new MyAdapter(getApplicationContext(),list);
recyclerView.setAdapter(adapter);
}
}
Adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private List<CardData> data;
private Context context;
public MyAdapter(Context context,List<CardData> data){
this.data=data;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_contents,viewGroup,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(final MyViewHolder myViewHolder, final int i) {
myViewHolder.Meal.setText(data.get(i).Yemek);
myViewHolder.price.setText(data.get(i).Qiymet);
//Glide.with(context).load(data.get(i).url).into(myViewHolder.img);
myViewHolder.count.getText();
myViewHolder.card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myViewHolder.checkBox.setChecked(!myViewHolder.checkBox.isChecked());
data.get(i).checked = myViewHolder.checkBox.isChecked();
}
});
myViewHolder.add.setFocusable(true);
myViewHolder.remove.setFocusable(true);
myViewHolder.add.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String countS = myViewHolder.count.getText().toString();
int countI = Integer.valueOf(countS);
countI += 1;
String countN = String.valueOf(countI);
myViewHolder.count.setText(countN);
}
});
myViewHolder.remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String sayS = myViewHolder.count.getText().toString();
int sayI = Integer.valueOf(sayS);
if (sayI>0){
sayI -= 1;}
String sayN = String.valueOf(sayI);
myViewHolder.count.setText(sayN);
}
});
}
#Override
public int getItemCount() {
return data.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView Meal;
TextView price;
TextView count;
CardView card;
ImageView img;
CheckBox checkBox;
Button add;
Button remove;
MyViewHolder(View view){
super(view);
this.Meal = (TextView) view.findViewById(R.id.Meal);
this.price = (TextView) view.findViewById(R.id.Cost);
this.count = (TextView) view.findViewById(R.id.Count);
this.add = (Button) view.findViewById(R.id.addButton);
this.remove = (Button) view.findViewById(R.id.removeButton);
this.checkBox = (CheckBox) view.findViewById(R.id.checkBox);
this.img = (ImageView) view.findViewById(R.id.img);
this.card = (CardView) view.findViewById(R.id.card_view);
}
}
}
Data:
public class CardData {
public CardData() {
}
public String Meal;
public String Portion;
public String Cost;
public String url;
public Boolean checked;
public CardData(String meal, String portion, String cost, String url) {
Meal = meal;
Portion = portion;
Cost = cost;
this.url = url;
}
public Boolean isChecked() {
return checked;
}
public void setChecked(Boolean checked) {
this.checked = checked;
}
public String getMeal() {
return Meal;
}
public void setMeal(String meal) {
Meal = meal;
}
public String getPortion() {
return Portion;
}
public void setPortion(String portion) {
Portion = portion;
}
public String getCost() {
return Cost;
}
public void setCost(String cost) {
Cost = cost;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Related
I want to write a program to retrieve information from the server and display it in the Recycler View,But I have two problems.
When I add data to the table it will be added to the Recycler View list But when I delete, the list doesn't change.
2.Photos of each section cannot be loaded.
home.java
public class Home extends Fragment {
public Home() {
// Required empty public constructor
}
SwipeRefreshLayout srl;
RecyclerView rv;
FloatingActionButton add;
ArrayList<Post> al;
PostAdapter pa;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
srl = getActivity().findViewById(R.id.srl);
rv = getActivity().findViewById(R.id.rv);
// add = getActivity().findViewById(R.id.add);
AndroidNetworking.initialize(getContext());
al = new ArrayList<>();
pa = new PostAdapter(getContext(),al);
rv.setHasFixedSize(true);
rv.setItemAnimator(new DefaultItemAnimator());
rv.setLayoutManager(new LinearLayoutManager(getContext()));
rv.setAdapter(pa);
update();
srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
update();
}
});
}
private void update(){
String id = al.size() == 0 ? "0" : al.get(0).getId();
AndroidNetworking.post(Urls.host+Urls.post)
.addBodyParameter("id",id)
.build()
.getAsObjectList(Post.class, new ParsedRequestListener<List<Post>>() {
#Override
public void onResponse(List<Post> response) {
srl.setRefreshing(false);
for (Post p : response){
al.add(0,p);
pa.notifyDataSetChanged();
}
}
#Override
public void onError(ANError anError) {
srl.setRefreshing(false);
}
});
}
}
postadapter.java
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
Context context;
ArrayList<Post> al;
LayoutInflater inflater;
public PostAdapter(Context ctx,ArrayList<Post> arl){
context = ctx;
al = arl;
inflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.rv_item,null,false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
view.setLayoutParams(lp);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Post s = al.get(position);
holder.title.setText(s.getTitle());
holder.text.setText(s.getText());
holder.date.setText(s.getDate());
holder.image.setImageUrl(Urls.host+s.getImage());
holder.image.setDefaultImageResId(R.drawable.material);
holder.image.setErrorImageResId(R.drawable.material);
}
#Override
public int getItemCount() {
return al.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
ANImageView image;
AppCompatTextView title, text, date;
AppCompatImageView share;
public ViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image);
title = itemView.findViewById(R.id.title);
text = itemView.findViewById(R.id.text);
date = itemView.findViewById(R.id.date);
}
}
}
post.java
public class Post {
String title,text, date,id;
int imageUrl;
public Post(int imageUrl, String title, String text, String time, String id) {
this.imageUrl = imageUrl;
this.title = title;
this.text = text;
this.date = time;
this.id = id;
}
public int getImage() {
return imageUrl;
}
public void setImage(int imageUrl) {
this.imageUrl = imageUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Try this
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
Context context;
ArrayList<Post> al;
ArrayList<Post> newDataList;
LayoutInflater inflater;
public PostAdapter(Context ctx,ArrayList<Post> arl){
context = ctx;
al = arl;
inflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.rv_item,null,false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
view.setLayoutParams(lp);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Post s = al.get(position);
holder.title.setText(s.getTitle());
holder.text.setText(s.getText());
holder.date.setText(s.getDate());
holder.image.setImageUrl(Urls.host+s.getImage());
holder.image.setDefaultImageResId(R.drawable.material);
holder.image.setErrorImageResId(R.drawable.material);
}
#Override
public int getItemCount() {
return al.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
ANImageView image;
AppCompatTextView title, text, date;
AppCompatImageView share;
public ViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image);
title = itemView.findViewById(R.id.title);
text = itemView.findViewById(R.id.text);
date = itemView.findViewById(R.id.date);
}
public ArrayList<Post> getDataSet() {
return al;
}
public void refresh(ArrayList<Post> list) {
newDataList = new ArrayList<>();
newDataList.addAll(list);
al.clear();
al.addAll(newDataList);
notifyDataSetChanged();
}
}
Now at time when you wants to add or delete try getting adapter.getDataSet()
and update list with adapter.refresh(yourList)
I have a problem, when I enter my FinalListActivity first time by clicking button in MainActivity, everything works good. But when I go back to MainActivity and then I try enter again it throws an exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: app.listazakupow, PID: 5147
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at app.listazakupow.Adapters.FinalListAdapter.onBindViewHolder(FinalListAdapter.java:44)
at app.listazakupow.Adapters.FinalListAdapter.onBindViewHolder(FinalListAdapter.java:16)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
I know it's something wrong with my int ArrayList in Adapter class but i dont know what i should do. It is this fragment:
holder.imageView.setImageResource(imagesIndex.get(position));
Can somone help me? Below my code:
FinalListActivity
public class FinalListActivity extends AppCompatActivity {
private ArrayList<String> finalListArrayList;
private ArrayList<Integer> imagesIndex;
private RecyclerView recyclerView;
private TextView textView1, textView2, textView3;
private FinalListAdapter myAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private AppDatabase appDatabase;
private static final String DATABASE_NAME = "images_base";
#SuppressLint({"WrongViewCast", "SetTextI18n"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_finallist);
Intent intent = getIntent();
finalListArrayList = intent.getStringArrayListExtra("productList");
imagesIndex = intent.getIntegerArrayListExtra("imagesList");
appDatabase = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, DATABASE_NAME).fallbackToDestructiveMigration().build();
recyclerView = findViewById(R.id.recycler_view1);
mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
AsyncTask.execute(new Runnable() {
#Override
public void run() {
for(String s:finalListArrayList) {
String category = appDatabase.daoAccess().getCategoryByKeyword(s);
String imagePath = appDatabase.daoAccess().getImagePathForCategory(category);
int id;
if(imagePath!=null) {
id = getApplicationContext().getResources().getIdentifier(imagePath, "drawable", getPackageName());
}
else{
id = getApplicationContext().getResources().getIdentifier("app_logo_black", "drawable", getPackageName());
}
imagesIndex.add(id);
}
System.out.println("FinalListArrayListSize is:" + finalListArrayList.size()+" imageIndexList is: "+imagesIndex.size());
}
});
myAdapter = new FinalListAdapter(finalListArrayList, imagesIndex, recyclerView);
recyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
textView1 = findViewById(R.id.textView1);
textView2 = findViewById(R.id.textView2);
textView3 = findViewById(R.id.textView3);
textView1.setText("Amount of products: " + finalListArrayList.size());
}
#Override
protected void onResume(){
super.onResume();
System.out.println("FinalListArrayListSize is:" + finalListArrayList.size()+" imageIndexList is: "+imagesIndex.size());
}
}
FinalListAdapter
public class FinalListAdapter extends
RecyclerView.Adapter<FinalListAdapter.MyViewHolder> {
private ArrayList<String> mDataset;
private ArrayList<Integer> imagesIndex;
private ArrayList<FinalListItem> finalListItems;
private RecyclerView recyclerView;
public FinalListAdapter(ArrayList<String> mDataset,ArrayList<Integer> imagesIndex, RecyclerView recyclerView) {
this.mDataset = mDataset;
this.imagesIndex = imagesIndex;
this.recyclerView = recyclerView;
finalListItems = new ArrayList<>();
for (String a : mDataset) {
finalListItems.add(new FinalListItem(a, false));
}
}
public ArrayList<Integer> getImagesIndex(){
return imagesIndex;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return 0;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.final_list_TextView1.setText(finalListItems.get(position).getName());
holder.imageView.setImageResource(imagesIndex.get(position));
holder.checkBox.setOnCheckedChangeListener(null);
holder.checkBox.setBackgroundResource(R.drawable.listitem_white);
if(finalListItems.get(position).isChecked){
holder.linearLayout.setBackgroundResource(R.drawable.listitem_green);
holder.checkBox.setChecked(true);
}
else{
holder.linearLayout.setBackgroundResource(R.drawable.listitem_white);
holder.checkBox.setChecked(false);
}
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int currentPosition = holder.getAdapterPosition();
if(isChecked){
FinalListItem finalItemBefore = finalListItems.get(currentPosition);
FinalListItem finalItemAfter = new FinalListItem(finalItemBefore.getName(), true);
finalListItems.remove(finalItemBefore);
finalListItems.add(finalItemAfter);
recyclerView.scrollToPosition(0);
holder.linearLayout.setBackgroundResource(R.drawable.listitem_green);
notifyItemMoved(currentPosition, getItemCount() - 1);
}
else{
finalListItems.get(currentPosition).setChecked(false);
notifyItemChanged(currentPosition);
}
}
});
}
#Override
public int getItemCount() {
return finalListItems.size();
}
private class FinalListItem {
private String name;
private boolean isChecked;
public FinalListItem(String name, boolean isChecked) {
this.name = name;
this.isChecked = isChecked;
}
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
public String getName() {
return name;
}
}
public class MyViewHolder extends RecyclerView.ViewHolder {
final private TextView final_list_TextView1;
final private CheckBox checkBox;
final private LinearLayout linearLayout;
final private ImageView imageView;
public MyViewHolder(View view) {
super(view);
final_list_TextView1 = view.findViewById(R.id.final_list_TextView1);
checkBox = view.findViewById(R.id.checkBox1);
linearLayout = view.findViewById(R.id.linearLayout1);
imageView = view.findViewById(R.id.item_image);
}
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.finallist_list_layout, parent, false);
return new MyViewHolder(view);
}
}
Yes, the line of code:
holder.imageView.setImageResource(imagesIndex.get(position));
is causing the error.
Why? Because the value of position has nothing to do with the index of any value in the ArrayList "imagesIndex". The value position you get from onBindViewHolder refers to the row in the RecyclerView that means the ArrayList "finalListItems" which you generate in your constructor.
I'm creating a android app with Recylerview to retrieve list of mp3 files with play and download buttons.
Below is my JSON file :
From the above Json file Image, i want to retrieve those audioLink's in recycler view. I want to play them using Mediaplayer along with a seek bar and also Download them to mobile storage, i don't know how to implement them.Please Help me to code
Here is my Screenshot of a audio item in recyclerview
Here is my Model Class of Audio Items
public class AudioItem {
public String imageLink;
public String categoryId;
public String number;
public long viewCount;
public String audioTitle;
public AudioItem() {
}
public AudioItem(String imageLink, String categoryId, String audioTitle) {
this.imageLink = imageLink;
this.categoryId = categoryId;
this.audioTitle = audioTitle;
}
public String getAudioTitle() {
return audioTitle;
}
public void setAudioTitle(String audioTitle) {
this.audioTitle = audioTitle;
}
public AudioItem(String number) {
this.number = number;
}
public String getImageLink() {
return imageLink;
}
public void setImageLink(String imageLink) {
this.imageLink = imageLink;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public long getViewCount() {
return viewCount;
}
public void setViewCount(long viewCount) {
this.viewCount = viewCount;
}
}
Here is my List of mp3's AudioItemViewHolder Class
public class ListBRViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ItemClickListener itemClickListener;
public TextView wallpaperVcount,wallpaperVcountlinear,AudioTitle;
public ImageButton play,download;
public void setItemClickListener(ItemClickListener itemClickListener)
{
this.itemClickListener = itemClickListener;
}
public ListBRViewHolder(View itemView) {
super(itemView);
wallpaperVcount=(TextView)itemView.findViewById(R.id.viewCount);
AudioTitle=(TextView)itemView.findViewById(R.id.brtitle);
download=(ImageButton)itemView.findViewById(R.id.btn_download) ;
play=(ImageButton)itemView.findViewById(R.id.btn_play) ;
wallpaperVcountlinear(TextView)itemView.findViewById(R.id.viewCountLinear);
itemView.setOnClickListener(this);
}
Here is my AudioListView Class
public class NewBRList extends AppCompatActivity {
Query query;
FirebaseRecyclerOptions<AudioItem> options;
FirebaseRecyclerAdapter<AudioItem,ListBRViewHolder> adapter;
RecyclerView recyclerView;
AdView mAdview;
RelativeLayout relativeLayout;
//Room Database
CompositeDisposable compositeDisposable;
RecentsRepository recentsRepository;
FavouritesRepository favouritesRepository;
ImageView image_category;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newbr_list);
Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
toolbar.setTitle(Common.CATEGORY_SELECTED);
setSupportActionBar(toolbar);
relativeLayout=(RelativeLayout)findViewById(R.id.listviewlayoutnewbr) ;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
image_category=(ImageView)findViewById(R.id.image_newbr);
recyclerView=(RecyclerView)findViewById(R.id.recycler_newbr_list);
recyclerView.setHasFixedSize(true);
recyclerView.setItemViewCacheSize(20);
recyclerView.setDrawingCacheEnabled(true);
recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
linearLayoutManager.setReverseLayout(true);
recyclerView.setLayoutManager(linearLayoutManager);
loadBackgroundList();
}
private void loadBackgroundList() {
query= FirebaseDatabase.getInstance().getReference(Common.STR_WALLPAPER)
.orderByChild("categoryId").equalTo(Common.CATEGORY_ID_SELECTED);
options=new FirebaseRecyclerOptions.Builder<AudioItem>()
.setQuery(query,AudioItem.class)
.build();
adapter=new FirebaseRecyclerAdapter<AudioItem, ListBRViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ListBRViewHolder holder, int position, #NonNull final AudioItem model) {
holder.AudioTitle.setText(model.getAudioTitle());
holder.wallpaperVcountlinear.setText("Views : "+ model.getViewCount());
holder.download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(NewBRList.this,"Download Test",Toast.LENGTH_SHORT).show();
}
});
holder.play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(NewBRList.this,"Play Test",Toast.LENGTH_SHORT).show();
}
});
}
#Override
public ListBRViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView= LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_br_item_linear,parent,false);
int height=parent.getMeasuredHeight()/2;
itemView.setMinimumHeight(height);
return new ListBRViewHolder(itemView);
}
};
adapter.startListening();
recyclerView.setAdapter(adapter);
}
Please Kindly Help me :)
Thank you.
I am trying make an application with 2 screen: MainActivity (login) and CustomerInfoActivity.
Login screen with.
The other screen is used to show customer information (name, phone, image) displayed by recycler view, and a textview to display location update.
Using broadcast receiver and catch the event when the device go to sleep mode/wake up => disable/enable service.
My app crash when I click the Login button to jump to the Recycle view screen and I have no idea how to handle the disable Service requirement.
Please give me some help. Thank you.
DataCustomer.java
public class DataCustomer {
private int image;
private String name;
private int phonenumber;
public DataCustomer(String name, int phonenumber, int image) {
this.image = image;
this.name = name;
this.phonenumber = phonenumber;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(int phonenumber) {
this.phonenumber = phonenumber;
}}
CustomerAdapter.java
public class CustomerAdapter extends RecyclerView.Adapter<CustomerAdapter.ViewHolder> {
private ArrayList<DataCustomer> dataCustomers;
private Context context;
public CustomerAdapter(ArrayList<DataCustomer> dataCustomers, Context context) {
this.dataCustomers = dataCustomers;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View itemView = layoutInflater.inflate(R.layout.item_customer,parent,false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.customer_name.setText(dataCustomers.get(position).getName());
holder.customer_phone.setText(dataCustomers.get(position).getPhonenumber());
holder.customer_image.setImageResource(dataCustomers.get(position).getImage());
}
#Override
public int getItemCount() {
return dataCustomers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView customer_name;
TextView customer_phone;
ImageView customer_image;
public ViewHolder(View itemView){
super(itemView);
customer_name = (TextView)itemView.findViewById(R.id.customer_name);
customer_phone = (TextView) itemView.findViewById(R.id.customer_phone);
customer_image = (ImageView)itemView.findViewById(R.id.customer_image);
}
}}
CustomerInfoActivity.java
public class CustomerInfoActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customer_info);
initView();
}
public void initView(){
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.customer_items);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
recyclerView.setLayoutManager(layoutManager);
ArrayList<DataCustomer> arrayList = new ArrayList<>();
arrayList.add(new DataCustomer("A",12,R.drawable.A));
arrayList.add(new DataCustomer("B",34,R.drawable.B));
arrayList.add(new DataCustomer("C",56,R.drawable.C));
arrayList.add(new DataCustomer("D",78,R.drawable.D));
CustomerAdapter customerAdapter = new CustomerAdapter(arrayList, getApplicationContext());
recyclerView.setAdapter(customerAdapter);
}}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static EditText username;
private static EditText password;
private static CheckBox rememberpassword;
private static Button loginbutton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginButton();
}
public void loginButton(){
username = (EditText)findViewById(R.id.editText_username);
password = (EditText)findViewById(R.id.editText_password);
rememberpassword = (CheckBox)findViewById(R.id.checkBox_rememberpassword);
loginbutton = (Button)findViewById(R.id.button_login);
loginbutton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if(username.getText().toString().equals("user") &&
password.getText().toString().equals("pass") ) {
Intent intent = new Intent("com.assignment.assignment2_v2.CustomerInfoActivity");
startActivity(intent);
}
}
}
);
}
}
Crash probably could be fixed by switching for implicit Intent to explicit one:
Intent intent = new Intent(MainActivity.this, CustomerInfoActivity.class);
startActivity(intent);
Try this one. Also could you add your crash logs if this will not help?
How do i set data in RecylerView using Retrofit.I have tried but i was not able to performed it successfully.
Here is my code:
JSON DATA is :
{
"model": [
{
"id": "1",
"brand_name": "Audi",
"brand_logo": "1495456122.",
},
{
"id": "3",
"brand_name": "BMW",
"brand_logo": "1495451144.",
}
]
}
BrandSelectActivity.java
public class BrandSelectActivity extends AppCompatActivity implements View.OnClickListener {
ProgressDialog pDialog;
Button btn_addVehicle;
BrandListRecyclerAdapter adapter;
RecyclerView recyclerView_brand;
public ImageView carBrandImg;
public TextView carBrandName;
private static String TAG = BrandSelectActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_brand_select);
carBrandImg = (ImageView)findViewById(R.id.carBrandImg);
carBrandName = (TextView)findViewById(R.id.carBrandName);
recyclerView_brand = (RecyclerView) findViewById(R.id.recycler_view);
pDialog = new ProgressDialog(getApplicationContext());
pDialog.setCancelable(true);
pDialog.setMessage("Please Wait...");
pDialog.show();
ArrayList<BrandModel> brandModelArrayList = new ArrayList<BrandModel>();
BrandListRecyclerAdapter brandAdapter = new BrandListRecyclerAdapter(BrandSelectActivity.this, brandModelArrayList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView_brand.setLayoutManager(mLayoutManager);
recyclerView_brand.setAdapter(brandAdapter);
brandAdapter.setItemClickListener(new BrandListRecyclerAdapter.MyClickListerer() {
#Override
public void onItemClick(int position, View view) {
Intent sosIntent = new Intent(BrandSelectActivity.this, ModelSelectActivity.class);
startActivity(sosIntent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
callBrandSelect();
}
private void callBrandSelect() {
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<BrandSelectResponse> call = apiService.saveBrand("1");
call.enqueue(new Callback<BrandSelectResponse>() {
#Override
public void onResponse(Call<BrandSelectResponse> call, retrofit2.Response<BrandSelectResponse> response) {
BrandSelectResponse br= response.body();
List<BrandSelectResponse.ModelBean> modelList = br.getModel();
modelList.size();
modelList.get(0).getBrand_logo();
modelList.get(0).getBrand_name();
pb.dismiss();
}
#Override
public void onFailure(Call<BrandSelectResponse>call, Throwable t) {
Toast.makeText(BrandSelectActivity.this,"Opps ..!!Failed to
connect to our server.. Try Again later..",Toast.LENGTH_SHORT).show();
Log.e(TAG, t.toString());
}
});
}
#Override
public void onClick(View v) {
}
}
BrandListRecyclerAdapter.java
public class BrandListRecyclerAdapter extends RecyclerView.Adapter<BrandListRecyclerAdapter.MyViewHolder> {
Context mcontext;
List<BrandSelectResponse> brandModelArrayList;
public LayoutInflater inflater;
public static MyClickListerer myClickListerer;
public BrandListRecyclerAdapter(Context context, ArrayList<BrandSelectResponse> brandModelArrayList) {
this.mcontext = context;
this.brandModelArrayList=brandModelArrayList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_brand, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
BrandSelectResponse current = brandModelArrayList.get(position);
holder.setData((BrandSelectResponse) brandModelArrayList,position);
holder.carBrandName.setText(current.getBrand_name());
holder.carBrandImg.setImageResource(current.getBrand_logo());
}
public interface MyClickListerer {
void onItemClick(int position, View view);
}
public void setItemClickListener(MyClickListerer myClickListerer) {
this.myClickListerer = myClickListerer;
}
#Override
public int getItemCount() {
return brandModelArrayList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
public ImageView carBrandImg;
public TextView carBrandName;
BrandSelectResponse brandModelArrayList;
LinearLayout current;
int position;
public MyViewHolder(View itemView) {
super(itemView);
carBrandImg = (ImageView) itemView.findViewById(R.id.carBrandImg);
carBrandName = (TextView) itemView.findViewById(R.id.carBrandName);
}
public void setData(BrandSelectResponse current, int position) {
carBrandName.setText(brandModelArrayList.getBrand_name());
carBrandImg.setImageResource(brandModelArrayList.getBrand_logo());
this.position = position;
this.brandModelArrayList = current;
}
#Override
public void onClick(View v) {
myClickListerer.onItemClick(getAdapterPosition(), v);
}
}
}
BrandSelectResponse.java
public class BrandSelectResponse implements Serializable{
private List<ModelBean> model;
public BrandSelectResponse(List<ModelBean> model) {
this.model = model;
}
public List<ModelBean> getModel() {
return model;
}
public void setModel(List<ModelBean> model) {
this.model = model;
}
public static class ModelBean {
private String id;
private String brand_name;
private String brand_logo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBrand_name() {
return brand_name;
}
public void setBrand_name(String brand_name) {
this.brand_name = brand_name;
}
public String getBrand_logo() {
return brand_logo;
}
public void setBrand_logo(String brand_logo) {
this.brand_logo = brand_logo;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
}
You give to adapter EMPTY list.
You never add data to brandModelArrayList.
Next time try to look at the logcat, what is the exception and which line is the problem.