I have a pretty cool problem that I keep trying to figure out.
I have an Activity named Bill, it has a Textview and a RecyclerView. I plan to use textview to count the bills I have while recyclerView will show those bills.
But the problem is that in the adapter when I am processing the Viewholder data for the RecyclerView, it has a button to clear the Bill in case the customer returns or cancels the order.
And the problem is now I don't know how to setText for TextView, can anyone please answer this question for me? Thanks.
Here is the Bill activity i mention
package anhtuan.example.sample.feature;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.TextView;
import java.util.ArrayList;
import anhtuan.example.sample.Bill.Bill_RecyclerView_Adapter;
import anhtuan.example.sample.DAO.DAO;
import anhtuan.example.sample.Model.BillModel;
import anhtuan.example.sample.R;
public class Bill extends AppCompatActivity {
TextView bill_total;
RecyclerView bill_RecyclerView;
ArrayList<BillModel>bills;
DAO dao;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bill);
setTitle("Bill");
bill_total = findViewById(R.id.bill_total);
bill_RecyclerView = findViewById(R.id.bill_recyclerView);
getSupportActionBar().hide();
bills=new ArrayList<>();
dao = new DAO(Bill.this);
bills= dao.getDSBill();
bill_total.setText("Bills: "+dao.CountBill());
Bill_RecyclerView_Adapter adapter = new Bill_RecyclerView_Adapter(bills,Bill.this,dao);
bill_RecyclerView.setLayoutManager(new LinearLayoutManager(Bill.this,RecyclerView.VERTICAL,false));
bill_RecyclerView.setAdapter(adapter);
}
}
bill_total is the textView i use to count the bill with the function in DAO class named CountBill()
public int CountBill(){
SQLiteDatabase database = sqLite.getReadableDatabase();
Cursor c = database.rawQuery("select * from bill ",new String[]{});
int sum = c.getCount();
c.close();
return sum;
}
And here is the RecyclerView Adapter
package anhtuan.example.sample.Bill;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import anhtuan.example.sample.DAO.DAO;
import anhtuan.example.sample.Model.BillModel;
import anhtuan.example.sample.R;
public class Bill_RecyclerView_Adapter extends RecyclerView.Adapter<Bill_RecyclerView_Viewholder> {
ArrayList<BillModel> bills;
Context context;
DAO dao;
public Bill_RecyclerView_Adapter(ArrayList<BillModel> bills, Context context, DAO dao) {
this.bills = bills;
this.context = context;
this.dao = dao;
}
#NonNull
#Override
public Bill_RecyclerView_Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.bill_viewholder,parent,false);
return new Bill_RecyclerView_Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull Bill_RecyclerView_Viewholder holder, int position) {
BillModel billModel;
billModel = bills.get(position);
holder.picture.setImageBitmap(billModel.BillBookPicture);
holder.name.setText(billModel.BillBookName);
holder.category.setText("Tag: "+billModel.BillBookCategory);
holder.date.setText("Date: "+billModel.BillDate);
holder.money.setText("Money: "+billModel.BillMoney);
holder.sale.setText("Sale: "+billModel.BillSale);
holder.totalSale.setText("Total: "+billModel.BillTotalSale);
holder.del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dao.BillDel(billModel.id);
bills = dao.getDSBill();
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return bills.size();
}
}
Thanks https://stackoverflow.com/users/20015640/urvish-shiroya recommend me about the interface callback, it kinda hard to understand clearly but i think i got a hand of it.
All i need to do here is to create an interface file named ViewUpdater then create a class interface in it:
public interface ViewUpdater {
void CallBack(TextView id);
}
Then create a void class to setText in Bill activity:
public void SetText(ViewUpdater view){
view.CallBack(bill_total);
}
Finally call it in the onBindViewHolder at the deleted button for it to automatic the Bill count after i delete a bill:
public void onBindViewHolder(#NonNull Bill_RecyclerView_Viewholder holder, int position) {
BillModel billModel;
billModel = bills.get(position);
holder.picture.setImageBitmap(billModel.BillBookPicture);
holder.name.setText(billModel.BillBookName);
holder.category.setText("Tag: "+billModel.BillBookCategory);
holder.date.setText("Date: "+billModel.BillDate);
holder.money.setText("Money: "+billModel.BillMoney);
holder.sale.setText("Sale: "+billModel.BillSale);
holder.totalSale.setText("Total: "+billModel.BillTotalSale);
holder.del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dao.BillDel(billModel.id);
bills = dao.getDSBill();
((Bill)context).SetText(new ViewUpdater() {
#Override
public void CallBack(TextView id) {
id.setText("Bills: "+dao.CountBill()+"");
}
});
notifyDataSetChanged();
}
});
}
Hope this help with someone has the same problem
Related
I was trying to practice using the Recycler in Android Studio using Java.
I have made so much progress so far.
When I run the application it crashes immediately, I have checked the logs and I had an error on the below:
Attempt to invoke virtual method 'android.view.View androidx.recyclerview.widget.RecyclerView.findViewById(int)' on a null object reference
and
Attempt to invoke virtual method 'android.view.View androidx.recyclerview.widget.RecyclerView.findViewById(int)' on a null object reference
Below is my MainActivity class:
package com.example.recyleview;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.LinearLayout;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView recView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recView.findViewById(R.id.recView);
recView.setLayoutManager(new LinearLayoutManager(this));
setContentView(R.layout.activity_main);
ArrayList<Contact> contacts = new ArrayList<>();
contacts.add(new Contact("Jacob", "jacob#gmail.com", "later"));
contacts.add((new Contact("Sara ", "sara#gmail.com", "later")));
contacts.add(new Contact("Nino", "nino#gmail.com", "later"));
ContactsRecViewAdapter adapter = new ContactsRecViewAdapter(this);
adapter.setContacts(contacts);
recView.setAdapter(adapter);
}
}
and here is another class called ContactsRecViewAdapter
package com.example.recyleview;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ContactsRecViewAdapter extends RecyclerView.Adapter<ContactsRecViewAdapter.ViewHolder>{
private ArrayList<Contact> contacts = new ArrayList<>();
private final Context context;
public ContactsRecViewAdapter(Context context) {
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.contacts_list_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ContactsRecViewAdapter.ViewHolder holder, int position) {
holder.txtName.setText(contacts.get(position).getName());
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, contacts.get(position).getName() + " Clicked", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return contacts.size();
}
public void setContacts(ArrayList<Contact> contacts) {
this.contacts = contacts;
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
private final TextView txtName;
private final RelativeLayout parent;
public ViewHolder(#NonNull View itemView) {
super(itemView);
txtName = itemView.findViewById(R.id.txtName);
parent = itemView.findViewById(R.id.parent);
}
}
}
Change
recView.findViewById(R.id.recView);
to
recView = findViewById(R.id.recView);
Also you have duplicated:
setContentView(R.layout.activity_main);
You have to set the contentView before you try to find the views.
I want the app to open a page when the user taps on an item and pass some extra information to that intent. That's it. I tried about 7 - 10 onclickListener types but I didn't solve anything. I am posting my adapter class with the latest implementation ( that doesn't work ). Json works and the Recyclerview loads data and images from url with no problems.
package byDragosT.myapplication;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class RecipeApiAdapter extends RecyclerView.Adapter<RecipeApiAdapter.RecipeViewHolder> {
private ArrayList<RecipeItem> recipeItems;
private Context context;
public RecipeApiAdapter(ArrayList<RecipeItem> recipeItems, Context context){
this.recipeItems = recipeItems;
this.context = context;
}
#NonNull
#Override //// Mare grija ce layout pui aici - sfat pentru viitor - mi-a luat 4 ore sa gasesc eroarea
public RecipeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recipe_item_in_recyclerview_api, parent, false);
return new RecipeViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecipeViewHolder holder, int position) {
final RecipeItem recipeItem = recipeItems.get(position);
holder.title.setText(recipeItem.getMnameRecipe());
holder.description.setText(recipeItem.getMdescribeRecipe());
Picasso.get().load(recipeItem.getItemPictureUrl())
.into(holder.jpegRecipe);
System.out.println("image with title: " + holder.title.getText() + "was added in theory");
}
#Override
public int getItemCount() {
return recipeItems.size();
}
public static class RecipeViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView jpegRecipe;
public TextView title;
public TextView description;
public RelativeLayout containerView;
public RecyclerView mRecyclerView;
RecipeViewHolder(View view){
super(view);
jpegRecipe = view.findViewById(R.id.picture);
title = view.findViewById(R.id.recipe_name);
description = view.findViewById(R.id.ingredients_list);
containerView = view.findViewById(R.id.recipe_item_container); // vezi aici
mRecyclerView = view.findViewById(R.id.recyclerView);
}
#Override
public void onClick(View v) {
int itemPosition = mRecyclerView.getChildLayoutPosition(v);
RecipeItem current = recipeItems.get(itemPosition);
Intent intent = new Intent(v.getContext(), RecipeDetailsActivity.class);
intent.putExtra("name", current.getMnameRecipe());
v.getContext().startActivity(intent);
}
}
}
Try adding view.setOnClickListener(this);
RecipeViewHolder(View view){
super(view);
view.setOnClickListener(this);
.....
}
I have built an overview of an order with a ReyclerView. Below you can see the code for the adapter class. My problem only occurs in the following place, if the user clicks on an element of ReyclerView, a popup with an expanded view should appear.
This popup also occurs. Unfortunately, as soon as I want to populate the TextView with the order code, the app supports and says null Attempt to invoke virtual method'void android.widget.TextView.setText (java.lang.CharSequence)' on a null object reference.
How can I avoid this null error so that it all works?
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Layout;
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.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class UserBestellAdapter extends RecyclerView.Adapter<UserBestellAdapter.ViewHolder> {
ArrayList<Bestellung> bestellung;
Context mContext;
Dialog epicDialog;
public UserBestellAdapter(Context context, ArrayList<Bestellung> list) {
mContext = context;
bestellung = list;
epicDialog = new Dialog(mContext);
}
#NonNull
#Override
public UserBestellAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.adapter_bestell, parent, false);
UserBestellAdapter.ViewHolder viewHolder = new UserBestellAdapter.ViewHolder(view);
return viewHolder;
}
#NonNull
#Override
public void onBindViewHolder(#NonNull UserBestellAdapter.ViewHolder holder, int position) {
//Gesamtpreis: holder.item_betrag.setText(String.valueOf(bestellung.get(position).getBetrag()));
// Datum: holder.item_datum.setText(bestellung.get(position).getDatum());
holder.item_items.setText(bestellung.get(position).getProdukte());
//holder.item_code.setText(bestellung.get(position).getBestellnummer());
String bestellid =bestellung.get(position).getBestellnummer() + "";
holder.item_code.setText(bestellid);
holder.item_betrag.setText(Double.toString(bestellung.get(position).getSumme()));
holder.item_datum.setText(bestellung.get(position).getDatum());
holder.layout_user_bestellung.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView order_overview_number = epicDialog.findViewById(R.id.order_overview_number);
order_overview_number.setText();
epicDialog.setContentView(R.layout.order_popup_waiting);
epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Button btn_order_overview_finish = (Button) epicDialog.findViewById(R.id.btn_order_overview_finish);
/*
btn_order_overview_finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
epicDialog.dismiss();
}
});*/
epicDialog.show();
}
});
}
#Override
public int getItemCount() {
return bestellung.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView item_items, item_betrag, item_datum, item_code;
private ConstraintLayout layout_user_bestellung;
public ViewHolder(#NonNull View itemView) {
super(itemView);
item_items = itemView.findViewById(R.id.items);
item_betrag = itemView.findViewById(R.id.betrag);
item_datum = itemView.findViewById(R.id.datum);
item_code = itemView.findViewById(R.id.code);
layout_user_bestellung = itemView.findViewById(R.id.layout_user_bestellung);
}
}
}
Your Dialog is initialized with new Dialog(context) but in your onClick Method you expect that your epicDialog has a TextVew with the id order_overview_number.
This will always return null and thus order_overview_number.setText() thows a NPE.
To reference a view of a Dialog the Dialog needs a layout which contains that view, similar to fragments and activities.
This may have further information for you:
How to create a Custom Dialog box in android?
https://developer.android.com/guide/topics/ui/dialogs
I'm trying to fetch data from an API and show the data into a recycler view. That API Contains an image URL and id. And I want to show the image from the URL and the id in the recycler view. But when I go to the Activity the recycler view is not showing the list. It is fetching the data from the API very well but it is not showing the data in the Recyclerview in a list format.
RecyclerviewAdapter.java
package com.madhulata.shriresume.shared;
import android.content.Context;
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 android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.madhulata.shriresume.R;
import java.util.ArrayList;
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.ViewHolder>{
private ArrayList<String> mImageNames;
private ArrayList<String> mId;
private Context mContext;
public RecyclerviewAdapter(ArrayList<String> mImageNames, ArrayList<String> mId, Context mContext) {
this.mImageNames = mImageNames;
this.mId = mId;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.resume_format,parent,false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Log.d("Recycler","on Bind Called");
Glide.with(mContext)
.asBitmap()
.load(mImageNames.get(position))
.into(holder.resumeImage);
holder.resumeId.setText(mId.get(position));
holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, mImageNames.get(position), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return mImageNames.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView resumeImage;
TextView resumeId;
ConstraintLayout constraintLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
resumeImage = itemView.findViewById(R.id.resumeLogo);
resumeId = itemView.findViewById(R.id.resumeId);
constraintLayout = itemView.findViewById(R.id.resumeTypeLayout);
}
}
}
***********************************SelectResume.java********************
package com.madhulata.shriresume.activity_dir;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.madhulata.shriresume.R;
import com.madhulata.shriresume.models.ResumeType;
import com.madhulata.shriresume.shared.RecyclerviewAdapter;
import com.madhulata.shriresume.shared.RetrofitClient;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class SelectResume extends AppCompatActivity {
RecyclerView selectResumeList;
private static final String TAG = "SignupActivity";
private ArrayList<String> mId;
private ArrayList<String> mUrls;
ProgressBar p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_resume);
mId = new ArrayList<>();
mUrls = new ArrayList<>();
selectResumeList = findViewById(R.id.selectResumeList);
getResume();
}
private void initRecyclerView(){
Log.i("Value","init Recycler View");
RecyclerviewAdapter adapter = new RecyclerviewAdapter(mUrls,mId,this);
selectResumeList.setAdapter(adapter);
selectResumeList.setLayoutManager(new LinearLayoutManager(this));
}
private void getResume(){
Log.i("Value","Call method");
Call<List<ResumeType>> call = RetrofitClient.getInstance().getApi().getResume();
call.enqueue(new Callback<List<ResumeType>>() {
#Override
public void onResponse(Call<List<ResumeType>> call, Response<List<ResumeType>> response) {
if (!response.isSuccessful()){
Toast.makeText(SelectResume.this, response.code(), Toast.LENGTH_SHORT).show();
}else{
List<ResumeType> resume = response.body();
for (ResumeType r : resume){
mUrls.add(r.getUrl());
mId.add(r.getId());
Log.i("Value", mId.toString());
}
}
Log.i("Value","Call method 3");
}
#Override
public void onFailure(Call<List<ResumeType>> call, Throwable t) {
Toast.makeText(SelectResume.this, "Something went wrong!", Toast.LENGTH_SHORT).show();
}
});
initRecyclerView();
}
}
Why it is not showing?
Your initRecyclerView(); called before you update your data from the services. Retrofit callback works in a separate thread.
Try this instead of your method
private void getResume(){
Log.i("Value","Call method");
Call<List<ResumeType>> call = RetrofitClient.getInstance().getApi().getResume();
call.enqueue(new Callback<List<ResumeType>>() {
#Override
public void onResponse(Call<List<ResumeType>> call, Response<List<ResumeType>> response) {
if (!response.isSuccessful()){
Toast.makeText(SelectResume.this, response.code(), Toast.LENGTH_SHORT).show();
}else{
List<ResumeType> resume = response.body();
for (ResumeType r : resume){
mUrls.add(r.getUrl());
mId.add(r.getId());
Log.i("Value", mId.toString());
}
initRecyclerView();
}
Log.i("Value","Call method 3");
}
#Override
public void onFailure(Call<List<ResumeType>> call, Throwable t) {
Toast.makeText(SelectResume.this, "Something went wrong!", Toast.LENGTH_SHORT).show();
}
});
}
You can set adapter once at start in onCreate() even if your data is empty. You can add data later and call notifyDataSetChanged() on the adapter. The RecyclerView will be updated accordingly. This will save you from the overhead of setting adapter to RecyclerView each time you get some data.
public class SelectResume extends AppCompatActivity {
RecyclerView selectResumeList;
private static final String TAG = "SignupActivity";
private ArrayList<String> mId;
private ArrayList<String> mUrls;
ProgressBar p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_resume);
mId = new ArrayList<>();
mUrls = new ArrayList<>();
selectResumeList = findViewById(R.id.selectResumeList);
initRecyclerView();
getResume();
}
private void initRecyclerView(){
Log.i("Value","init Recycler View");
RecyclerviewAdapter adapter = new RecyclerviewAdapter(mUrls, mId, this);
selectResumeList.setAdapter(adapter);
selectResumeList.setLayoutManager(new LinearLayoutManager(this));
}
private void getResume(){
Log.i("Value","Call method");
Call<List<ResumeType>> call = RetrofitClient.getInstance().getApi().getResume();
call.enqueue(new Callback<List<ResumeType>>() {
#Override
public void onResponse(Call<List<ResumeType>> call, Response<List<ResumeType>> response) {
if (!response.isSuccessful()) {
Toast.makeText(SelectResume.this, response.code(), Toast.LENGTH_SHORT).show();
} else {
List<ResumeType> resume = response.body();
for (ResumeType r : resume){
mUrls.add(r.getUrl());
mId.add(r.getId());
Log.i("Value", mId.toString());
}
adapter.notifyDataSetChanged();
}
Log.i("Value","Call method 3");
}
#Override
public void onFailure(Call<List<ResumeType>> call, Throwable t) {
Toast.makeText(SelectResume.this, "Something went wrong!", Toast.LENGTH_SHORT).show();
}
});
}
}
You receive the objects to show into RecyclerView from async network call. You need to update the adapter on the callback of your network call. Moreover I advice to initialize the adapter with empty list on the activity created, and after when you receive your data update the list with notifyDataSetChanged()
https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#notifyDataSetChanged()
Have an apparently simple task of -
Display a list of items using recycler view and each item should be card view.On click of any item new screen should open which shows detail of that item.
I already have seen various questions posted on the same topic, I would appreciate a little help on the attempt ive made rather than redirecting me there, since I'm pretty new and unable to understand how exactly to implement just by seeing those answers.I have tried to follow a tutorial closely but clearly have failed in replicating the results.HERE ARE THE FILES
MainActivity.java
. package com.example.hardikvats.recylerviewdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private String[] phones={"MotoX","Nokia Asha","Lumia 710","Iphone 7s"};
private String[] OperatingSytem={"Android","Symbian","Windows","Ios"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RecyclerView recyclerView= (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
MyAdapter adapter=new MyAdapter(this,phones);
recyclerView.setAdapter(adapter);
}
}
MyAdapter.java
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
String[] phones;
String[] OperatingSystem;
//CONSTRUCTOR
public MyAdapter(Context c, String[] PhoneModel){
this.c=c;
this.phones=PhoneModel;
//this.OperatingSystem=OperatingSystem;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//INFLATING FROM XML TO JAVA VIEW
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,null);
MyHolder holder=new MyHolder(v);
return holder;
}
#Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.PhoneModel.setText(phones[position]);
holder.setItemClickListner(new ItemClickListner() {
#Override
public void onItemClick(View v, int position) {
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[position]);
}
});
}
#Override
public int getItemCount() {
return phones.length;
}
}
MyHolder.java
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView PhoneModel;
ItemClickListner icl;
public MyHolder(View itemView) {
super(itemView);
PhoneModel=(TextView) itemView.findViewById(R.id.MobilePhone);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
this.icl.onItemClick(v,getLayoutPosition());
}
public void setItemClickListner(ItemClickListner itemClickListner){
this.icl=itemClickListner;
}
}
DetailActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity {
TextView OperatingSystem;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail2);
Intent i=getIntent();
final String OperatingSystem =i.getExtras().getString("Operating System");
}
}
ItemClickListner.java(Interface)
`import android.view.View;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public interface ItemClickListner {
void onItemClick(View v, int position);
}`
The goal is to click each list item from phones array and get an activity listing the OS in a new activity in a new textfield
after i.putExtra("OS NAME ....
add this line
c.startActivity(c,DetailActivity.class);
As you did, in order that changes to be small, try this:
holder.PhoneModel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[holder.getAdapterPosition()]);
}
});
Holder will always retain your position.
//set on item click listener like this
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(MainActivity.this, "Card at " + position + " is clicked", Toast.LENGTH_SHORT).show();
// here you can start your detail Activity
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[position]);
c.startActivity(i);
}
}));
// here is the on item click listener class
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
GestureDetector mGestureDetector;
public interface OnItemClickListener{
public void onItemClick(View view, int position);
}
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View childView = rv.findChildViewUnder(e.getX(),e.getY());
if(childView != null && mListener != null && mGestureDetector.onTouchEvent(e)){
mListener.onItemClick(childView, rv.getChildAdapterPosition(childView));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override`enter code here`
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}