When I change the value from recycleview.adapter, i want to set it the value to textview in mainactivity, how to do it?
it will be like this,
the recycle data retreive from my json, so it will be random and many data,
when I change or add the value of "total win" to more than "0", the textview at bottom will be appear, and "total all" will count from data I add, when its done, I want to send the "result" value to next activity or post and save it to mysql dbase,
here my code of MainActivity :
...
private List<Details> listDetails = new ArrayList<>();
private RecyclerAdapter viewAdapter;
#BindView(R.id.recyclerView)
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
ButterKnife.bind(this);
viewAdapter = new RecyclerAdapter(this, listDetails);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(viewAdapter);
getMyData();
}
...
private void getMyData() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(AppConfig.URL_MAIN)
.addConverterFactory(GsonConverterFactory.create())
.build();
...
});
...
My RecycleAdapter code :
...
private Context context;
private List<Details> listDetails;
public RecyclerAdapter(Context context, List<Details> listDetails) {
this.context = context;
this.listDetails = listDetails;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view, parent, false);
ViewHolder holder = new ViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Details getSet = listDetails.get(position);
holder.tvName.setText(getSet.getName());
holder.numberPickerTotalWin.setValueChangedListener(new ValueChangedListener() {
#Override
public void valueChanged(int value, ActionEnum action) {
Toast.makeText(context, position + value + " Clicked", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return listDetails.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
#BindView((R.id.nP))
NumberPicker numberPickerTotalWin;
#BindView(R.id.tvName)
TextView tvName;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
...
}
}
Check the code
YourActivity ... implements RecyclerViewItemClick
private List<Details> listDetails = new ArrayList<>();
private RecyclerAdapter viewAdapter;
#BindView(R.id.recyclerView)
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
ButterKnife.bind(this);
viewAdapter = new RecyclerAdapter(this, listDetails, this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(viewAdapter);
getMyData();
}
...
private void getMyData() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(AppConfig.URL_MAIN)
.addConverterFactory(GsonConverterFactory.create())
.build();
...
});
RecyclerViewAdapter
private RecyclerViewItemClick mListener;
public RecyclerAdapter(Context context, List<Details> listDetails, RecyclerViewItemClick listener) {
this.context = context;
this.listDetails = listDetails;
this.mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view, parent, false);
ViewHolder holder = new ViewHolder(v, mListener);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Details getSet = listDetails.get(position);
holder.tvName.setText(getSet.getName());
holder.numberPickerTotalWin.setValueChangedListener(new ValueChangedListener() {
#Override
public void valueChanged(int value, ActionEnum action) {
Toast.makeText(context, position + value + " Clicked", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return listDetails.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
#BindView((R.id.nP))
NumberPicker numberPickerTotalWin;
#BindView(R.id.tvName)
TextView tvName;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mListener != null){
//you can access to the current position if you want -> getLayoutPosition()
mListener.yourMethod();
}
}
public interface RecyclerViewItemClick {
void yourMethod();
}
}
Related
I made a recycler view inside the recycler view. And when I select the inside recycler view, the dialog is displayed, and I want to configure the recycler view in that dialog. I made a dialog and succeeded in displaying the dialog. but I don't know how to make a recycler view in a dialog. please help me.
Dialog class
public class RoomDialog extends Dialog {
private EditText etStudentName, etStudentNumber;
private Button btnConfirm, btnCancel;
private Context context;
private CustomDialogClickListener clickListener;
private Retrofit retrofit;
public EditText getEtStudentName() {
return etStudentName;
}
public EditText getEtStudentNumber() {
return etStudentNumber;
}
public Button getBtnConfirm() {
return btnConfirm;
}
public Button getBtnCancel() {
return btnCancel;
}
public RoomDialog(#NonNull Context context) {
super(context);
this.context = context;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_room);
etStudentName = findViewById(R.id.et_room_Studentname);
etStudentNumber = findViewById(R.id.et_room_studentNumber);
btnConfirm = findViewById(R.id.btn_room_confrim);
btnCancel = findViewById(R.id.btn_room_cancel);
btnConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
}) ;
btnCancel.setOnClickListener( new View.OnClickListener(){
#Override
public void onClick(View v) {
dismiss();
}
});
}
}
Inner recycler view
public class RoomAdapter extends RecyclerView.Adapter<RoomAdapter.CustomViewHolder> {
private Context context;
private ArrayList<RoomData> rooms;
public ArrayList<StudnetInRoomData> students;
private LayoutInflater inflater;
public RoomAdapter(Context context, ArrayList<RoomData> rooms) {
this.context = context;
this.rooms = rooms;
this.inflater = LayoutInflater.from(context);
students = new ArrayList<>();
}
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
view = inflater.inflate(R.layout.single_room, parent, false);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CustomViewHolder holder, int position) {
RoomData room = rooms.get(position);
holder.tvRoomNum.setText(String.valueOf(room.roomNum));
}
#Override
public int getItemCount() {
return rooms.size();
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView tvRoomNum;
public TextView tvRoomTitle;
public CustomViewHolder(View itemView) {
super(itemView);
tvRoomNum = (TextView) itemView.findViewById(R.id.tvRoomNumber);
tvRoomTitle = (TextView) itemView.findViewById(R.id.tv_room_title);
tvRoomNum.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
RoomDialog roomDialog = new RoomDialog(context);
roomDialog.setCanceledOnTouchOutside(true);
roomDialog.setCancelable(true);
roomDialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
roomDialog.show();
}
});
}
}
}
I Uploaded some data to sqlite and I want to delete each data from the recyclerview by pressing a button. so how can I achieve this? I want to get the id from recyclerview to the mainactivity then delete the data from sqlite and update reyclerview. How can I achieve this?
MainActivity
public class SelectedProblems extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selecte_problem_drawal);
mRecyclerView = (RecyclerView) findViewById(R.id.selected_problem_recycle_view); // Instantiate Recyclerview
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
selectedProblemsAdapter = new SelectedProblemsAdapter(this, getAllItems(), listener);
mRecyclerView.setAdapter(selectedProblemsAdapter);
Button remove = findviewbyid(R.id.remove);
remove.setOnClickListener(new View.OnClickListener() {
}
}
SelectedProblemsAdapter
public SelectedProblemsAdapter(Context context, Cursor cursor, OnItemClick listener) {
this.context = context;
this.cursor = cursor;
listener = listener;
}
#Override
public SelectedProblemsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.activity_selected_problems_content, null, false);
return new SelectedProblemsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SelectedProblemsViewHolder holder, final int position) {
if (this.cursor != null){
}
}
#Override
public int getItemCount() {
return (null != cursor ? cursor.getCount(): 0);
}
public void update(Cursor cursor) {
this.cursor = cursor;
notifyDataSetChanged();
}
class SelectedProblemsViewHolder extends RecyclerView.ViewHolder{
TextView selectedProblems, selectedProblemPrice, selectedProblemTotal;
Button remove_problem_from_cart;
public SelectedProblemsViewHolder(View itemView) {
super(itemView);
selectedProblems = itemView.findViewById(R.id.selected_problems);
selectedProblemPrice = itemView.findViewById(R.id.selected_problem_price);
selectedProblemTotal = itemView.findViewById(R.id.selectedProblemTotal);
remove_problem_from_cart = itemView.findViewById(R.id.remove_problem_from_cart);
}
}
}
MainActivity
public class SelectedProblems extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selecte_problem_drawal);
mRecyclerView = (RecyclerView) findViewById(R.id.selected_problem_recycle_view); // Instantiate Recyclerview
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
selectedProblemsAdapter = new SelectedProblemsAdapter(this, getAllItems(), listener);
mRecyclerView.setAdapter(selectedProblemsAdapter);
Button remove = findviewbyid(R.id.remove);
remove.setOnClickListener(new View.OnClickListener() {
}
}
SelectedProblemsAdapter
public SelectedProblemsAdapter(Context context, Cursor cursor, OnItemClick listener) {
this.context = context;
this.cursor = cursor;
listener = listener;
}
#Override
public SelectedProblemsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.activity_selected_problems_content, null, false);
return new SelectedProblemsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SelectedProblemsViewHolder holder, final int position) {
if (this.cursor != null){
// it will call your interface method which is implemented in Activity
holder.yourView_name.setOnClickListener(new View.OnClickListener() {
listener.yourmethod();
}
}
}
#Override
public int getItemCount() {
return (null != cursor ? cursor.getCount(): 0);
}
public void update(Cursor cursor) {
this.cursor = cursor;
notifyDataSetChanged();
}
class SelectedProblemsViewHolder extends RecyclerView.ViewHolder{
TextView selectedProblems, selectedProblemPrice, selectedProblemTotal;
Button remove_problem_from_cart;
public SelectedProblemsViewHolder(View itemView) {
super(itemView);
selectedProblems = itemView.findViewById(R.id.selected_problems);
selectedProblemPrice = itemView.findViewById(R.id.selected_problem_price);
selectedProblemTotal = itemView.findViewById(R.id.selectedProblemTotal);
remove_problem_from_cart = itemView.findViewById(R.id.remove_problem_from_cart);
}
}
}
You can achieve it by implementing an interface.
Step 1: Create an interface with an abstract function that takes in the type of data as its parameters.
public interface OnDataItemClickListener {
void onItemClick(YourItem yourItem);
}
Step 2: Make the activity implement the interface and override its methods.
public class SelectedProblems extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selecte_problem_drawal);
mRecyclerView = (RecyclerView) findViewById(R.id.selected_problem_recycle_view); //
//Instantiate Recyclerview
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
selectedProblemsAdapter = new SelectedProblemsAdapter(this, getAllItems());
mRecyclerView.setAdapter(selectedProblemsAdapter);
}
#Override
public void onItemClick(YourItem yourItem) {
}
Step 3: Pass the interface through the adapter's constructor.
//Global variable of the interface
private onDataItemClickListener onclickListner;
// while instatiating the adapter
selectedProblemsAdapter = new SelectedProblemsAdapter(this, getAllItems(), onClickListener);
Step 4: In the onBindViewHolder method, use the interface instance(received through the constructor) to call the methods, which will help pass the data to the main activity/ activity.
public SelectedProblemsAdapter(Context context, Cursor cursor, OnDataItemClickListener listener) {
this.context = context;
this.cursor = cursor;
listener = listener;
}
#Override
public SelectedProblemsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.activity_selected_problems_content, null, false);
return new SelectedProblemsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SelectedProblemsViewHolder holder, final int position) {
if (this.cursor != null){
holder.yourView.setOnClickListener(new View.OnClickListener() {
// onItemClick is the abstract function present in the interface.
listener.onItemClicked(" your data item ");
// here the data item/position etc, which you want to delete will be passed on to the main acticity.
}
}
}
#Override
public int getItemCount() {
return (null != cursor ? cursor.getCount(): 0);
}
public void update(Cursor cursor) {
this.cursor = cursor;
notifyDataSetChanged();
}
class SelectedProblemsViewHolder extends RecyclerView.ViewHolder{
TextView selectedProblems, selectedProblemPrice, selectedProblemTotal;
Button remove_problem_from_cart;
public SelectedProblemsViewHolder(View itemView) {
super(itemView);
selectedProblems = itemView.findViewById(R.id.selected_problems);
selectedProblemPrice = itemView.findViewById(R.id.selected_problem_price);
selectedProblemTotal = itemView.findViewById(R.id.selectedProblemTotal);
remove_problem_from_cart = itemView.findViewById(R.id.remove_problem_from_cart);
}
}
}
Step 5: Finally write the code to delete the object through the overridden interface method, in the main activity.
#Override
public void onItemClick(YourItem yourItem) {
yourItem.delete();
// you can use any number of functions to perform with your dataItem here.
selectedProblemsAdapter.update()
//call your update function here to change the list in recycler view.
}
Note: If you are using a view model and live data, you do not need to write the notifyDataSetChanged() function.The data gets updated automatically.
This will help you to delete or perform any number of operations on your data, which is passed from your adapter to the main activity.
I'm using Horizontal Recycleview to show the icon in my app. It cotains one Recycle view and one Mainactivity Class.
I'm trying to use the onClick listener method inside the adapter class but to my surprise it is not working yet all and also don't recognize intent and give cannot resolve intent symbol. so I used toast message instead but also app compile sucessfully but nothing happens.
Here is my Recycle view class
public class SnapRecyclerAdapter extends RecyclerView.Adapter<SnapRecyclerAdapter.ReyclerViewHolder> {
private LayoutInflater layoutInflater;
private Context context;
private ArrayList<Item> items;
public SnapRecyclerAdapter(Context context, ArrayList<Item> items) {
this.layoutInflater = LayoutInflater.from(context);
this.context = context;
this.items = items;
}
#Override
public ReyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View item = layoutInflater.inflate(R.layout.item_recycler_view, parent, false);
return new ReyclerViewHolder(item);
}
#Override
public void onBindViewHolder(final ReyclerViewHolder holder, int position) {
Item item = items.get(position);
holder.image.setImageResource(item.getDrawable());
holder.appName.setText(item.getName());
}
#Override
public int getItemCount() {
return items.size();
}
class ReyclerViewHolder extends RecyclerView.ViewHolder {
private ImageView image;
private TextView appName;
private ReyclerViewHolder(final View v) {
super(v);
image = (ImageView) v.findViewById(R.id.image);
appName = (TextView) v.findViewById(R.id.app_name);
context = v.getContext();
}
private View.OnClickListener Click=new View.OnClickListener(){
#Override
public void onClick(View v) {
switch(getAdapterPosition())
{
case 1:
Toast.makeText(context, "No data available", Toast.LENGTH_SHORT).show();
}
}
};
}
}
and my Mainactivity class is
public class MainActivity extends AppCompatActivity {
private ArrayList<Item> items;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
createApps();
SnapHelper snapHelper = new GravitySnapHelper(Gravity.BOTTOM);
snapHelper.attachToRecyclerView(recyclerView);
// HORIZONTAL for Gravity START/END and VERTICAL for TOP/BOTTOM
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
recyclerView.setHasFixedSize(true);
SnapRecyclerAdapter adapter = new SnapRecyclerAdapter(this, items);
recyclerView.setAdapter(adapter);
}
private void createApps() {
items = new ArrayList<>();
items.add(new Item("Google+", R.drawable.google_plus));
items.add(new Item("Facebook", R.drawable.facebook));
items.add(new Item("LinkedIn", R.drawable.linkedin));
items.add(new Item("Youtube", R.drawable.youtube));
items.add(new Item("Instagram", R.drawable.instagram));
items.add(new Item("Skype", R.drawable.skype));
items.add(new Item("Twitter", R.drawable.twitter));
items.add(new Item("Wikipedia", R.drawable.wikipedia));
items.add(new Item("Whats app", R.drawable.what_apps));
items.add(new Item("Pokemon Go", R.drawable.pokemon_go));
}
}
Your implementation setOnClickListener is not correct. You should set it for each view in RecylerView and inside that you can write your code to start an activity or show a toast, etc.
public class SnapRecyclerAdapter extends RecyclerView.Adapter<SnapRecyclerAdapter.ReyclerViewHolder> {
private LayoutInflater layoutInflater;
private Context context;
private ArrayList<Item> items;
public SnapRecyclerAdapter(Context context, ArrayList<Item> items) {
this.layoutInflater = LayoutInflater.from(context);
this.context = context;
this.items = items;
}
#Override
public ReyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View item = layoutInflater.inflate(R.layout.item_recycler_view, parent, false);
ReyclerViewHolder holder = new ReyclerViewHolder(item)
item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, items.get(holder.getAdapterPosition()).getName(), Toast.LENGTH_SHORT).show();
// TODO: You can start an activity by using Intent as well.
}
});
return holder;
}
#Override
public void onBindViewHolder(final ReyclerViewHolder holder, int position) {
Item item = items.get(position);
holder.image.setImageResource(item.getDrawable());
holder.appName.setText(item.getName());
}
#Override
public int getItemCount() {
return items.size();
}
class ReyclerViewHolder extends RecyclerView.ViewHolder {
private ImageView image;
private TextView appName;
private ReyclerViewHolder(final View v) {
super(v);
image = (ImageView) v.findViewById(R.id.image);
appName = (TextView) v.findViewById(R.id.app_name);
context = v.getContext();
}
}
}
You want the click listener on the whole itemView? Here is an example:
//Implement View.OnClickListener
class ReyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView image;
private TextView appName;
private ReyclerViewHolder(final View v) {
super(v);
image = (ImageView) v.findViewById(R.id.image);
appName = (TextView) v.findViewById(R.id.app_name);
// Set the onClickListener
v.setOnClickListener(this)
}
#Override
public void onClick(View v) {
// if (getAdapterPosition() != RecyclerView.NO_POSITION) {
Context context = v.getContext();
Intent intent = new Intent(context, aActivityClass.class);
intent.putExtra(extraKey, extraValue);
context.startActivity(intent)
// }
};
}
Do you set the click listener on a View ? Something like image.setOnClickListener(Click) ? By the way, variables should start with lowercase
you need to pass the view from adapter by using onclickListner and make and internface in adapter
this is where we are passing the view in adapter :
#Override
public void onBindViewHolder(myholder holder, final int position) {
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClick.click(position,view);
}
});
Interface for adapter onclick and activity:
public void clickItem(PartnerBankAdapter.OnItemClick onItemClick){
this.onItemClick=onItemClick;
}
public interface OnItemClick{
public void click(int postion,View view);
}
Define Interface as glocbal object in adapter:
private OnItemClick onItemClick;
Consider this example for adapter:
public class PartnerBankAdapter extends RecyclerView.Adapter<PartnerBankAdapter.myholder> {
public Context mContext;
ArrayList<String> bankname;
ArrayList<Integer> iconlist;
private OnItemClick onItemClick;
public PartnerBankAdapter(Context mContext, ArrayList<String> banklist,ArrayList<Integer> iconlist)
{
this.mContext = mContext;
this.bankname=banklist;
this.iconlist=iconlist;
}
#Override
public myholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bank_list_adpater,parent,false);
return new myholder(view);
}
#Override
public void onBindViewHolder(myholder holder, final int position) {
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClick.click(position,view);
}
});
holder.txt.setText(bankname.get(position));
holder.image.setImageResource(iconlist.get(position));
holder.txtacc.setText(bankname.get(position));
}
#Override
public int getItemCount() {
return bankname.size();
}
public static class myholder extends RecyclerView.ViewHolder {
TextView txt,txtacc;
ImageView image;
LinearLayout parent;
public myholder(View itemView) {
super(itemView);
txt= (TextView) itemView.findViewById(R.id.txbank);
image=(ImageView) itemView.findViewById(R.id.imagebank);
parent=(LinearLayout) itemView.findViewById(R.id.parent);
txtacc=(TextView) itemView.findViewById(R.id.txbankacc);
}
}
public void clickItem(PartnerBankAdapter.OnItemClick onItemClick){
this.onItemClick=onItemClick;
}
public interface OnItemClick{
public void click(int postion,View view);
}
}
and then just use onclick in your activity on recyclerview
consider code below for onclick in activity :
partnerBankAdapter.clickItem(new PartnerBankAdapter.OnItemClick() {
#Override
public void click(int postion, View view) {
}
});
I want to pass a string value from my adapter class to my fragment. I tried storing the string in a bundle. To retrieve the value i used Bundle b = getArguments(); b.getString("key") the problem is im getting a null pointer exception. Below is the code that saves the string in a bundle. So my question is how can i pass a string value from adapterA to fragmentB.
Thanks in advance.
Adapter.java
public class ToDoRecyclerViewAdapter extends RecyclerView.Adapter<ToDoRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<Aktivnost_> mValues;
private final OnListFragmentInteractionListener mListener;
public ToDoRecyclerViewAdapter td;
public ToDoRecyclerViewAdapter(List<Aktivnost_ > items, Context context, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mItem = mValues.get(position);
holder.mContentView.setText(mValues.get(position).getNaziv());
holder.mDateView.setText(mValues.get(position).getDatum());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem);
Intent i = new Intent(context.getApplicationContext(), PodrobnostiActivity.class);
i.putExtra("task_id", mValues.get(position).getId_());
context.getApplicationContext().startActivity(i);
Toast.makeText(v.getContext(), "task - " + mValues.get(position).getId_(), Toast.LENGTH_SHORT).show();
}
}
});
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getContext());
CharSequence meni[] = new CharSequence[] {"DOING", "FINISHED"};
adb.setItems(meni, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0) {
Bundle b = new Bundle();
DoingFragment d = new DoingFragment();
mValues.get(i).setStanje("doing");
b.putString("doing", mValues.get(i).getStanje());
d.setArguments(b);
} else {
mValues.get(i).setStanje("koncano");
}
}
});
AlertDialog alertDialog = adb.create();
alertDialog.setCancelable(true);
alertDialog.show();
return true;
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mContentView;
public final TextView mDateView;
public long id;
public Aktivnost_ mItem;
public ViewHolder(View view) {
super(view);
mView = view;
this.id = id;
mDateView = (TextView) view.findViewById(R.id.Date);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
And i want to get the value i set in bundle in this fragment.
Fragment.java
public class DoingFragment extends Fragment {
DoingFragmentRecyclerViewAdapter mAdapter;
private OnListFragmentInteractionListener mListener;
public DoingFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_doingfragment_list, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list_doing);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
mAdapter = new DoingFragmentRecyclerViewAdapter(listAktivnosti(),mListener);
recyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction1(Aktivnost_ item);
}
AppDatabase db;
public void openDB() {
db = new AppDatabase(getContext());
db.open();
}
Aktivnost_ ak;
List<Aktivnost_> array;
public List<Aktivnost_> listAktivnosti() {
array = new ArrayList<>();
openDB();
Bundle b = getArguments();
Cursor cursor = db.getAllRows(b.getString("doing"));
while(cursor.moveToNext()) {
ak = new Aktivnost_();
ak.setId_(cursor.getLong(cursor.getColumnIndex("_id")));
ak.setNaziv(cursor.getString(cursor.getColumnIndex("naziv")));
ak.setDatum(cursor.getString(cursor.getColumnIndex("datum")));
ak.setFk_projekt(cursor.getInt(cursor.getColumnIndex("fk_projekt")));
ak.setUdeleženci(cursor.getString(cursor.getColumnIndex("udelezenci")));
ak.setStanje(cursor.getString(cursor.getColumnIndex("stanje")));
array.add(ak);
}
return array;
}
}
From the code, I can see you are only setting the Bundle parameters in Fragment object, but not using that fragment object further.
You need to display that fragment object first, then it will reflect into your target fragment.
I need to parse JSON data into HorizontalScrollView with Retrofit2. I parsed it into ListView succesfully, but I haven't imagination how to do it into HorizontalScrollView. Google can't give me right answer.
My code with ListView below.
P.S. I want to do HorizontalScrollView instead of ListView.
Like this.
MyForecastAdapter.java
public class MyForecastAdapter extends ArrayAdapter<Forecast> {
List<Forecast> forecastList;
Context context;
private LayoutInflater inflater;
public MyForecastAdapter(Context context, List<Forecast> objects) {
super(context, 0, objects);
this.context = context;
this.inflater = LayoutInflater.from(context);
forecastList = objects;
}
#Override
public Forecast getItem(int position) {
return forecastList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
View view = inflater.inflate(R.layout.activity_row, parent, false);
viewHolder = ViewHolder.create((RelativeLayout) view);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Forecast item = getItem(position);
viewHolder.textViewTemp.setText(item.getMain().getTemp());
viewHolder.textViewHumidity.setText(item.getMain().getHumidity());
return viewHolder.relativeLayout;
}
private static class ViewHolder {
public final RelativeLayout relativeLayout;
public final TextView textViewTemp;
public final TextView textViewHumidity;
private ViewHolder(RelativeLayout relativeLayout, TextView textViewTemp, TextView textViewHumidity) {
this.relativeLayout = relativeLayout;
this.textViewTemp = textViewTemp;
this.textViewHumidity = textViewHumidity;
}
public static ViewHolder create(RelativeLayout relativeLayout) {
TextView textViewTemp = (TextView) relativeLayout.findViewById(R.id.textViewTemp);
TextView textViewHumidity = (TextView) relativeLayout.findViewById(R.id.textViewHumidity);
return new ViewHolder(relativeLayout, textViewTemp, textViewHumidity);
}
}
}
ForecastList.java
public class ForecastList {
#SerializedName("list")
#Expose
private ArrayList<Forecast> forecasts = new ArrayList<>();
public ArrayList<Forecast> getForecasts() {
return forecasts;
}
public void setForecasts(ArrayList<Forecast> forecasts) {
this.forecasts = forecasts;
}
}
Forecast.java - getters/setters.
ApiService.java
public interface ApiService {
#GET("/data/2.5/forecast?q=Kirov,ru&appid=/../")
Call<ForecastList> getMyJSON();
}
RetrofitClient.java
public class RetrofitClient {
private static final String ROOT_URL = "http://api.openweathermap.org";
private static Retrofit getRetrofitInstance() {
return new Retrofit.Builder().baseUrl(ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static ApiService getApiService() {
return getRetrofitInstance().create(ApiService.class);
}
}
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
forecastList = new ArrayList<>();
parentView = findViewById(R.id.parentLayout);
listView = (ListView) findViewById(R.id.listView);
ApiService apiService = RetrofitClient.getApiService();
Call<ForecastList> call = apiService.getMyJSON();
call.enqueue(new Callback<ForecastList>() {
#Override
public void onResponse(Call<ForecastList> call, Response<ForecastList> response) {
if (response.isSuccessful()) {
forecastList = response.body().getForecasts();
adapter = new MyForecastAdapter(MainActivity.this, forecastList);
listView.setAdapter(adapter);
} else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<ForecastList> call, Throwable t) {
}
});
}
You can use horizonatal Scroll View using Recycle View with LinearLayoutManager with constructor new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
Use this code .....
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
forecastList = new ArrayList<>();
parentView = findViewById(R.id.parentLayout);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
myList = (RecyclerView) findViewById(R.id.listView);
myList.setLayoutManager(layoutManager);
ApiService apiService = RetrofitClient.getApiService();
Call<ForecastList> call = apiService.getMyJSON();
call.enqueue(new Callback<ForecastList>() {
#Override
public void onResponse(Call<ForecastList> call, Response<ForecastList> response) {
if (response.isSuccessful()) {
forecastList = response.body().getForecasts();
adapter = new MyForecastAdapter(MainActivity.this, forecastList);
myList.setAdapter(adapter);
} else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<ForecastList> call, Throwable t) {
}
});
}
and change ListView into RecycleView in XML and in code also.....