I try to add a swipe left or right to my RecyclerView List, but I don't know what I'm doing wrong. I've tried a lot of working solutions but they don't work for me.
This is my Fragment:
import android.app.Fragment;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.util.ArrayList;
import de.christian_heinisch.studenttodo.adapters.ToDoListRecyclerViewAdapter;
import de.christian_heinisch.studenttodo.database.ToDo;
import de.christian_heinisch.studenttodo.database.ToDoDataSource;
/**
* A simple {#link Fragment} subclass.
*/
public class ToDoFragment_RV extends Fragment {
View rootview;
private ToDoDataSource dataSource_todo;
private RecyclerView mRecyclerView;
private RecyclerView new_mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerView.LayoutManager new_mLayoutManager;
private static String LOG_TAG = "RecyclerViewActivity";
public ToDoFragment_RV() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootview = inflater.inflate(R.layout.fragment_to_do_rv, container, false);
mRecyclerView = (RecyclerView) rootview.findViewById(R.id.rv);
mRecyclerView.setHasFixedSize(true);
LinearSnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(mRecyclerView);
mLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new ToDoListRecyclerViewAdapter(getContext(), getDataSet());
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setOnFlingListener(snapHelper);
RecyclerView.ItemDecoration itemDecoration =
new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
new_mRecyclerView = (RecyclerView) rootview.findViewById(R.id.rv_checked);
new_mRecyclerView.setHasFixedSize(true);
new_mLayoutManager = new LinearLayoutManager(getContext());
new_mRecyclerView.setLayoutManager(new_mLayoutManager);
mAdapter = new ToDoListRecyclerViewAdapter(getContext(), getDataSet_checked());
new_mRecyclerView.setAdapter(mAdapter);
RecyclerView.ItemDecoration newitemDecoration =
new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL);
new_mRecyclerView.addItemDecoration(newitemDecoration);
// setHasOptionsMenu(true);
FloatingActionButton fab = (FloatingActionButton) rootview.findViewById(R.id.fbToDoAdd);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((StartActivity)getContext()).DialogAddToDO();
}
});
return rootview;
}
private ArrayList<ToDo> getDataSet() {
dataSource_todo = new ToDoDataSource(getContext());
dataSource_todo.open();
ArrayList<ToDo> arrayOfToDo = null;
arrayOfToDo = dataSource_todo.getToDoForList("false");
dataSource_todo.close();
return arrayOfToDo;
}
private ArrayList<ToDo> getDataSet_checked() {
dataSource_todo = new ToDoDataSource(getContext());
dataSource_todo.open();
ArrayList<ToDo> arrayOfToDo = null;
arrayOfToDo = dataSource_todo.getToDoForList("true");
dataSource_todo.close();
return arrayOfToDo;
}
}
This is my RecyclerView Adapter
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import de.christian_heinisch.studenttodo.R;
import de.christian_heinisch.studenttodo.StartActivity;
import de.christian_heinisch.studenttodo.ToDoFragment_RV;
import de.christian_heinisch.studenttodo.database.ToDo;
import de.christian_heinisch.studenttodo.database.ToDoDataSource;
/**
* Created by chris on 16.06.2017.
*/
public class ToDoListRecyclerViewAdapter extends RecyclerView
.Adapter<ToDoListRecyclerViewAdapter
.DataObjectHolder> {
private ArrayList<ToDo> mDataset;
private static MyClickListener myClickListener;
private Context mContext;
ToDoDataSource dataSource = new ToDoDataSource(mContext);
public static class DataObjectHolder extends RecyclerView.ViewHolder
implements View
.OnClickListener {
TextView label;
TextView dateTime;
CheckBox checked;
public DataObjectHolder(View itemView) {
super(itemView);
label = (TextView) itemView.findViewById(R.id.textView_item_todolist_content);
dateTime = (TextView) itemView.findViewById(R.id.textView_item_todolist_Date);
checked = (CheckBox) itemView.findViewById(R.id.cbToDo);
//itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public ToDoListRecyclerViewAdapter(Context context, ArrayList<ToDo> myDataset) {
mDataset = myDataset;
mContext = context;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_todolist, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(final DataObjectHolder holder, final int position) {
holder.label.setText(mDataset.get(position).getToDo());
holder.dateTime.setText(getDate(mDataset.get(position).isDate()));
if(mDataset.get(position).isChecked().equalsIgnoreCase("true")){
holder.checked.toggle();
}
holder.itemView.setOnTouchListener(new View.OnTouchListener() {
float _xSwipe1;
float _xSwipe2;
#Override
public boolean onTouch(View v, MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
_xSwipe1 = event.getX();
break;
case MotionEvent.ACTION_UP:
_xSwipe2 = event.getX();
float deltaX = _xSwipe2 - _xSwipe1;
if (deltaX < 0)
{
Log.e("SWIPE", "Right to Left swipe");
}
else if (deltaX >0)
{
Log.e("SWIPE", "Left to right swipe");
}
break;
}
return false;
}
});
// Set onClicklistener
holder.label.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View view) {
System.out.println("Position " + position);
edit(mDataset.get(position).getId());
//notifyDataSetChanged();
return false;
}
});
holder.dateTime.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View view) {
edit(mDataset.get(position).getId());
return false;
}
});
holder.checked.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dataSource = new ToDoDataSource(mContext);
dataSource.open();
// TODO Auto-generated method stub
if(holder.checked.isChecked()){
System.out.println("Checked");
dataSource.updateToDo(mDataset.get(position).getId(), mDataset.get(position).getToDo(), "true", mDataset.get(position).isDate());
}else{
System.out.println("un-Checked");
dataSource.updateToDo(mDataset.get(position).getId(), mDataset.get(position).getToDo(), "false", mDataset.get(position).isDate());
}
dataSource.close();
}
});
}
public void addItem(ToDo dataObj, int index) {
mDataset.add(dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
private String getDate(long time) {
Calendar cal = Calendar.getInstance(Locale.GERMAN);
cal.setTimeInMillis(time);
String date = DateFormat.format("dd.MM.yyyy", cal).toString();
return date;
}
private void edit(long l){
((StartActivity)mContext).DialogEditToDO(l);
}
}
Return true on case MotionEvent.ACTION_DOWN may resolve your issue.
Related
I am using a recycler view. I've set an OnLongClickListener() on it using a custom interface. everything works fine but when I long-press the row the app crashes with Java.lang.IndexOutOfBoundsException. while debugging I found that my array list's data is being deleted while I long-press but the recycler view is just not getting updated.
here's my code.
MainActivity.java
package com.raunak.alarmdemo4;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Switch;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.raunak.alarmdemo4.Activities.AddAlarm;
import com.raunak.alarmdemo4.Adapters.AlarmAdapter;
import com.raunak.alarmdemo4.HelperClasses.AlarmsDBhelperClass;
import com.raunak.alarmdemo4.Interfaces.AlarmRecyclerViewInterface;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements AlarmRecyclerViewInterface {
FloatingActionButton mAlarmAddButton;
RecyclerView mRecyclerView;
SQLiteDatabase db;
AlarmsDBhelperClass mAlarmsDBhelperClass;
ArrayList<String> nameArrayList,modeArrayList,repeatArrayList,hoursArrayList,minArrayList;
Switch mSwitch;
AlarmAdapter alarmAdapter = new AlarmAdapter(hoursArrayList,minArrayList,modeArrayList,repeatArrayList,nameArrayList,this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//Initializing RecyclerView & DatabaseHelperClass and the FAB button
mAlarmsDBhelperClass = new AlarmsDBhelperClass(getApplicationContext());
mAlarmAddButton = findViewById(R.id.btnAlarmADD);
mRecyclerView = findViewById(R.id.alarmList);
mSwitch = findViewById(R.id.switchONOFF);
//Initializing ArrayList
nameArrayList = new ArrayList<>();
modeArrayList = new ArrayList<>();
repeatArrayList = new ArrayList<>();
hoursArrayList = new ArrayList<>();
minArrayList = new ArrayList<>();
DividerItemDecoration itemDecoration = new DividerItemDecoration(this,DividerItemDecoration.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
//Getting a writable reference of the Database.
db = mAlarmsDBhelperClass.getWritableDatabase();
//getAlarm(db);
getAlarm(db);
mAlarmAddButton.setImageResource(R.drawable.addalarm);
mAlarmAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent mIntent = new Intent(getApplicationContext(), AddAlarm.class);
startActivity(mIntent);
}
});
/* mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
Toast.makeText(getApplicationContext(),"Checked !",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Unchecked !",Toast.LENGTH_SHORT).show();
}
}
});*/
AlarmAdapter alarmAdapter = new AlarmAdapter(hoursArrayList,minArrayList,modeArrayList,repeatArrayList,nameArrayList,this);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mRecyclerView.setAdapter(alarmAdapter);
mRecyclerView.setHasFixedSize(true);
}
public void getAlarm(SQLiteDatabase db) {
Cursor cursor = db.rawQuery("SELECT * FROM alarms", new String[]{});
cursor.moveToFirst();
if (cursor != null) {
do {
nameArrayList.add(cursor.getString(2));
modeArrayList.add(cursor.getString(3));
repeatArrayList.add(cursor.getString(4));
hoursArrayList.add(Integer.toString(cursor.getInt(5)));
minArrayList.add(Integer.toString(cursor.getInt(6)));
} while (cursor.moveToNext());
}
cursor.close();
}
#Override
public void onItemClick(int position) {
Toast.makeText(this, "Alarm Clicked !", Toast.LENGTH_SHORT).show();
}
#Override
public void onLongItemClick(int position) {
hoursArrayList.remove(position);
Log.d("d",""+position);
alarmAdapter.notifyItemRemoved(position);
Toast.makeText(this, ""+hoursArrayList.size(), Toast.LENGTH_SHORT).show();
}
}
my Recyclerview adapter.
package com.raunak.alarmdemo4.Adapters;
import android.util.Log;
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 com.raunak.alarmdemo4.Interfaces.AlarmRecyclerViewInterface;
import com.raunak.alarmdemo4.R;
import java.util.ArrayList;
public class AlarmAdapter extends RecyclerView.Adapter<AlarmAdapter.AlarmView> {
//Variables for the main recycler view
private ArrayList<String> hoursArrayList;
private ArrayList<String> minArrayList;
private ArrayList<String> modeArrayList;
private ArrayList<String> repeatArrayList;
private ArrayList<String> nameArrayList;
private AlarmRecyclerViewInterface mInterface;
public AlarmAdapter(ArrayList<String> hours,ArrayList<String> mins,ArrayList<String> mode,ArrayList<String> repeat,ArrayList<String> name,AlarmRecyclerViewInterface mInterface){
this.hoursArrayList = hours;
this.minArrayList = mins;
this.modeArrayList = mode;
this.nameArrayList = name;
this.repeatArrayList = repeat;
this.mInterface = mInterface;
}
#NonNull
#Override
public AlarmView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.alarm_profile,parent,false);
return new AlarmView(view);
}
#Override
public void onBindViewHolder(#NonNull AlarmView holder, int position) {
if(Integer.parseInt(hoursArrayList.get(position)) < 10 ){
holder.hours.setText("0"+hoursArrayList.get(position));
}else {
holder.hours.setText(hoursArrayList.get(position));
}
if (Integer.parseInt(minArrayList.get(position)) < 10){
holder.mins.setText("0"+minArrayList.get(position));
}else {
holder.mins.setText(minArrayList.get(position));
}
holder.repeat.setText(repeatArrayList.get(position));
holder.mode.setText(modeArrayList.get(position));
holder.name.setText(nameArrayList.get(position));
}
#Override
public int getItemCount() {
return nameArrayList.size();
}
/*ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
nameArrayList.remove(viewHolder.getAdapterPosition());
modeArrayList.remove(viewHolder.getAdapterPosition());
repeatArrayList.remove(viewHolder.getAdapterPosition());
hoursArrayList.remove(viewHolder.getAdapterPosition());
minArrayList.remove(viewHolder.getAdapterPosition());
}
};*/
public class AlarmView extends RecyclerView.ViewHolder{
TextView hours,mins,repeat,name,mode;
public AlarmView(#NonNull View itemView) {
super(itemView);
hours = itemView.findViewById(R.id.txtHOUR);
mins = itemView.findViewById(R.id.txtMins);
repeat = itemView.findViewById(R.id.txtRepeatDays);
name = itemView.findViewById(R.id.txtName);
mode = itemView.findViewById(R.id.txtMode);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("d",""+getAdapterPosition());
mInterface.onItemClick(getAdapterPosition());
}
});
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Log.d("d",""+getAdapterPosition());
mInterface.onLongItemClick(getAdapterPosition());
return true;
}
});
}
}
}
my CustomInterface
package com.raunak.alarmdemo4.Interfaces;
public interface AlarmRecyclerViewInterface {
void onItemClick(int position);
void onLongItemClick(int position);
}
Thanks for help!
You should remove the element also from nameArrayList and inside your Adapter:
#Override
public int getItemCount() {
return nameArrayList.size(); //This return a number that is higher than the number of elements
}
.
//When you call this, you remove the element from the list in the Main Activity, but not in your Adapter
hoursArrayList.remove(position);
.
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
int pos = getAdapterPosition();
Log.d("d",""+ pos);
hoursArrayList.remove(pos); //I think you'd add
nameArrayList.remove(pos); //these two lines
mInterface.onLongItemClick(pos);
return true;
}
});
.
#Override
public int getItemCount() {
return hoursArrayList.size(); //Or just the first line and modify this
}
And you should modify your MainActiivty fields:
FloatingActionButton mAlarmAddButton;
RecyclerView mRecyclerView;
SQLiteDatabase db;
AlarmsDBhelperClass mAlarmsDBhelperClass;
ArrayList<String> nameArrayList,modeArrayList,repeatArrayList,hoursArrayList,minArrayList;
Switch mSwitch;
AlarmAdapter alarmAdapter = new AlarmAdapter(hoursArrayList,minArrayList,modeArrayList,repeatArrayList,nameArrayList,this);
//This line has nosense, if you re-declare another alarmAdapter in the onCreate
Your are declaring and assigning different adapter in onCreate. Remove the declaration from there and just initialize it there.
AlarmAdapter alarmAdapter = new AlarmAdapter(hoursArrayList,minArrayList,modeArrayList,repeatArrayList,nameArrayList,this);
And you need to improve your code for efficiency, create a model class instead of declaring arrrayList of every param.
I use this code in MainActivity But I can not access setOnMenuItemClickListener in MainActivity .
MainActivity class:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Toast toast ;
ImageView hahaha;
protected static int ss=77;
//recyclerview objects
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
public int xxx=222;
//model object for our list data
private List<MyList> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializing views
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
//loading list view item with this function
loadRecyclerViewItem();
}
private void loadRecyclerViewItem() {
//you can fetch the data from server or some apis
//for this tutorial I am adding some dummy data directly
for (int i = 1; i <= 7; i++) {
MyList myList = new MyList(
"Heading " + i,
"id = " + i,
"https://mediaresources.idiva.com/media//content/2014/May/diet_kids_health1.jpg",
"HHHHHH" + i
);
list.add(myList);
}
adapter = new CustomAdapter(list, this);
recyclerView.setAdapter(adapter);
}
}
and this is CustomAdaptor.class
import android.content.Context;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.List;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private List<MyList> list;
private Context mCtx;
public CustomAdapter(List<MyList> list, Context mCtx) {
this.list = list;
this.mCtx = mCtx;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_items, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final CustomAdapter.ViewHolder holder, final int position) {
MyList myList = list.get(position);
//loading the image
Glide.with(mCtx)
.load(myList.getUrl())
.into(holder.imageView);
holder.textViewHead.setText(myList.getHead());
holder.textViewDesc.setText(myList.getDesc());
//holder.textViewDesc.setText(myList.getIdofdata());
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//creating a popup menu
PopupMenu popup = new PopupMenu(mCtx, holder.buttonViewOption);
//inflating menu from xml resource
popup.inflate(R.menu.options_menu);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu1:
//handle menu1 click
holder.textViewHead.setText("moshiri" + holder.textViewHead.getText() );
break;
case R.id.menu2:
//holder.textViewHead.setText("new" + holder.textViewDesc.getText() );
holder.textViewHead.setText("mohsen hi dear");
break;
case R.id.menu3:
holder.textViewHead.setText("##################" + list.indexOf(this));
holder.textViewDesc.setText("############" + list.indexOf(this));
//MainActivity me=new MainActivity();
MainActivity.ss=77;
removeItem(3);
break;
}
return false;
}
});
//displaying the popup
popup.show();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public void removeItem(int position) {
list.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, getItemCount() );
// notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewHead;
public TextView textViewDesc;
public TextView buttonViewOption;
public ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
textViewHead = (TextView) itemView.findViewById(R.id.textViewHead);
textViewDesc = (TextView) itemView.findViewById(R.id.textViewDesc);
buttonViewOption = (TextView) itemView.findViewById(R.id.textViewOptions);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
}
}
}
In CustomAdaptor I access onclick listener in menu and button but I can not manage menu and button in MainActivity. How can I use Listener in mainActivity or how can I send changes from CustomAdaptor to mainActivity?
Use interface for this purpose. In your CustomAdapter declare that interface and in ViewHolder override the click listener method and pass items from adapter you want. Currently I am passing position only you can pass anything here. I have make changes in your code just check below.
import android.content.Context;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.List;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
protected CustomClicklistener mListener;
private List<MyList> list;
private Context mCtx;
private CustomClicklistener clickListener;
public interface CustomClicklistener {
void onItemClick(int position);
}
public CustomAdapter(List<MyList> list, Context mCtx, CustomClicklistener
clickListener) {
this.list = list;
this.mCtx = mCtx;
this.clickListener = clickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_items, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final CustomAdapter.ViewHolder holder, final int position) {
MyList myList = list.get(position);
//loading the image
Glide.with(mCtx)
.load(myList.getUrl())
.into(holder.imageView);
holder.textViewHead.setText(myList.getHead());
holder.textViewDesc.setText(myList.getDesc());
//holder.textViewDesc.setText(myList.getIdofdata());
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//creating a popup menu
PopupMenu popup = new PopupMenu(mCtx, holder.buttonViewOption);
//inflating menu from xml resource
popup.inflate(R.menu.options_menu);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu1:
//handle menu1 click
holder.textViewHead.setText("moshiri" + holder.textViewHead.getText() );
break;
case R.id.menu2:
//holder.textViewHead.setText("new" + holder.textViewDesc.getText() );
holder.textViewHead.setText("mohsen hi dear");
break;
case R.id.menu3:
holder.textViewHead.setText("##################" + list.indexOf(this));
holder.textViewDesc.setText("############" + list.indexOf(this));
//MainActivity me=new MainActivity();
MainActivity.ss=77;
removeItem(3);
break;
}
return false;
}
});
//displaying the popup
popup.show();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public void removeItem(int position) {
list.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, getItemCount() );
// notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView textViewHead;
public TextView textViewDesc;
public TextView buttonViewOption;
public ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
textViewHead = (TextView) itemView.findViewById(R.id.textViewHead);
textViewDesc = (TextView) itemView.findViewById(R.id.textViewDesc);
buttonViewOption = (TextView) itemView.findViewById(R.id.textViewOptions);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
}
#Override
public void onClick(View view) {
if (mListener != null) {
mListener.onItemClick(getAdapterPosition());
notifyDataSetChanged();
}
}
}
}
In MainActivity you can get that clicklistener like below in oncCreate METHOD AT THE END
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
CustomAdapter.CustomClicklistener clickListener;
Toast toast ;
ImageView hahaha;
protected static int ss=77;
//recyclerview objects
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
public int xxx=222;
//model object for our list data
private List<MyList> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializing views
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
//loading list view item with this function
loadRecyclerViewItem();
clickListener = new CustomAdapter.CustomClicklistener() {
#Override
public void onItemClick(int position) {
// Do what you want here
Toast.makeText(MainActivity.this, "This ... " , Toast.LENGTH_LONG).show();
}
};
}
private void loadRecyclerViewItem() {
//you can fetch the data from server or some apis
//for this tutorial I am adding some dummy data directly
for (int i = 1; i <= 7; i++) {
MyList myList = new MyList(
"Heading " + i,
"id = " + i,
"https://media.alalamtv.net/news/image/855x495//2015/02/16/alalam_635596703961833722_25f_4x3.jpg",
"HHHHHH" + i
);
list.add(myList);
}
adapter = new CustomAdapter(list, this, clickListener);
recyclerView.setAdapter(adapter);
}
}
Create an interface in your CustomAdapter class like:
CustomAdapterListener customAdapterListener;
public interface CustomAdapterListener {
void onItemClick();
}
And then in your constructor :
public CustomAdapter(List<MyList> list, Context mCtx, CustomAdapterListener customAdapterListener) {
this.list = list;
this.mCtx = mCtx;
this.customAdapterListener= customAdapterListener;
}
and trigger interface method when click event occured:
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
customAdapterListener.onItemClick();
});
And from your Activity; add your activity as listener like this :
adapter = new CustomAdapter(list, this, this);
Finally you have to implement your interface in your activity like :
public class MainActivity extends AppCompatActivity implements CustomAdapter.CustomAdapterListener
And click on red underlined text and press alt+enter, this will suggest you to implement interface methods, after confirm that warning you have onItemClick method in your activity. This method will trigger from adapter if click event is occured.
I would like to ask how will I be able to handle the NullException every time that I reach the last object in my int[] array.
Here is my InformationTab
package com.example.aldrinjohn.milktracktest;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by Aldrin John on 3/20/2017.
*/
public class InformationTab extends Fragment{
ViewPager viewPager;
CustomSwipeAdapter adapter;
Button btnTrivia,btnBenefitB,btnBenefitM,btnPump,btnStoring,btnInfo;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.informationtab, container, false);
viewPager = (ViewPager)rootView.findViewById(R.id.view_pager);
btnTrivia = (Button)rootView.findViewById(R.id.trivia);
btnTrivia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GlobalVariables.buttonClick = "trivia";
adapter = new CustomSwipeAdapter(getActivity());
viewPager.setAdapter(adapter);
}
});
btnBenefitB = (Button)rootView.findViewById(R.id.benefit_babies);
btnBenefitB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GlobalVariables.buttonClick = "benefitb";
adapter = new CustomSwipeAdapter(getActivity());
viewPager.setAdapter(adapter);
}
});
btnBenefitM = (Button)rootView.findViewById(R.id.benefit_mother);
btnBenefitM.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GlobalVariables.buttonClick = "benefitm";
adapter = new CustomSwipeAdapter(getActivity());
viewPager.setAdapter(adapter);
}
});
btnPump = (Button)rootView.findViewById(R.id.pump);
btnPump.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GlobalVariables.buttonClick = "pump";
adapter = new CustomSwipeAdapter(getActivity());
viewPager.setAdapter(adapter);
}
});
btnStoring = (Button)rootView.findViewById(R.id.storing);
btnStoring.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GlobalVariables.buttonClick = "storing";
adapter = new CustomSwipeAdapter(getActivity());
viewPager.setAdapter(adapter);
}
});
btnInfo = (Button)rootView.findViewById(R.id.tips);
btnInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GlobalVariables.buttonClick = "tips";
adapter = new CustomSwipeAdapter(getActivity());
viewPager.setAdapter(adapter);
}
});
return rootView;
}
}
and this is my
package com.example.aldrinjohn.milktracktest;
import android.content.Context;
import android.provider.ContactsContract;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.google.android.gms.ads.formats.NativeAd;
import com.google.android.gms.tagmanager.Container;
/**
* Created by Aldrin John on 3/26/2017.
*/
public class CustomSwipeAdapter extends PagerAdapter{
private int[] trivia = {R.drawable.c1,R.drawable.c2,R.drawable.c3,R.drawable.c4, R.drawable.c5,R.drawable.c6};
private int[] benefitBaby = {R.drawable.c7,R.drawable.c8,R.drawable.c9};
private int[] benefitMother = {R.drawable.c91,R.drawable.c92};
private int[] info = {R.drawable.a1,R.drawable.a2,R.drawable.a3,R.drawable.a4,R.drawable.a5,R.drawable.a6,R.drawable.a7,
R.drawable.a8,R.drawable.a9,R.drawable.a91,R.drawable.a92};
private int[] storing = {R.drawable.b1,R.drawable.b2,R.drawable.b3,R.drawable.b4};
private int[] pump = {R.drawable.a21,R.drawable.a22,R.drawable.a23,R.drawable.a24,R.drawable.a25,R.drawable.a31,R.drawable.a32,
R.drawable.a33,R.drawable.a34,R.drawable.a35,R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4,R.drawable.pic5};
private Context ctx;
private LayoutInflater layoutInflater;
public CustomSwipeAdapter(Context ctx)
{
this.ctx = ctx;
}
#Override
public int getCount() {
return pump.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view==(LinearLayout)object);
}
#Override
public Object instantiateItem(ViewGroup container, int position){
layoutInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
ImageView imgTrivia = (ImageView)item_view.findViewById(R.id.image_view);
if(GlobalVariables.buttonClick.equals("trivia"))
{
imgTrivia.setImageResource(trivia[position]);
}
else if (GlobalVariables.buttonClick.equals("benefitb"))
{
imgTrivia.setImageResource(benefitBaby[position]);
}
else if (GlobalVariables.buttonClick.equals("benefitm"))
{
imgTrivia.setImageResource(benefitMother[position]);
}
else if (GlobalVariables.buttonClick.equals("storing"))
{
imgTrivia.setImageResource(storing[position]);
}
else if (GlobalVariables.buttonClick.equals("tips"))
{
imgTrivia.setImageResource(info[position]);
}
else if (GlobalVariables.buttonClick.equals("pump"))
{
imgTrivia.setImageResource(pump[position]);
}
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object){
container.removeView((LinearLayout)object);
}
}
SOLVED! I just used a global variable class that contains the number of slides that is clicked. and return it to getCount function.
In my app is Retrofit 1.9 and RecyclerView. On startup HTTP request is sending and I receive data, but not displaying. After SwipeRefresh data are downloaded again, but before that Recycler is displaying previous data.
Fragment:
package com.example.bolek.testy.Fragments;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.widget.DefaultItemAnimator;
import android.widget.Toast;
import com.example.bolek.testy.Adapters.ChaptersAdapter;
import com.example.bolek.testy.Interfaces.WebService;
import com.example.bolek.testy.Pojo.Chapter;
import com.example.bolek.testy.R;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
import java.util.ArrayList;
import java.util.List;
public class RetrofitFragment extends Fragment {
private List<Chapter> chapterList = new ArrayList<>();
private RecyclerView recyclerView;
private ChaptersAdapter mAdapter;
RestAdapter retrofit;
WebService webService;
SwipeRefreshLayout refreshLayout;
public RetrofitFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_retrofit, container, false);
}
#Override
public void onViewCreated(View v, Bundle savedInstanceState) {
recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
refreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipeRefreshLayout);
RecyclerView.LayoutManager mLayoutManager;
int screenSize = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
//sprawdzanie rozmiaru ekranu
switch (screenSize) {
case Configuration.SCREENLAYOUT_SIZE_SMALL:
mLayoutManager = new GridLayoutManager(getActivity().getApplicationContext(), 1);
break;
case Configuration.SCREENLAYOUT_SIZE_LARGE:
case Configuration.SCREENLAYOUT_SIZE_XLARGE:
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
mLayoutManager = new GridLayoutManager(getActivity().getApplicationContext(), 5);
} else {
mLayoutManager = new GridLayoutManager(getActivity().getApplicationContext(), 4);
}
break;
default:
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
mLayoutManager = new GridLayoutManager(getActivity().getApplicationContext(), 4);
} else {
mLayoutManager = new GridLayoutManager(getActivity().getApplicationContext(), 2);
}
}
mAdapter = new ChaptersAdapter(chapterList, getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
Log.i("aaaaaaaaaaaa", "startup");
prepareData(true);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.i("aaaaaaaaaaaa", "onRefresh called from SwipeRefreshLayout");
prepareData(true);
}
});
}
private void prepareData(final boolean refresh) {
retrofit = new RestAdapter.Builder()
.setEndpoint("http://bolex.cba.pl/")
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
webService = retrofit.create(WebService.class);
try {
webService.getData(new Callback<Chapter[]>() {
#Override
public void success(Chapter[] data, Response response) {
if (refresh) {
chapterList.clear();
}
for (Chapter item : data) {
chapterList.add(item);
}
refreshLayout.setRefreshing(false);
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
Log.d("Rest", error.getLocalizedMessage());
}
});
} catch (Exception e) {
Log.d("Rest", e.toString());
}
mAdapter.notifyDataSetChanged();
}
}
Adapter:
package com.example.bolek.testy.Adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.util.List;
import com.example.bolek.testy.Pojo.Chapter;
import com.example.bolek.testy.R;
public class ChaptersAdapter extends RecyclerView.Adapter<ChaptersAdapter.MyViewHolder> {
private List<Chapter> chapterList;
private Context mContext;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView date, number, title;
private ImageView cover;
public MyViewHolder(View view) {
super(view);
date = (TextView) view.findViewById(R.id.date);
cover = (ImageView) view.findViewById(R.id.cover);
number = (TextView) view.findViewById(R.id.number);
title = (TextView) view.findViewById(R.id.title);
}
}
public ChaptersAdapter(List<Chapter> chapterList, Context mContext) {
this.chapterList = chapterList;
this.mContext = mContext;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chapter_list_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Chapter chapter = chapterList.get(position);
holder.title.setText(chapter.getTitle());
if(chapter.getDate() == null){
Log.d("aaaaaaaaaaaaaaaaaaaaa","null");
}
Glide.with(mContext).load("https://novelki.pl/uploads/"+chapter.getImage())
.thumbnail(0.5f)
.error(R.drawable.no_foto)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.cover);
holder.date.setText(chapter.getDate());
holder.number.setText("Tom " + chapter.getTomNumber() + " chapter " + chapter.getChapterNumber());
}
#Override
public int getItemCount() {
return chapterList.size();
}
}
Any idea?
P.S.
Sorry for my bad english.
I think you might not be updating you adapter when the data comes:
private void prepareData(final boolean refresh) {
#Override
public void success(Chapter[] data, Response response) {
retrofit = new RestAdapter.Builder()
.setEndpoint("http://bolex.cba.pl/")
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
webService = retrofit.create(WebService.class);
try {
webService.getData(new Callback<Chapter[]>() {
#Override
public void success(Chapter[] data, Response response) {
if (refresh) {
chapterList.clear();
}
for (Chapter item : data) {
chapterList.add(item);
}
// I JUST ADDED THIS LINE BELOW
mAdapter.notifyDataSetChanged();
refreshLayout.setRefreshing(false);
}
...
}
hi i have a recyclerview with GridLayoutManager that have 3 cols but in the first row just shows 2 items like this :
where i was wrong in this codes :
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.github.florent37.materialviewpager.MaterialViewPagerHelper;
import com.github.florent37.materialviewpager.adapter.RecyclerViewMaterialAdapter;
import java.util.ArrayList;
import java.util.List;
public class Main_Recycle6 extends Fragment {
private RecyclerView recyclerView;
private Main_Recycle_Adapter2 movieRecyclerviewAdapter;
private List<Main> movies;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
return inflater.inflate(R.layout.main_grid4, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
movies = new ArrayList<>();
recyclerView = (RecyclerView) getView().findViewById(R.id.Recycle1);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// recyclerView.setNestedScrollingEnabled(false);
RecyclerView.LayoutManager layoutManager;
layoutManager = new GridLayoutManager(getActivity(), 3);
recyclerView.setLayoutManager(layoutManager);
movies = getData();
movieRecyclerviewAdapter = new Main_Recycle_Adapter2 (getActivity(), movies);
recyclerView.setAdapter(movieRecyclerviewAdapter);
RecyclerViewMaterialAdapter movieRecyclerviewAdapterMaterial = new RecyclerViewMaterialAdapter(movieRecyclerviewAdapter);
// 4. set adapter
recyclerView.setAdapter(movieRecyclerviewAdapterMaterial);
//5. Register the recyclerview to MaterialViewPager
MaterialViewPagerHelper.registerRecyclerView(getActivity(), recyclerView, null);
}
public static Main_Recycle newInstance() {
return new Main_Recycle();
}
private List<Main> getData() {
List<Main> movies = new ArrayList<>();
String names[] = { "آزمون 1",
"آزمون 2",
.....
};
String logos[] = {"i1",
"i2",
.....
};
for (int i = 0; i < names.length; i++) {
Main newMovie = new Main(names[i], logos[i]);
movies.add(newMovie);
}
return movies;
}
adapter :
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
public class Main_Recycle_Adapter2 extends RecyclerView.Adapter<Main_Recycle_Adapter2.MovieViewHolder> {
List<Main> movies = Collections.emptyList();
LayoutInflater layoutInflater;
Context context;
public Main_Recycle_Adapter2(Context context, List<Main> movies){
this.context = context;
layoutInflater = LayoutInflater.from(context);
this.movies = movies;
}
//;;;;;;;;;;;;;;
#Override
public int getItemCount() {
return movies.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType )
{
View row;
row = layoutInflater.inflate(R.layout.gridview_custom_layout, parent, false);
MovieViewHolder holder = new MovieViewHolder(row);
return holder;
}
#Override
public void onBindViewHolder(MovieViewHolder holder, int position) {
Main thisMovie = movies.get(position);
holder.tozih.setText(thisMovie.getName());
holder.tablooo.setImageResource(context.getResources().getIdentifier(thisMovie.getLogo(), "drawable", context.getPackageName()));
}
public class MovieViewHolder extends RecyclerView.ViewHolder {
private TextView tozih;
private ImageView tablooo;
public MovieViewHolder(View itemView) {
super(itemView);
tozih = (TextView) itemView.findViewById(R.id.gridview_text);
tablooo = (ImageView) itemView.findViewById(R.id.gridview_image);
}
}
}
here is the grid code
the recyclerview is in a fragment and the fragment is in another activity
RecyclerView.LayoutManager layoutManager;
layoutManager = new GridLayoutManager(getActivity(), 3);
recyclerView.setLayoutManager(layoutManager);
thanks in advance